From 1f554c1093dde6a4d3ed80fae2675abfb6c12fac Mon Sep 17 00:00:00 2001 From: Alex Barney Date: Sun, 3 Mar 2019 19:45:25 -0600 Subject: [PATCH] Do naming refactoring on Ryujinx.Graphics (#611) * Renaming part 1 * Renaming part 2 * Renaming part 3 * Renaming part 4 * Renaming part 5 * Renaming part 6 * Renaming part 7 * Renaming part 8 * Renaming part 9 * Renaming part 10 * General cleanup * Thought I got all of these * Apply #595 * Additional renaming * Tweaks from feedback * Rename files --- Ryujinx.Graphics/CdmaProcessor.cs | 64 +- Ryujinx.Graphics/ChClassId.cs | 4 +- Ryujinx.Graphics/ChCommandEntry.cs | 8 +- Ryujinx.Graphics/DmaPusher.cs | 142 +- Ryujinx.Graphics/Gal/EmbeddedResource.cs | 10 +- Ryujinx.Graphics/Gal/GalColorF.cs | 16 +- Ryujinx.Graphics/Gal/GalFrontFace.cs | 4 +- Ryujinx.Graphics/Gal/GalImage.cs | 76 +- Ryujinx.Graphics/Gal/GalImageFormat.cs | 28 +- Ryujinx.Graphics/Gal/GalPipelineState.cs | 12 +- Ryujinx.Graphics/Gal/GalSurfaceFormat.cs | 88 +- Ryujinx.Graphics/Gal/GalTextureFormat.cs | 22 +- Ryujinx.Graphics/Gal/GalTextureSampler.cs | 36 +- Ryujinx.Graphics/Gal/GalTextureType.cs | 4 +- Ryujinx.Graphics/Gal/GalVertexAttrib.cs | 28 +- Ryujinx.Graphics/Gal/IGalConstBuffer.cs | 8 +- Ryujinx.Graphics/Gal/IGalMemory.cs | 4 +- Ryujinx.Graphics/Gal/IGalPipeline.cs | 6 +- Ryujinx.Graphics/Gal/IGalRasterizer.cs | 34 +- Ryujinx.Graphics/Gal/IGalRenderTarget.cs | 46 +- Ryujinx.Graphics/Gal/IGalRenderer.cs | 2 +- Ryujinx.Graphics/Gal/IGalShader.cs | 12 +- Ryujinx.Graphics/Gal/IGalTexture.cs | 10 +- .../Gal/OpenGL/DeleteValueCallback.cs | 2 +- Ryujinx.Graphics/Gal/OpenGL/ImageHandler.cs | 6 +- .../Gal/OpenGL/OGLCachedResource.cs | 191 --- Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs | 74 - Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs | 70 - Ryujinx.Graphics/Gal/OpenGL/OGLLimit.cs | 12 - Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs | 207 --- .../Gal/OpenGL/OGLRenderTarget.cs | 549 ------- Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs | 58 - Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs | 298 ---- .../Gal/OpenGL/OGLShaderProgram.cs | 86 - Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs | 381 ----- .../Gal/OpenGL/OglCachedResource.cs | 191 +++ Ryujinx.Graphics/Gal/OpenGL/OglConstBuffer.cs | 74 + ...GLEnumConverter.cs => OglEnumConverter.cs} | 192 +-- Ryujinx.Graphics/Gal/OpenGL/OglExtension.cs | 70 + Ryujinx.Graphics/Gal/OpenGL/OglLimit.cs | 12 + .../OpenGL/{OGLPipeline.cs => OglPipeline.cs} | 490 +++--- Ryujinx.Graphics/Gal/OpenGL/OglRasterizer.cs | 207 +++ .../Gal/OpenGL/OglRenderTarget.cs | 549 +++++++ Ryujinx.Graphics/Gal/OpenGL/OglRenderer.cs | 58 + Ryujinx.Graphics/Gal/OpenGL/OglShader.cs | 298 ++++ .../Gal/OpenGL/OglShaderProgram.cs | 86 + ...{OGLStreamBuffer.cs => OglStreamBuffer.cs} | 24 +- Ryujinx.Graphics/Gal/OpenGL/OglTexture.cs | 381 +++++ Ryujinx.Graphics/Gal/Shader/GlslDecl.cs | 263 ++-- Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs | 1234 +++++++-------- Ryujinx.Graphics/Gal/Shader/GlslProgram.cs | 12 +- .../Gal/Shader/ShaderDecodeAlu.cs | 1206 +++++++------- .../Gal/Shader/ShaderDecodeFlow.cs | 32 +- .../Gal/Shader/ShaderDecodeFunc.cs | 2 +- .../Gal/Shader/ShaderDecodeHelper.cs | 58 +- .../Gal/Shader/ShaderDecodeMem.cs | 696 ++++----- .../Gal/Shader/ShaderDecodeMove.cs | 352 ++--- .../Gal/Shader/ShaderDecodeOpCode.cs | 224 +-- .../Gal/Shader/ShaderDecodeSpecial.cs | 18 +- Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs | 170 +- Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs | 92 +- Ryujinx.Graphics/Gal/Shader/ShaderIrAsg.cs | 6 +- Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs | 8 +- Ryujinx.Graphics/Gal/Shader/ShaderIrCmnt.cs | 4 +- Ryujinx.Graphics/Gal/Shader/ShaderIrCond.cs | 8 +- .../Gal/Shader/ShaderIrMetaIpa.cs | 4 +- .../Gal/Shader/ShaderIrMetaTex.cs | 10 +- .../Gal/Shader/ShaderIrMetaTexq.cs | 6 +- Ryujinx.Graphics/Gal/Shader/ShaderIrOp.cs | 20 +- .../Gal/Shader/ShaderIrOperAbuf.cs | 6 +- .../Gal/Shader/ShaderIrOperCbuf.cs | 8 +- .../Gal/Shader/ShaderIrOperGpr.cs | 20 +- .../Gal/Shader/ShaderIrOperImm.cs | 4 +- .../Gal/Shader/ShaderIrOperImmf.cs | 4 +- .../Gal/Shader/ShaderIrOperPred.cs | 4 +- .../Gal/Shader/ShaderOpCodeTable.cs | 62 +- Ryujinx.Graphics/Gal/Shader/ShaderOper.cs | 6 +- Ryujinx.Graphics/Gal/ShaderDeclInfo.cs | 34 +- Ryujinx.Graphics/Gal/ShaderDumper.cs | 76 +- Ryujinx.Graphics/Gal/ShaderException.cs | 2 +- Ryujinx.Graphics/GpuMethodCall.cs | 16 +- Ryujinx.Graphics/GpuResourceManager.cs | 116 +- Ryujinx.Graphics/Graphics3d/INvGpuEngine.cs | 2 +- .../Graphics3d/MacroInterpreter.cs | 230 +-- Ryujinx.Graphics/Graphics3d/NvGpuEngine2d.cs | 277 ++-- Ryujinx.Graphics/Graphics3d/NvGpuEngine3d.cs | 973 ++++++------ .../Graphics3d/NvGpuEngine3dReg.cs | 4 +- .../Graphics3d/NvGpuEngineM2mf.cs | 185 ++- .../Graphics3d/NvGpuEngineP2mf.cs | 141 +- Ryujinx.Graphics/Graphics3d/NvGpuFifo.cs | 120 +- Ryujinx.Graphics/Graphics3d/NvGpuMethod.cs | 2 +- .../Graphics3d/Texture/ASTCDecoder.cs | 1385 ----------------- .../Graphics3d/Texture/ASTCPixel.cs | 138 -- .../Graphics3d/Texture/AstcDecoder.cs | 1385 +++++++++++++++++ .../Graphics3d/Texture/AstcPixel.cs | 138 ++ .../Graphics3d/Texture/BitArrayStream.cs | 90 +- .../Graphics3d/Texture/BlockLinearSwizzle.cs | 180 +-- .../Graphics3d/Texture/ISwizzle.cs | 8 +- .../Graphics3d/Texture/ImageUtils.cs | 409 +++-- .../Graphics3d/Texture/IntegerEncoded.cs | 204 +-- .../Graphics3d/Texture/LinearSwizzle.cs | 34 +- .../Graphics3d/Texture/TextureFactory.cs | 188 +-- .../Graphics3d/Texture/TextureHelper.cs | 46 +- .../Graphics3d/Texture/TextureSwizzle.cs | 2 +- Ryujinx.Graphics/Memory/NvGpuVmm.cs | 308 ++-- Ryujinx.Graphics/Memory/NvGpuVmmCache.cs | 10 +- Ryujinx.Graphics/NvGpu.cs | 16 +- Ryujinx.Graphics/QuadHelper.cs | 52 +- .../Texture/TextureInstructionSuffix.cs | 16 +- Ryujinx.Graphics/VDec/BitStreamWriter.cs | 56 +- Ryujinx.Graphics/VDec/DecoderHelper.cs | 10 +- Ryujinx.Graphics/VDec/FFmpeg.cs | 106 +- Ryujinx.Graphics/VDec/H264BitStreamWriter.cs | 54 +- Ryujinx.Graphics/VDec/H264Decoder.cs | 278 ++-- Ryujinx.Graphics/VDec/VideoDecoder.cs | 284 ++-- Ryujinx.Graphics/VDec/Vp9Decoder.cs | 580 +++---- Ryujinx.Graphics/VDec/VpxBitStreamWriter.cs | 26 +- Ryujinx.Graphics/VDec/VpxRangeEncoder.cs | 92 +- Ryujinx.Graphics/Vic/StructUnpacker.cs | 52 +- Ryujinx.Graphics/Vic/SurfaceOutputConfig.cs | 28 +- Ryujinx.Graphics/Vic/SurfacePixelFormat.cs | 4 +- Ryujinx.Graphics/Vic/VideoImageComposer.cs | 96 +- Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs | 10 +- Ryujinx.sln.DotSettings | 7 + Ryujinx/Program.cs | 2 +- 125 files changed, 9121 insertions(+), 9120 deletions(-) delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLCachedResource.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLLimit.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLRenderTarget.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLShaderProgram.cs delete mode 100644 Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglCachedResource.cs create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglConstBuffer.cs rename Ryujinx.Graphics/Gal/OpenGL/{OGLEnumConverter.cs => OglEnumConverter.cs} (79%) create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglExtension.cs create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglLimit.cs rename Ryujinx.Graphics/Gal/OpenGL/{OGLPipeline.cs => OglPipeline.cs} (56%) create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglRasterizer.cs create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglRenderTarget.cs create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglRenderer.cs create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglShader.cs create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglShaderProgram.cs rename Ryujinx.Graphics/Gal/OpenGL/{OGLStreamBuffer.cs => OglStreamBuffer.cs} (51%) create mode 100644 Ryujinx.Graphics/Gal/OpenGL/OglTexture.cs delete mode 100644 Ryujinx.Graphics/Graphics3d/Texture/ASTCDecoder.cs delete mode 100644 Ryujinx.Graphics/Graphics3d/Texture/ASTCPixel.cs create mode 100644 Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs create mode 100644 Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs diff --git a/Ryujinx.Graphics/CdmaProcessor.cs b/Ryujinx.Graphics/CdmaProcessor.cs index 4ebf2007..4ff12fbf 100644 --- a/Ryujinx.Graphics/CdmaProcessor.cs +++ b/Ryujinx.Graphics/CdmaProcessor.cs @@ -8,41 +8,41 @@ namespace Ryujinx.Graphics private const int MethSetMethod = 0x10; private const int MethSetData = 0x11; - private NvGpu Gpu; + private NvGpu _gpu; - public CdmaProcessor(NvGpu Gpu) + public CdmaProcessor(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; } - public void PushCommands(NvGpuVmm Vmm, int[] CmdBuffer) + public void PushCommands(NvGpuVmm vmm, int[] cmdBuffer) { - List Commands = new List(); + List commands = new List(); - ChClassId CurrentClass = 0; + ChClassId currentClass = 0; - for (int Index = 0; Index < CmdBuffer.Length; Index++) + for (int index = 0; index < cmdBuffer.Length; index++) { - int Cmd = CmdBuffer[Index]; + int cmd = cmdBuffer[index]; - int Value = (Cmd >> 0) & 0xffff; - int MethodOffset = (Cmd >> 16) & 0xfff; + int value = (cmd >> 0) & 0xffff; + int methodOffset = (cmd >> 16) & 0xfff; - ChSubmissionMode SubmissionMode = (ChSubmissionMode)((Cmd >> 28) & 0xf); + ChSubmissionMode submissionMode = (ChSubmissionMode)((cmd >> 28) & 0xf); - switch (SubmissionMode) + switch (submissionMode) { - case ChSubmissionMode.SetClass: CurrentClass = (ChClassId)(Value >> 6); break; + case ChSubmissionMode.SetClass: currentClass = (ChClassId)(value >> 6); break; case ChSubmissionMode.Incrementing: { - int Count = Value; + int count = value; - for (int ArgIdx = 0; ArgIdx < Count; ArgIdx++) + for (int argIdx = 0; argIdx < count; argIdx++) { - int Argument = CmdBuffer[++Index]; + int argument = cmdBuffer[++index]; - Commands.Add(new ChCommand(CurrentClass, MethodOffset + ArgIdx, Argument)); + commands.Add(new ChCommand(currentClass, methodOffset + argIdx, argument)); } break; @@ -50,44 +50,44 @@ namespace Ryujinx.Graphics case ChSubmissionMode.NonIncrementing: { - int Count = Value; + int count = value; - int[] Arguments = new int[Count]; + int[] arguments = new int[count]; - for (int ArgIdx = 0; ArgIdx < Count; ArgIdx++) + for (int argIdx = 0; argIdx < count; argIdx++) { - Arguments[ArgIdx] = CmdBuffer[++Index]; + arguments[argIdx] = cmdBuffer[++index]; } - Commands.Add(new ChCommand(CurrentClass, MethodOffset, Arguments)); + commands.Add(new ChCommand(currentClass, methodOffset, arguments)); break; } } } - ProcessCommands(Vmm, Commands.ToArray()); + ProcessCommands(vmm, commands.ToArray()); } - private void ProcessCommands(NvGpuVmm Vmm, ChCommand[] Commands) + private void ProcessCommands(NvGpuVmm vmm, ChCommand[] commands) { - int MethodOffset = 0; + int methodOffset = 0; - foreach (ChCommand Command in Commands) + foreach (ChCommand command in commands) { - switch (Command.MethodOffset) + switch (command.MethodOffset) { - case MethSetMethod: MethodOffset = Command.Arguments[0]; break; + case MethSetMethod: methodOffset = command.Arguments[0]; break; case MethSetData: { - if (Command.ClassId == ChClassId.NvDec) + if (command.ClassId == ChClassId.NvDec) { - Gpu.VideoDecoder.Process(Vmm, MethodOffset, Command.Arguments); + _gpu.VideoDecoder.Process(vmm, methodOffset, command.Arguments); } - else if (Command.ClassId == ChClassId.GraphicsVic) + else if (command.ClassId == ChClassId.GraphicsVic) { - Gpu.VideoImageComposer.Process(Vmm, MethodOffset, Command.Arguments); + _gpu.VideoImageComposer.Process(vmm, methodOffset, command.Arguments); } break; diff --git a/Ryujinx.Graphics/ChClassId.cs b/Ryujinx.Graphics/ChClassId.cs index 7b74c6fb..115f0b89 100644 --- a/Ryujinx.Graphics/ChClassId.cs +++ b/Ryujinx.Graphics/ChClassId.cs @@ -2,7 +2,7 @@ namespace Ryujinx.Graphics { enum ChClassId { - Host1x = 0x1, + Host1X = 0x1, VideoEncodeMpeg = 0x20, VideoEncodeNvEnc = 0x21, VideoStreamingVi = 0x30, @@ -10,7 +10,7 @@ namespace Ryujinx.Graphics VideoStreamingIspB = 0x34, VideoStreamingViI2c = 0x36, GraphicsVic = 0x5d, - Graphics3d = 0x60, + Graphics3D = 0x60, GraphicsGpu = 0x61, Tsec = 0xe0, TsecB = 0xe1, diff --git a/Ryujinx.Graphics/ChCommandEntry.cs b/Ryujinx.Graphics/ChCommandEntry.cs index 9001fab1..b01b77ed 100644 --- a/Ryujinx.Graphics/ChCommandEntry.cs +++ b/Ryujinx.Graphics/ChCommandEntry.cs @@ -8,11 +8,11 @@ namespace Ryujinx.Graphics public int[] Arguments { get; private set; } - public ChCommand(ChClassId ClassId, int MethodOffset, params int[] Arguments) + public ChCommand(ChClassId classId, int methodOffset, params int[] arguments) { - this.ClassId = ClassId; - this.MethodOffset = MethodOffset; - this.Arguments = Arguments; + ClassId = classId; + MethodOffset = methodOffset; + Arguments = arguments; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/DmaPusher.cs b/Ryujinx.Graphics/DmaPusher.cs index 608d8a1d..c6825aba 100644 --- a/Ryujinx.Graphics/DmaPusher.cs +++ b/Ryujinx.Graphics/DmaPusher.cs @@ -6,10 +6,10 @@ namespace Ryujinx.Graphics { public class DmaPusher { - private ConcurrentQueue<(NvGpuVmm, long)> IbBuffer; + private ConcurrentQueue<(NvGpuVmm, long)> _ibBuffer; - private long DmaPut; - private long DmaGet; + private long _dmaPut; + private long _dmaGet; private struct DmaState { @@ -21,43 +21,43 @@ namespace Ryujinx.Graphics public int LengthPending; } - private DmaState State; + private DmaState _state; - private bool SliEnable; - private bool SliActive; + private bool _sliEnable; + private bool _sliActive; - private bool IbEnable; - private bool NonMain; + private bool _ibEnable; + private bool _nonMain; - private long DmaMGet; + private long _dmaMGet; - private NvGpuVmm Vmm; + private NvGpuVmm _vmm; - private NvGpu Gpu; + private NvGpu _gpu; - private AutoResetEvent Event; + private AutoResetEvent _event; - public DmaPusher(NvGpu Gpu) + public DmaPusher(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; - IbBuffer = new ConcurrentQueue<(NvGpuVmm, long)>(); + _ibBuffer = new ConcurrentQueue<(NvGpuVmm, long)>(); - IbEnable = true; + _ibEnable = true; - Event = new AutoResetEvent(false); + _event = new AutoResetEvent(false); } - public void Push(NvGpuVmm Vmm, long Entry) + public void Push(NvGpuVmm vmm, long entry) { - IbBuffer.Enqueue((Vmm, Entry)); + _ibBuffer.Enqueue((vmm, entry)); - Event.Set(); + _event.Set(); } public bool WaitForCommands() { - return Event.WaitOne(8); + return _event.WaitOne(8); } public void DispatchCalls() @@ -67,101 +67,101 @@ namespace Ryujinx.Graphics private bool Step() { - if (DmaGet != DmaPut) + if (_dmaGet != _dmaPut) { - int Word = Vmm.ReadInt32(DmaGet); + int word = _vmm.ReadInt32(_dmaGet); - DmaGet += 4; + _dmaGet += 4; - if (!NonMain) + if (!_nonMain) { - DmaMGet = DmaGet; + _dmaMGet = _dmaGet; } - if (State.LengthPending != 0) + if (_state.LengthPending != 0) { - State.LengthPending = 0; - State.MethodCount = Word & 0xffffff; + _state.LengthPending = 0; + _state.MethodCount = word & 0xffffff; } - else if (State.MethodCount != 0) + else if (_state.MethodCount != 0) { - if (!SliEnable || SliActive) + if (!_sliEnable || _sliActive) { - CallMethod(Word); + CallMethod(word); } - if (!State.NonIncrementing) + if (!_state.NonIncrementing) { - State.Method++; + _state.Method++; } - if (State.IncrementOnce) + if (_state.IncrementOnce) { - State.NonIncrementing = true; + _state.NonIncrementing = true; } - State.MethodCount--; + _state.MethodCount--; } else { - int SumissionMode = (Word >> 29) & 7; + int sumissionMode = (word >> 29) & 7; - switch (SumissionMode) + switch (sumissionMode) { case 1: //Incrementing. - SetNonImmediateState(Word); + SetNonImmediateState(word); - State.NonIncrementing = false; - State.IncrementOnce = false; + _state.NonIncrementing = false; + _state.IncrementOnce = false; break; case 3: //Non-incrementing. - SetNonImmediateState(Word); + SetNonImmediateState(word); - State.NonIncrementing = true; - State.IncrementOnce = false; + _state.NonIncrementing = true; + _state.IncrementOnce = false; break; case 4: //Immediate. - State.Method = (Word >> 0) & 0x1fff; - State.SubChannel = (Word >> 13) & 7; - State.NonIncrementing = true; - State.IncrementOnce = false; + _state.Method = (word >> 0) & 0x1fff; + _state.SubChannel = (word >> 13) & 7; + _state.NonIncrementing = true; + _state.IncrementOnce = false; - CallMethod((Word >> 16) & 0x1fff); + CallMethod((word >> 16) & 0x1fff); break; case 5: //Increment-once. - SetNonImmediateState(Word); + SetNonImmediateState(word); - State.NonIncrementing = false; - State.IncrementOnce = true; + _state.NonIncrementing = false; + _state.IncrementOnce = true; break; } } } - else if (IbEnable && IbBuffer.TryDequeue(out (NvGpuVmm Vmm, long Entry) Tuple)) + else if (_ibEnable && _ibBuffer.TryDequeue(out (NvGpuVmm Vmm, long Entry) tuple)) { - this.Vmm = Tuple.Vmm; + _vmm = tuple.Vmm; - long Entry = Tuple.Entry; + long entry = tuple.Entry; - int Length = (int)(Entry >> 42) & 0x1fffff; + int length = (int)(entry >> 42) & 0x1fffff; - DmaGet = Entry & 0xfffffffffc; - DmaPut = DmaGet + Length * 4; + _dmaGet = entry & 0xfffffffffc; + _dmaPut = _dmaGet + length * 4; - NonMain = (Entry & (1L << 41)) != 0; + _nonMain = (entry & (1L << 41)) != 0; - Gpu.ResourceManager.ClearPbCache(); + _gpu.ResourceManager.ClearPbCache(); } else { @@ -171,20 +171,20 @@ namespace Ryujinx.Graphics return true; } - private void SetNonImmediateState(int Word) + private void SetNonImmediateState(int word) { - State.Method = (Word >> 0) & 0x1fff; - State.SubChannel = (Word >> 13) & 7; - State.MethodCount = (Word >> 16) & 0x1fff; + _state.Method = (word >> 0) & 0x1fff; + _state.SubChannel = (word >> 13) & 7; + _state.MethodCount = (word >> 16) & 0x1fff; } - private void CallMethod(int Argument) + private void CallMethod(int argument) { - Gpu.Fifo.CallMethod(Vmm, new GpuMethodCall( - State.Method, - Argument, - State.SubChannel, - State.MethodCount)); + _gpu.Fifo.CallMethod(_vmm, new GpuMethodCall( + _state.Method, + argument, + _state.SubChannel, + _state.MethodCount)); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/EmbeddedResource.cs b/Ryujinx.Graphics/Gal/EmbeddedResource.cs index 45b77da7..ba662499 100644 --- a/Ryujinx.Graphics/Gal/EmbeddedResource.cs +++ b/Ryujinx.Graphics/Gal/EmbeddedResource.cs @@ -5,15 +5,15 @@ namespace Ryujinx.Graphics.Gal { static class EmbeddedResource { - public static string GetString(string Name) + public static string GetString(string name) { - Assembly Asm = typeof(EmbeddedResource).Assembly; + Assembly asm = typeof(EmbeddedResource).Assembly; - using (Stream ResStream = Asm.GetManifestResourceStream(Name)) + using (Stream resStream = asm.GetManifestResourceStream(name)) { - StreamReader Reader = new StreamReader(ResStream); + StreamReader reader = new StreamReader(resStream); - return Reader.ReadToEnd(); + return reader.ReadToEnd(); } } } diff --git a/Ryujinx.Graphics/Gal/GalColorF.cs b/Ryujinx.Graphics/Gal/GalColorF.cs index 7cfb171d..e915870c 100644 --- a/Ryujinx.Graphics/Gal/GalColorF.cs +++ b/Ryujinx.Graphics/Gal/GalColorF.cs @@ -8,15 +8,15 @@ namespace Ryujinx.Graphics.Gal public float Alpha { get; private set; } public GalColorF( - float Red, - float Green, - float Blue, - float Alpha) + float red, + float green, + float blue, + float alpha) { - this.Red = Red; - this.Green = Green; - this.Blue = Blue; - this.Alpha = Alpha; + Red = red; + Green = green; + Blue = blue; + Alpha = alpha; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/GalFrontFace.cs b/Ryujinx.Graphics/Gal/GalFrontFace.cs index 17ad1126..6cc4a802 100644 --- a/Ryujinx.Graphics/Gal/GalFrontFace.cs +++ b/Ryujinx.Graphics/Gal/GalFrontFace.cs @@ -2,7 +2,7 @@ { public enum GalFrontFace { - CW = 0x900, - CCW = 0x901 + Cw = 0x900, + Ccw = 0x901 } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/GalImage.cs b/Ryujinx.Graphics/Gal/GalImage.cs index fb904b09..1345704d 100644 --- a/Ryujinx.Graphics/Gal/GalImage.cs +++ b/Ryujinx.Graphics/Gal/GalImage.cs @@ -25,63 +25,63 @@ namespace Ryujinx.Graphics.Gal public GalTextureTarget TextureTarget; public GalImage( - int Width, - int Height, - int Depth, - int LayerCount, - int TileWidth, - int GobBlockHeight, - int GobBlockDepth, - GalMemoryLayout Layout, - GalImageFormat Format, - GalTextureTarget TextureTarget, - int MaxMipmapLevel = 1, - GalTextureSource XSource = GalTextureSource.Red, - GalTextureSource YSource = GalTextureSource.Green, - GalTextureSource ZSource = GalTextureSource.Blue, - GalTextureSource WSource = GalTextureSource.Alpha) + int width, + int height, + int depth, + int layerCount, + int tileWidth, + int gobBlockHeight, + int gobBlockDepth, + GalMemoryLayout layout, + GalImageFormat format, + GalTextureTarget textureTarget, + int maxMipmapLevel = 1, + GalTextureSource xSource = GalTextureSource.Red, + GalTextureSource ySource = GalTextureSource.Green, + GalTextureSource zSource = GalTextureSource.Blue, + GalTextureSource wSource = GalTextureSource.Alpha) { - this.Width = Width; - this.Height = Height; - this.LayerCount = LayerCount; - this.Depth = Depth; - this.TileWidth = TileWidth; - this.GobBlockHeight = GobBlockHeight; - this.GobBlockDepth = GobBlockDepth; - this.Layout = Layout; - this.Format = Format; - this.MaxMipmapLevel = MaxMipmapLevel; - this.XSource = XSource; - this.YSource = YSource; - this.ZSource = ZSource; - this.WSource = WSource; - this.TextureTarget = TextureTarget; + Width = width; + Height = height; + LayerCount = layerCount; + Depth = depth; + TileWidth = tileWidth; + GobBlockHeight = gobBlockHeight; + GobBlockDepth = gobBlockDepth; + Layout = layout; + Format = format; + MaxMipmapLevel = maxMipmapLevel; + XSource = xSource; + YSource = ySource; + ZSource = zSource; + WSource = wSource; + TextureTarget = textureTarget; - Pitch = ImageUtils.GetPitch(Format, Width); + Pitch = ImageUtils.GetPitch(format, width); } - public bool SizeMatches(GalImage Image, bool IgnoreLayer = false) + public bool SizeMatches(GalImage image, bool ignoreLayer = false) { if (ImageUtils.GetBytesPerPixel(Format) != - ImageUtils.GetBytesPerPixel(Image.Format)) + ImageUtils.GetBytesPerPixel(image.Format)) { return false; } if (ImageUtils.GetAlignedWidth(this) != - ImageUtils.GetAlignedWidth(Image)) + ImageUtils.GetAlignedWidth(image)) { return false; } - bool Result = Height == Image.Height && Depth == Image.Depth; + bool result = Height == image.Height && Depth == image.Depth; - if (!IgnoreLayer) + if (!ignoreLayer) { - Result = Result && LayerCount == Image.LayerCount; + result = result && LayerCount == image.LayerCount; } - return Result; + return result; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/GalImageFormat.cs b/Ryujinx.Graphics/Gal/GalImageFormat.cs index 70998d11..8dcde182 100644 --- a/Ryujinx.Graphics/Gal/GalImageFormat.cs +++ b/Ryujinx.Graphics/Gal/GalImageFormat.cs @@ -22,23 +22,23 @@ namespace Ryujinx.Graphics.Gal Astc2D12x12, Astc2DEnd, - RGBA4, - RGB565, - BGR565, - BGR5A1, - RGB5A1, + Rgba4, + Rgb565, + Bgr565, + Bgr5A1, + Rgb5A1, R8, - RG8, - RGBX8, - RGBA8, - BGRA8, - RGB10A2, + Rg8, + Rgbx8, + Rgba8, + Bgra8, + Rgb10A2, R16, - RG16, - RGBA16, + Rg16, + Rgba16, R32, - RG32, - RGBA32, + Rg32, + Rgba32, R11G11B10, D16, D24, diff --git a/Ryujinx.Graphics/Gal/GalPipelineState.cs b/Ryujinx.Graphics/Gal/GalPipelineState.cs index 8deb68b4..c044a55f 100644 --- a/Ryujinx.Graphics/Gal/GalPipelineState.cs +++ b/Ryujinx.Graphics/Gal/GalPipelineState.cs @@ -2,7 +2,7 @@ { public struct ColorMaskState { - private static readonly ColorMaskState _Default = new ColorMaskState() + private static readonly ColorMaskState DefaultBackingField = new ColorMaskState() { Red = true, Green = true, @@ -10,7 +10,7 @@ Alpha = true }; - public static ColorMaskState Default => _Default; + public static ColorMaskState Default => DefaultBackingField; public bool Red; public bool Green; @@ -20,7 +20,7 @@ public struct BlendState { - private static readonly BlendState _Default = new BlendState() + private static readonly BlendState DefaultBackingField = new BlendState() { Enabled = false, SeparateAlpha = false, @@ -32,7 +32,7 @@ FuncDstAlpha = GalBlendFactor.Zero }; - public static BlendState Default => _Default; + public static BlendState Default => DefaultBackingField; public bool Enabled; public bool SeparateAlpha; @@ -111,9 +111,9 @@ { ConstBufferKeys = new long[Stages][]; - for (int Stage = 0; Stage < Stages; Stage++) + for (int stage = 0; stage < Stages; stage++) { - ConstBufferKeys[Stage] = new long[ConstBuffersPerStage]; + ConstBufferKeys[stage] = new long[ConstBuffersPerStage]; } Blends = new BlendState[RenderTargetsCount]; diff --git a/Ryujinx.Graphics/Gal/GalSurfaceFormat.cs b/Ryujinx.Graphics/Gal/GalSurfaceFormat.cs index 08bd622b..9cebcc27 100644 --- a/Ryujinx.Graphics/Gal/GalSurfaceFormat.cs +++ b/Ryujinx.Graphics/Gal/GalSurfaceFormat.cs @@ -4,48 +4,48 @@ { Bitmap = 0x1c, Unknown1D = 0x1d, - RGBA32Float = 0xc0, - RGBA32Sint = 0xc1, - RGBA32Uint = 0xc2, - RGBX32Float = 0xc3, - RGBX32Sint = 0xc4, - RGBX32Uint = 0xc5, - RGBA16Unorm = 0xc6, - RGBA16Snorm = 0xc7, - RGBA16Sint = 0xc8, - RGBA16Uint = 0xc9, - RGBA16Float = 0xca, - RG32Float = 0xcb, - RG32Sint = 0xcc, - RG32Uint = 0xcd, - RGBX16Float = 0xce, - BGRA8Unorm = 0xcf, - BGRA8Srgb = 0xd0, - RGB10A2Unorm = 0xd1, - RGB10A2Uint = 0xd2, - RGBA8Unorm = 0xd5, - RGBA8Srgb = 0xd6, - RGBA8Snorm = 0xd7, - RGBA8Sint = 0xd8, - RGBA8Uint = 0xd9, - RG16Unorm = 0xda, - RG16Snorm = 0xdb, - RG16Sint = 0xdc, - RG16Uint = 0xdd, - RG16Float = 0xde, - BGR10A2Unorm = 0xdf, + Rgba32Float = 0xc0, + Rgba32Sint = 0xc1, + Rgba32Uint = 0xc2, + Rgbx32Float = 0xc3, + Rgbx32Sint = 0xc4, + Rgbx32Uint = 0xc5, + Rgba16Unorm = 0xc6, + Rgba16Snorm = 0xc7, + Rgba16Sint = 0xc8, + Rgba16Uint = 0xc9, + Rgba16Float = 0xca, + Rg32Float = 0xcb, + Rg32Sint = 0xcc, + Rg32Uint = 0xcd, + Rgbx16Float = 0xce, + Bgra8Unorm = 0xcf, + Bgra8Srgb = 0xd0, + Rgb10A2Unorm = 0xd1, + Rgb10A2Uint = 0xd2, + Rgba8Unorm = 0xd5, + Rgba8Srgb = 0xd6, + Rgba8Snorm = 0xd7, + Rgba8Sint = 0xd8, + Rgba8Uint = 0xd9, + Rg16Unorm = 0xda, + Rg16Snorm = 0xdb, + Rg16Sint = 0xdc, + Rg16Uint = 0xdd, + Rg16Float = 0xde, + Bgr10A2Unorm = 0xdf, R11G11B10Float = 0xe0, R32Sint = 0xe3, R32Uint = 0xe4, R32Float = 0xe5, - BGRX8Unorm = 0xe6, - BGRX8Srgb = 0xe7, + Bgrx8Unorm = 0xe6, + Bgrx8Srgb = 0xe7, B5G6R5Unorm = 0xe8, - BGR5A1Unorm = 0xe9, - RG8Unorm = 0xea, - RG8Snorm = 0xeb, - RG8Sint = 0xec, - RG8Uint = 0xed, + Bgr5A1Unorm = 0xe9, + Rg8Unorm = 0xea, + Rg8Snorm = 0xeb, + Rg8Sint = 0xec, + Rg8Uint = 0xed, R16Unorm = 0xee, R16Snorm = 0xef, R16Sint = 0xf0, @@ -56,13 +56,13 @@ R8Sint = 0xf5, R8Uint = 0xf6, A8Unorm = 0xf7, - BGR5X1Unorm = 0xf8, - RGBX8Unorm = 0xf9, - RGBX8Srgb = 0xfa, - BGR5X1UnormUnknownFB = 0xfb, - BGR5X1UnormUnknownFC = 0xfc, - BGRX8UnormUnknownFD = 0xfd, - BGRX8UnormUnknownFE = 0xfe, + Bgr5x1Unorm = 0xf8, + Rgbx8Unorm = 0xf9, + Rgbx8Srgb = 0xfa, + Bgr5x1UnormUnknownFB = 0xfb, + Bgr5x1UnormUnknownFC = 0xfc, + Bgrx8UnormUnknownFD = 0xfd, + Bgrx8UnormUnknownFE = 0xfe, Y32UintUnknownFF = 0xff } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/GalTextureFormat.cs b/Ryujinx.Graphics/Gal/GalTextureFormat.cs index 51ce5779..ed27180a 100644 --- a/Ryujinx.Graphics/Gal/GalTextureFormat.cs +++ b/Ryujinx.Graphics/Gal/GalTextureFormat.cs @@ -2,20 +2,20 @@ namespace Ryujinx.Graphics.Gal { public enum GalTextureFormat { - RGBA32 = 0x1, - RGBA16 = 0x3, - RG32 = 0x4, - RGBA8 = 0x8, - RGB10A2 = 0x9, - RG16 = 0xc, + Rgba32 = 0x1, + Rgba16 = 0x3, + Rg32 = 0x4, + Rgba8 = 0x8, + Rgb10A2 = 0x9, + Rg16 = 0xc, R32 = 0xf, BptcSfloat = 0x10, BptcUfloat = 0x11, - RGBA4 = 0x12, - RGB5A1 = 0x14, - RGB565 = 0x15, + Rgba4 = 0x12, + Rgb5A1 = 0x14, + Rgb565 = 0x15, BptcUnorm = 0x17, - RG8 = 0x18, + Rg8 = 0x18, R16 = 0x1b, R8 = 0x1d, R11G11B10F = 0x21, @@ -26,7 +26,7 @@ namespace Ryujinx.Graphics.Gal BC5 = 0x28, D24S8 = 0x29, D32F = 0x2f, - D32FX24S8 = 0x30, + D32Fx24S8 = 0x30, D16 = 0x3a, Astc2D4x4 = 0x40, Astc2D5x5 = 0x41, diff --git a/Ryujinx.Graphics/Gal/GalTextureSampler.cs b/Ryujinx.Graphics/Gal/GalTextureSampler.cs index 1d658cea..2e57a130 100644 --- a/Ryujinx.Graphics/Gal/GalTextureSampler.cs +++ b/Ryujinx.Graphics/Gal/GalTextureSampler.cs @@ -16,26 +16,26 @@ namespace Ryujinx.Graphics.Gal public DepthCompareFunc DepthCompareFunc { get; private set; } public GalTextureSampler( - GalTextureWrap AddressU, - GalTextureWrap AddressV, - GalTextureWrap AddressP, - GalTextureFilter MinFilter, - GalTextureFilter MagFilter, - GalTextureMipFilter MipFilter, - GalColorF BorderColor, - bool DepthCompare, - DepthCompareFunc DepthCompareFunc) + GalTextureWrap addressU, + GalTextureWrap addressV, + GalTextureWrap addressP, + GalTextureFilter minFilter, + GalTextureFilter magFilter, + GalTextureMipFilter mipFilter, + GalColorF borderColor, + bool depthCompare, + DepthCompareFunc depthCompareFunc) { - this.AddressU = AddressU; - this.AddressV = AddressV; - this.AddressP = AddressP; - this.MinFilter = MinFilter; - this.MagFilter = MagFilter; - this.MipFilter = MipFilter; - this.BorderColor = BorderColor; + AddressU = addressU; + AddressV = addressV; + AddressP = addressP; + MinFilter = minFilter; + MagFilter = magFilter; + MipFilter = mipFilter; + BorderColor = borderColor; - this.DepthCompare = DepthCompare; - this.DepthCompareFunc = DepthCompareFunc; + DepthCompare = depthCompare; + DepthCompareFunc = depthCompareFunc; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/GalTextureType.cs b/Ryujinx.Graphics/Gal/GalTextureType.cs index f7dd16d1..b02b8b37 100644 --- a/Ryujinx.Graphics/Gal/GalTextureType.cs +++ b/Ryujinx.Graphics/Gal/GalTextureType.cs @@ -6,8 +6,8 @@ Unorm = 2, Sint = 3, Uint = 4, - Snorm_Force_Fp16 = 5, - Unorm_Force_Fp16 = 6, + SnormForceFp16 = 5, + UnormForceFp16 = 6, Float = 7 } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/GalVertexAttrib.cs b/Ryujinx.Graphics/Gal/GalVertexAttrib.cs index 31b648df..feca5aea 100644 --- a/Ryujinx.Graphics/Gal/GalVertexAttrib.cs +++ b/Ryujinx.Graphics/Gal/GalVertexAttrib.cs @@ -13,21 +13,21 @@ namespace Ryujinx.Graphics.Gal public bool IsBgra { get; private set; } public GalVertexAttrib( - int Index, - bool IsConst, - int Offset, - byte[] Data, - GalVertexAttribSize Size, - GalVertexAttribType Type, - bool IsBgra) + int index, + bool isConst, + int offset, + byte[] data, + GalVertexAttribSize size, + GalVertexAttribType type, + bool isBgra) { - this.Index = Index; - this.IsConst = IsConst; - this.Data = Data; - this.Offset = Offset; - this.Size = Size; - this.Type = Type; - this.IsBgra = IsBgra; + Index = index; + IsConst = isConst; + Data = data; + Offset = offset; + Size = size; + Type = type; + IsBgra = isBgra; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/IGalConstBuffer.cs b/Ryujinx.Graphics/Gal/IGalConstBuffer.cs index 0cdcc237..8c4e6d03 100644 --- a/Ryujinx.Graphics/Gal/IGalConstBuffer.cs +++ b/Ryujinx.Graphics/Gal/IGalConstBuffer.cs @@ -7,11 +7,11 @@ namespace Ryujinx.Graphics.Gal void LockCache(); void UnlockCache(); - void Create(long Key, long Size); + void Create(long key, long size); - bool IsCached(long Key, long Size); + bool IsCached(long key, long size); - void SetData(long Key, long Size, IntPtr HostAddress); - void SetData(long Key, byte[] Data); + void SetData(long key, long size, IntPtr hostAddress); + void SetData(long key, byte[] data); } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/IGalMemory.cs b/Ryujinx.Graphics/Gal/IGalMemory.cs index e6762b50..78eb7154 100644 --- a/Ryujinx.Graphics/Gal/IGalMemory.cs +++ b/Ryujinx.Graphics/Gal/IGalMemory.cs @@ -1,7 +1,7 @@ namespace Ryujinx.Graphics.Gal { - public unsafe interface IGalMemory + public interface IGalMemory { - int ReadInt32(long Position); + int ReadInt32(long position); } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/IGalPipeline.cs b/Ryujinx.Graphics/Gal/IGalPipeline.cs index cb470fb4..1ecb2602 100644 --- a/Ryujinx.Graphics/Gal/IGalPipeline.cs +++ b/Ryujinx.Graphics/Gal/IGalPipeline.cs @@ -2,10 +2,10 @@ { public interface IGalPipeline { - void Bind(GalPipelineState State); - void Unbind(GalPipelineState State); + void Bind(GalPipelineState state); + void Unbind(GalPipelineState state); void ResetDepthMask(); - void ResetColorMask(int Index); + void ResetColorMask(int index); } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/IGalRasterizer.cs b/Ryujinx.Graphics/Gal/IGalRasterizer.cs index 04f7aae5..33bdeaad 100644 --- a/Ryujinx.Graphics/Gal/IGalRasterizer.cs +++ b/Ryujinx.Graphics/Gal/IGalRasterizer.cs @@ -8,29 +8,29 @@ namespace Ryujinx.Graphics.Gal void UnlockCaches(); void ClearBuffers( - GalClearBufferFlags Flags, - int Attachment, - float Red, - float Green, - float Blue, - float Alpha, - float Depth, - int Stencil); + GalClearBufferFlags flags, + int attachment, + float red, + float green, + float blue, + float alpha, + float depth, + int stencil); - bool IsVboCached(long Key, long DataSize); + bool IsVboCached(long key, long dataSize); - bool IsIboCached(long Key, long DataSize); + bool IsIboCached(long key, long dataSize); - void CreateVbo(long Key, int DataSize, IntPtr HostAddress); - void CreateVbo(long Key, byte[] Data); + void CreateVbo(long key, int dataSize, IntPtr hostAddress); + void CreateVbo(long key, byte[] data); - void CreateIbo(long Key, int DataSize, IntPtr HostAddress); - void CreateIbo(long Key, int DataSize, byte[] Buffer); + void CreateIbo(long key, int dataSize, IntPtr hostAddress); + void CreateIbo(long key, int dataSize, byte[] buffer); - void SetIndexArray(int Size, GalIndexFormat Format); + void SetIndexArray(int size, GalIndexFormat format); - void DrawArrays(int First, int Count, GalPrimitiveType PrimType); + void DrawArrays(int first, int count, GalPrimitiveType primType); - void DrawElements(long IboKey, int First, int VertexBase, GalPrimitiveType PrimType); + void DrawElements(long iboKey, int first, int vertexBase, GalPrimitiveType primType); } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/IGalRenderTarget.cs b/Ryujinx.Graphics/Gal/IGalRenderTarget.cs index 90cad856..c281fe06 100644 --- a/Ryujinx.Graphics/Gal/IGalRenderTarget.cs +++ b/Ryujinx.Graphics/Gal/IGalRenderTarget.cs @@ -4,42 +4,42 @@ namespace Ryujinx.Graphics.Gal { void Bind(); - void BindColor(long Key, int Attachment); + void BindColor(long key, int attachment); - void UnbindColor(int Attachment); + void UnbindColor(int attachment); - void BindZeta(long Key); + void BindZeta(long key); void UnbindZeta(); - void Present(long Key); + void Present(long key); - void SetMap(int[] Map); + void SetMap(int[] map); - void SetTransform(bool FlipX, bool FlipY, int Top, int Left, int Right, int Bottom); + void SetTransform(bool flipX, bool flipY, int top, int left, int right, int bottom); - void SetWindowSize(int Width, int Height); + void SetWindowSize(int width, int height); - void SetViewport(int Attachment, int X, int Y, int Width, int Height); + void SetViewport(int attachment, int x, int y, int width, int height); void Render(); void Copy( - GalImage SrcImage, - GalImage DstImage, - long SrcKey, - long DstKey, - int SrcLayer, - int DstLayer, - int SrcX0, - int SrcY0, - int SrcX1, - int SrcY1, - int DstX0, - int DstY0, - int DstX1, - int DstY1); + GalImage srcImage, + GalImage dstImage, + long srcKey, + long dstKey, + int srcLayer, + int dstLayer, + int srcX0, + int srcY0, + int srcX1, + int srcY1, + int dstX0, + int dstY0, + int dstX1, + int dstY1); - void Reinterpret(long Key, GalImage NewImage); + void Reinterpret(long key, GalImage newImage); } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/IGalRenderer.cs b/Ryujinx.Graphics/Gal/IGalRenderer.cs index 41e95a87..1acc4d03 100644 --- a/Ryujinx.Graphics/Gal/IGalRenderer.cs +++ b/Ryujinx.Graphics/Gal/IGalRenderer.cs @@ -4,7 +4,7 @@ namespace Ryujinx.Graphics.Gal { public interface IGalRenderer { - void QueueAction(Action ActionMthd); + void QueueAction(Action actionMthd); void RunActions(); diff --git a/Ryujinx.Graphics/Gal/IGalShader.cs b/Ryujinx.Graphics/Gal/IGalShader.cs index 4b951fa6..99cd4d76 100644 --- a/Ryujinx.Graphics/Gal/IGalShader.cs +++ b/Ryujinx.Graphics/Gal/IGalShader.cs @@ -4,16 +4,16 @@ namespace Ryujinx.Graphics.Gal { public interface IGalShader { - void Create(IGalMemory Memory, long Key, GalShaderType Type); + void Create(IGalMemory memory, long key, GalShaderType type); - void Create(IGalMemory Memory, long VpAPos, long Key, GalShaderType Type); + void Create(IGalMemory memory, long vpAPos, long key, GalShaderType type); - IEnumerable GetConstBufferUsage(long Key); - IEnumerable GetTextureUsage(long Key); + IEnumerable GetConstBufferUsage(long key); + IEnumerable GetTextureUsage(long key); - void Bind(long Key); + void Bind(long key); - void Unbind(GalShaderType Type); + void Unbind(GalShaderType type); void BindProgram(); } diff --git a/Ryujinx.Graphics/Gal/IGalTexture.cs b/Ryujinx.Graphics/Gal/IGalTexture.cs index de4ba9cb..23ce054a 100644 --- a/Ryujinx.Graphics/Gal/IGalTexture.cs +++ b/Ryujinx.Graphics/Gal/IGalTexture.cs @@ -5,14 +5,14 @@ namespace Ryujinx.Graphics.Gal void LockCache(); void UnlockCache(); - void Create(long Key, int Size, GalImage Image); + void Create(long key, int size, GalImage image); - void Create(long Key, byte[] Data, GalImage Image); + void Create(long key, byte[] data, GalImage image); - bool TryGetImage(long Key, out GalImage Image); + bool TryGetImage(long key, out GalImage image); - void Bind(long Key, int Index, GalImage Image); + void Bind(long key, int index, GalImage image); - void SetSampler(GalImage Image, GalTextureSampler Sampler); + void SetSampler(GalImage image, GalTextureSampler sampler); } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/DeleteValueCallback.cs b/Ryujinx.Graphics/Gal/OpenGL/DeleteValueCallback.cs index acd8d72f..63b626f1 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/DeleteValueCallback.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/DeleteValueCallback.cs @@ -1,4 +1,4 @@ namespace Ryujinx.Graphics.Gal.OpenGL { - delegate void DeleteValue(T Value); + delegate void DeleteValue(T value); } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/ImageHandler.cs b/Ryujinx.Graphics/Gal/OpenGL/ImageHandler.cs index 5714f3d8..d7f6f004 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/ImageHandler.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/ImageHandler.cs @@ -18,10 +18,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL public bool HasDepth => ImageUtils.HasDepth(Image.Format); public bool HasStencil => ImageUtils.HasStencil(Image.Format); - public ImageHandler(int Handle, GalImage Image) + public ImageHandler(int handle, GalImage image) { - this.Handle = Handle; - this.Image = Image; + Handle = handle; + Image = image; } } } diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLCachedResource.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLCachedResource.cs deleted file mode 100644 index 6e17872b..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLCachedResource.cs +++ /dev/null @@ -1,191 +0,0 @@ -using Ryujinx.Common; -using System; -using System.Collections.Generic; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - class OGLCachedResource - { - public delegate void DeleteValue(T Value); - - private const int MinTimeDelta = 5 * 60000; - private const int MaxRemovalsPerRun = 10; - - private struct CacheBucket - { - public T Value { get; private set; } - - public LinkedListNode Node { get; private set; } - - public long DataSize { get; private set; } - - public long Timestamp { get; private set; } - - public CacheBucket(T Value, long DataSize, LinkedListNode Node) - { - this.Value = Value; - this.DataSize = DataSize; - this.Node = Node; - - Timestamp = PerformanceCounter.ElapsedMilliseconds; - } - } - - private Dictionary Cache; - - private LinkedList SortedCache; - - private DeleteValue DeleteValueCallback; - - private Queue DeletePending; - - private bool Locked; - - private long MaxSize; - private long TotalSize; - - public OGLCachedResource(DeleteValue DeleteValueCallback, long MaxSize) - { - this.MaxSize = MaxSize; - - if (DeleteValueCallback == null) - { - throw new ArgumentNullException(nameof(DeleteValueCallback)); - } - - this.DeleteValueCallback = DeleteValueCallback; - - Cache = new Dictionary(); - - SortedCache = new LinkedList(); - - DeletePending = new Queue(); - } - - public void Lock() - { - Locked = true; - } - - public void Unlock() - { - Locked = false; - - while (DeletePending.TryDequeue(out T Value)) - { - DeleteValueCallback(Value); - } - - ClearCacheIfNeeded(); - } - - public void AddOrUpdate(long Key, T Value, long Size) - { - if (!Locked) - { - ClearCacheIfNeeded(); - } - - LinkedListNode Node = SortedCache.AddLast(Key); - - CacheBucket NewBucket = new CacheBucket(Value, Size, Node); - - if (Cache.TryGetValue(Key, out CacheBucket Bucket)) - { - if (Locked) - { - DeletePending.Enqueue(Bucket.Value); - } - else - { - DeleteValueCallback(Bucket.Value); - } - - SortedCache.Remove(Bucket.Node); - - TotalSize -= Bucket.DataSize; - - Cache[Key] = NewBucket; - } - else - { - Cache.Add(Key, NewBucket); - } - - TotalSize += Size; - } - - public bool TryGetValue(long Key, out T Value) - { - if (Cache.TryGetValue(Key, out CacheBucket Bucket)) - { - Value = Bucket.Value; - - SortedCache.Remove(Bucket.Node); - - LinkedListNode Node = SortedCache.AddLast(Key); - - Cache[Key] = new CacheBucket(Value, Bucket.DataSize, Node); - - return true; - } - - Value = default(T); - - return false; - } - - public bool TryGetSize(long Key, out long Size) - { - if (Cache.TryGetValue(Key, out CacheBucket Bucket)) - { - Size = Bucket.DataSize; - - return true; - } - - Size = 0; - - return false; - } - - private void ClearCacheIfNeeded() - { - long Timestamp = PerformanceCounter.ElapsedMilliseconds; - - int Count = 0; - - while (Count++ < MaxRemovalsPerRun) - { - LinkedListNode Node = SortedCache.First; - - if (Node == null) - { - break; - } - - CacheBucket Bucket = Cache[Node.Value]; - - long TimeDelta = Timestamp - Bucket.Timestamp; - - if (TimeDelta <= MinTimeDelta && !UnderMemoryPressure()) - { - break; - } - - SortedCache.Remove(Node); - - Cache.Remove(Node.Value); - - DeleteValueCallback(Bucket.Value); - - TotalSize -= Bucket.DataSize; - } - } - - private bool UnderMemoryPressure() - { - return TotalSize >= MaxSize; - } - } -} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs deleted file mode 100644 index a12681c7..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs +++ /dev/null @@ -1,74 +0,0 @@ -using OpenTK.Graphics.OpenGL; -using System; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - class OGLConstBuffer : IGalConstBuffer - { - private const long MaxConstBufferCacheSize = 64 * 1024 * 1024; - - private OGLCachedResource Cache; - - public OGLConstBuffer() - { - Cache = new OGLCachedResource(DeleteBuffer, MaxConstBufferCacheSize); - } - - public void LockCache() - { - Cache.Lock(); - } - - public void UnlockCache() - { - Cache.Unlock(); - } - - public void Create(long Key, long Size) - { - OGLStreamBuffer Buffer = new OGLStreamBuffer(BufferTarget.UniformBuffer, Size); - - Cache.AddOrUpdate(Key, Buffer, Size); - } - - public bool IsCached(long Key, long Size) - { - return Cache.TryGetSize(Key, out long CachedSize) && CachedSize == Size; - } - - public void SetData(long Key, long Size, IntPtr HostAddress) - { - if (Cache.TryGetValue(Key, out OGLStreamBuffer Buffer)) - { - Buffer.SetData(Size, HostAddress); - } - } - - public void SetData(long Key, byte[] Data) - { - if (Cache.TryGetValue(Key, out OGLStreamBuffer Buffer)) - { - Buffer.SetData(Data); - } - } - - public bool TryGetUbo(long Key, out int UboHandle) - { - if (Cache.TryGetValue(Key, out OGLStreamBuffer Buffer)) - { - UboHandle = Buffer.Handle; - - return true; - } - - UboHandle = 0; - - return false; - } - - private static void DeleteBuffer(OGLStreamBuffer Buffer) - { - Buffer.Dispose(); - } - } -} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs deleted file mode 100644 index eb06f83c..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs +++ /dev/null @@ -1,70 +0,0 @@ -using OpenTK.Graphics.OpenGL; -using Ryujinx.Common.Logging; -using System; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - static class OGLExtension - { - // Private lazy backing variables - private static Lazy s_EnhancedLayouts = new Lazy(() => HasExtension("GL_ARB_enhanced_layouts")); - private static Lazy s_TextureMirrorClamp = new Lazy(() => HasExtension("GL_EXT_texture_mirror_clamp")); - private static Lazy s_ViewportArray = new Lazy(() => HasExtension("GL_ARB_viewport_array")); - - private static Lazy s_NvidiaDriver = new Lazy(() => IsNvidiaDriver()); - - // Public accessors - public static bool EnhancedLayouts => s_EnhancedLayouts.Value; - public static bool TextureMirrorClamp => s_TextureMirrorClamp.Value; - public static bool ViewportArray => s_ViewportArray.Value; - - public static bool NvidiaDrvier => s_NvidiaDriver.Value; - - private static bool HasExtension(string Name) - { - int NumExtensions = GL.GetInteger(GetPName.NumExtensions); - - for (int Extension = 0; Extension < NumExtensions; Extension++) - { - if (GL.GetString(StringNameIndexed.Extensions, Extension) == Name) - { - return true; - } - } - - Logger.PrintInfo(LogClass.Gpu, $"OpenGL extension {Name} unavailable. You may experience some performance degredation"); - - return false; - } - - private static bool IsNvidiaDriver() - { - return GL.GetString(StringName.Vendor).Equals("NVIDIA Corporation"); - } - - public static class Required - { - // Public accessors - public static bool EnhancedLayouts => s_EnhancedLayoutsRequired.Value; - public static bool TextureMirrorClamp => s_TextureMirrorClampRequired.Value; - public static bool ViewportArray => s_ViewportArrayRequired.Value; - - // Private lazy backing variables - private static Lazy s_EnhancedLayoutsRequired = new Lazy(() => HasExtensionRequired(OGLExtension.EnhancedLayouts, "GL_ARB_enhanced_layouts")); - private static Lazy s_TextureMirrorClampRequired = new Lazy(() => HasExtensionRequired(OGLExtension.TextureMirrorClamp, "GL_EXT_texture_mirror_clamp")); - private static Lazy s_ViewportArrayRequired = new Lazy(() => HasExtensionRequired(OGLExtension.ViewportArray, "GL_ARB_viewport_array")); - - private static bool HasExtensionRequired(bool Value, string Name) - { - if (Value) - { - return true; - } - - Logger.PrintWarning(LogClass.Gpu, $"Required OpenGL extension {Name} unavailable. You may experience some rendering issues"); - - return false; - } - } - } -} diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLLimit.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLLimit.cs deleted file mode 100644 index 6c385bc4..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLLimit.cs +++ /dev/null @@ -1,12 +0,0 @@ -using OpenTK.Graphics.OpenGL; -using System; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - static class OGLLimit - { - private static Lazy s_MaxUboSize = new Lazy(() => GL.GetInteger(GetPName.MaxUniformBlockSize)); - - public static int MaxUboSize => s_MaxUboSize.Value; - } -} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs deleted file mode 100644 index c4015d02..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs +++ /dev/null @@ -1,207 +0,0 @@ -using OpenTK.Graphics.OpenGL; -using System; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - class OGLRasterizer : IGalRasterizer - { - private const long MaxVertexBufferCacheSize = 128 * 1024 * 1024; - private const long MaxIndexBufferCacheSize = 64 * 1024 * 1024; - - private int[] VertexBuffers; - - private OGLCachedResource VboCache; - private OGLCachedResource IboCache; - - private struct IbInfo - { - public int Count; - public int ElemSizeLog2; - - public DrawElementsType Type; - } - - private IbInfo IndexBuffer; - - public OGLRasterizer() - { - VertexBuffers = new int[32]; - - VboCache = new OGLCachedResource(GL.DeleteBuffer, MaxVertexBufferCacheSize); - IboCache = new OGLCachedResource(GL.DeleteBuffer, MaxIndexBufferCacheSize); - - IndexBuffer = new IbInfo(); - } - - public void LockCaches() - { - VboCache.Lock(); - IboCache.Lock(); - } - - public void UnlockCaches() - { - VboCache.Unlock(); - IboCache.Unlock(); - } - - public void ClearBuffers( - GalClearBufferFlags Flags, - int Attachment, - float Red, - float Green, - float Blue, - float Alpha, - float Depth, - int Stencil) - { - GL.ColorMask( - Attachment, - Flags.HasFlag(GalClearBufferFlags.ColorRed), - Flags.HasFlag(GalClearBufferFlags.ColorGreen), - Flags.HasFlag(GalClearBufferFlags.ColorBlue), - Flags.HasFlag(GalClearBufferFlags.ColorAlpha)); - - GL.ClearBuffer(ClearBuffer.Color, Attachment, new float[] { Red, Green, Blue, Alpha }); - - GL.ColorMask(Attachment, true, true, true, true); - GL.DepthMask(true); - - if (Flags.HasFlag(GalClearBufferFlags.Depth)) - { - GL.ClearBuffer(ClearBuffer.Depth, 0, ref Depth); - } - - if (Flags.HasFlag(GalClearBufferFlags.Stencil)) - { - GL.ClearBuffer(ClearBuffer.Stencil, 0, ref Stencil); - } - } - - public bool IsVboCached(long Key, long DataSize) - { - return VboCache.TryGetSize(Key, out long Size) && Size == DataSize; - } - - public bool IsIboCached(long Key, long DataSize) - { - return IboCache.TryGetSize(Key, out long Size) && Size == DataSize; - } - - public void CreateVbo(long Key, int DataSize, IntPtr HostAddress) - { - int Handle = GL.GenBuffer(); - - VboCache.AddOrUpdate(Key, Handle, DataSize); - - IntPtr Length = new IntPtr(DataSize); - - GL.BindBuffer(BufferTarget.ArrayBuffer, Handle); - GL.BufferData(BufferTarget.ArrayBuffer, Length, HostAddress, BufferUsageHint.StreamDraw); - } - - public void CreateVbo(long Key, byte[] Data) - { - int Handle = GL.GenBuffer(); - - VboCache.AddOrUpdate(Key, Handle, Data.Length); - - IntPtr Length = new IntPtr(Data.Length); - - GL.BindBuffer(BufferTarget.ArrayBuffer, Handle); - GL.BufferData(BufferTarget.ArrayBuffer, Length, Data, BufferUsageHint.StreamDraw); - } - - public void CreateIbo(long Key, int DataSize, IntPtr HostAddress) - { - int Handle = GL.GenBuffer(); - - IboCache.AddOrUpdate(Key, Handle, (uint)DataSize); - - IntPtr Length = new IntPtr(DataSize); - - GL.BindBuffer(BufferTarget.ElementArrayBuffer, Handle); - GL.BufferData(BufferTarget.ElementArrayBuffer, Length, HostAddress, BufferUsageHint.StreamDraw); - } - - public void CreateIbo(long Key, int DataSize, byte[] Buffer) - { - int Handle = GL.GenBuffer(); - - IboCache.AddOrUpdate(Key, Handle, DataSize); - - IntPtr Length = new IntPtr(Buffer.Length); - - GL.BindBuffer(BufferTarget.ElementArrayBuffer, Handle); - GL.BufferData(BufferTarget.ElementArrayBuffer, Length, Buffer, BufferUsageHint.StreamDraw); - } - - public void SetIndexArray(int Size, GalIndexFormat Format) - { - IndexBuffer.Type = OGLEnumConverter.GetDrawElementsType(Format); - - IndexBuffer.Count = Size >> (int)Format; - - IndexBuffer.ElemSizeLog2 = (int)Format; - } - - public void DrawArrays(int First, int Count, GalPrimitiveType PrimType) - { - if (Count == 0) - { - return; - } - - if (PrimType == GalPrimitiveType.Quads) - { - for (int Offset = 0; Offset < Count; Offset += 4) - { - GL.DrawArrays(PrimitiveType.TriangleFan, First + Offset, 4); - } - } - else if (PrimType == GalPrimitiveType.QuadStrip) - { - GL.DrawArrays(PrimitiveType.TriangleFan, First, 4); - - for (int Offset = 2; Offset < Count; Offset += 2) - { - GL.DrawArrays(PrimitiveType.TriangleFan, First + Offset, 4); - } - } - else - { - GL.DrawArrays(OGLEnumConverter.GetPrimitiveType(PrimType), First, Count); - } - } - - public void DrawElements(long IboKey, int First, int VertexBase, GalPrimitiveType PrimType) - { - if (!IboCache.TryGetValue(IboKey, out int IboHandle)) - { - return; - } - - PrimitiveType Mode = OGLEnumConverter.GetPrimitiveType(PrimType); - - GL.BindBuffer(BufferTarget.ElementArrayBuffer, IboHandle); - - First <<= IndexBuffer.ElemSizeLog2; - - if (VertexBase != 0) - { - IntPtr Indices = new IntPtr(First); - - GL.DrawElementsBaseVertex(Mode, IndexBuffer.Count, IndexBuffer.Type, Indices, VertexBase); - } - else - { - GL.DrawElements(Mode, IndexBuffer.Count, IndexBuffer.Type, First); - } - } - - public bool TryGetVbo(long VboKey, out int VboHandle) - { - return VboCache.TryGetValue(VboKey, out VboHandle); - } - } -} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLRenderTarget.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLRenderTarget.cs deleted file mode 100644 index 53cfd4a6..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLRenderTarget.cs +++ /dev/null @@ -1,549 +0,0 @@ -using OpenTK.Graphics.OpenGL; -using Ryujinx.Graphics.Texture; -using System; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - class OGLRenderTarget : IGalRenderTarget - { - private const int NativeWidth = 1280; - private const int NativeHeight = 720; - - private const int RenderTargetsCount = GalPipelineState.RenderTargetsCount; - - private struct Rect - { - public int X { get; private set; } - public int Y { get; private set; } - public int Width { get; private set; } - public int Height { get; private set; } - - public Rect(int X, int Y, int Width, int Height) - { - this.X = X; - this.Y = Y; - this.Width = Width; - this.Height = Height; - } - } - - private class FrameBufferAttachments - { - public int MapCount { get; set; } - - public DrawBuffersEnum[] Map { get; private set; } - - public long[] Colors { get; private set; } - - public long Zeta { get; set; } - - public FrameBufferAttachments() - { - Colors = new long[RenderTargetsCount]; - - Map = new DrawBuffersEnum[RenderTargetsCount]; - } - - public void Update(FrameBufferAttachments Source) - { - for (int Index = 0; Index < RenderTargetsCount; Index++) - { - Map[Index] = Source.Map[Index]; - - Colors[Index] = Source.Colors[Index]; - } - - MapCount = Source.MapCount; - Zeta = Source.Zeta; - } - } - - private int[] ColorHandles; - private int ZetaHandle; - - private OGLTexture Texture; - - private ImageHandler ReadTex; - - private Rect Window; - - private float[] Viewports; - - private bool FlipX; - private bool FlipY; - - private int CropTop; - private int CropLeft; - private int CropRight; - private int CropBottom; - - //This framebuffer is used to attach guest rendertargets, - //think of it as a dummy OpenGL VAO - private int DummyFrameBuffer; - - //These framebuffers are used to blit images - private int SrcFb; - private int DstFb; - - private FrameBufferAttachments Attachments; - private FrameBufferAttachments OldAttachments; - - private int CopyPBO; - - public bool FramebufferSrgb { get; set; } - - public OGLRenderTarget(OGLTexture Texture) - { - Attachments = new FrameBufferAttachments(); - - OldAttachments = new FrameBufferAttachments(); - - ColorHandles = new int[RenderTargetsCount]; - - Viewports = new float[RenderTargetsCount * 4]; - - this.Texture = Texture; - - Texture.TextureDeleted += TextureDeletionHandler; - } - - private void TextureDeletionHandler(object Sender, int Handle) - { - //Texture was deleted, the handle is no longer valid, so - //reset all uses of this handle on a render target. - for (int Attachment = 0; Attachment < RenderTargetsCount; Attachment++) - { - if (ColorHandles[Attachment] == Handle) - { - ColorHandles[Attachment] = 0; - } - } - - if (ZetaHandle == Handle) - { - ZetaHandle = 0; - } - } - - public void Bind() - { - if (DummyFrameBuffer == 0) - { - DummyFrameBuffer = GL.GenFramebuffer(); - } - - GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, DummyFrameBuffer); - - ImageHandler CachedImage; - - for (int Attachment = 0; Attachment < RenderTargetsCount; Attachment++) - { - long Key = Attachments.Colors[Attachment]; - - int Handle = 0; - - if (Key != 0 && Texture.TryGetImageHandler(Key, out CachedImage)) - { - Handle = CachedImage.Handle; - } - - if (Handle == ColorHandles[Attachment]) - { - continue; - } - - GL.FramebufferTexture( - FramebufferTarget.DrawFramebuffer, - FramebufferAttachment.ColorAttachment0 + Attachment, - Handle, - 0); - - ColorHandles[Attachment] = Handle; - } - - if (Attachments.Zeta != 0 && Texture.TryGetImageHandler(Attachments.Zeta, out CachedImage)) - { - if (CachedImage.Handle != ZetaHandle) - { - if (CachedImage.HasDepth && CachedImage.HasStencil) - { - GL.FramebufferTexture( - FramebufferTarget.DrawFramebuffer, - FramebufferAttachment.DepthStencilAttachment, - CachedImage.Handle, - 0); - } - else if (CachedImage.HasDepth) - { - GL.FramebufferTexture( - FramebufferTarget.DrawFramebuffer, - FramebufferAttachment.DepthAttachment, - CachedImage.Handle, - 0); - - GL.FramebufferTexture( - FramebufferTarget.DrawFramebuffer, - FramebufferAttachment.StencilAttachment, - 0, - 0); - } - else - { - throw new InvalidOperationException("Invalid image format \"" + CachedImage.Format + "\" used as Zeta!"); - } - - ZetaHandle = CachedImage.Handle; - } - } - else if (ZetaHandle != 0) - { - GL.FramebufferTexture( - FramebufferTarget.DrawFramebuffer, - FramebufferAttachment.DepthStencilAttachment, - 0, - 0); - - ZetaHandle = 0; - } - - if (OGLExtension.ViewportArray) - { - GL.ViewportArray(0, RenderTargetsCount, Viewports); - } - else - { - GL.Viewport( - (int)Viewports[0], - (int)Viewports[1], - (int)Viewports[2], - (int)Viewports[3]); - } - - if (Attachments.MapCount > 1) - { - GL.DrawBuffers(Attachments.MapCount, Attachments.Map); - } - else if (Attachments.MapCount == 1) - { - GL.DrawBuffer((DrawBufferMode)Attachments.Map[0]); - } - else - { - GL.DrawBuffer(DrawBufferMode.None); - } - - OldAttachments.Update(Attachments); - } - - public void BindColor(long Key, int Attachment) - { - Attachments.Colors[Attachment] = Key; - } - - public void UnbindColor(int Attachment) - { - Attachments.Colors[Attachment] = 0; - } - - public void BindZeta(long Key) - { - Attachments.Zeta = Key; - } - - public void UnbindZeta() - { - Attachments.Zeta = 0; - } - - public void Present(long Key) - { - Texture.TryGetImageHandler(Key, out ReadTex); - } - - public void SetMap(int[] Map) - { - if (Map != null) - { - Attachments.MapCount = Map.Length; - - for (int Attachment = 0; Attachment < Attachments.MapCount; Attachment++) - { - Attachments.Map[Attachment] = DrawBuffersEnum.ColorAttachment0 + Map[Attachment]; - } - } - else - { - Attachments.MapCount = 0; - } - } - - public void SetTransform(bool FlipX, bool FlipY, int Top, int Left, int Right, int Bottom) - { - this.FlipX = FlipX; - this.FlipY = FlipY; - - CropTop = Top; - CropLeft = Left; - CropRight = Right; - CropBottom = Bottom; - } - - public void SetWindowSize(int Width, int Height) - { - Window = new Rect(0, 0, Width, Height); - } - - public void SetViewport(int Attachment, int X, int Y, int Width, int Height) - { - int Offset = Attachment * 4; - - Viewports[Offset + 0] = X; - Viewports[Offset + 1] = Y; - Viewports[Offset + 2] = Width; - Viewports[Offset + 3] = Height; - } - - public void Render() - { - if (ReadTex == null) - { - return; - } - - int SrcX0, SrcX1, SrcY0, SrcY1; - - if (CropLeft == 0 && CropRight == 0) - { - SrcX0 = 0; - SrcX1 = ReadTex.Width; - } - else - { - SrcX0 = CropLeft; - SrcX1 = CropRight; - } - - if (CropTop == 0 && CropBottom == 0) - { - SrcY0 = 0; - SrcY1 = ReadTex.Height; - } - else - { - SrcY0 = CropTop; - SrcY1 = CropBottom; - } - - float RatioX = MathF.Min(1f, (Window.Height * (float)NativeWidth) / ((float)NativeHeight * Window.Width)); - float RatioY = MathF.Min(1f, (Window.Width * (float)NativeHeight) / ((float)NativeWidth * Window.Height)); - - int DstWidth = (int)(Window.Width * RatioX); - int DstHeight = (int)(Window.Height * RatioY); - - int DstPaddingX = (Window.Width - DstWidth) / 2; - int DstPaddingY = (Window.Height - DstHeight) / 2; - - int DstX0 = FlipX ? Window.Width - DstPaddingX : DstPaddingX; - int DstX1 = FlipX ? DstPaddingX : Window.Width - DstPaddingX; - - int DstY0 = FlipY ? DstPaddingY : Window.Height - DstPaddingY; - int DstY1 = FlipY ? Window.Height - DstPaddingY : DstPaddingY; - - GL.Viewport(0, 0, Window.Width, Window.Height); - - if (SrcFb == 0) - { - SrcFb = GL.GenFramebuffer(); - } - - GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, SrcFb); - GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, 0); - - GL.FramebufferTexture(FramebufferTarget.ReadFramebuffer, FramebufferAttachment.ColorAttachment0, ReadTex.Handle, 0); - - GL.ReadBuffer(ReadBufferMode.ColorAttachment0); - - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.Disable(EnableCap.FramebufferSrgb); - - GL.BlitFramebuffer( - SrcX0, - SrcY0, - SrcX1, - SrcY1, - DstX0, - DstY0, - DstX1, - DstY1, - ClearBufferMask.ColorBufferBit, - BlitFramebufferFilter.Linear); - - if (FramebufferSrgb) - { - GL.Enable(EnableCap.FramebufferSrgb); - } - } - - public void Copy( - GalImage SrcImage, - GalImage DstImage, - long SrcKey, - long DstKey, - int SrcLayer, - int DstLayer, - int SrcX0, - int SrcY0, - int SrcX1, - int SrcY1, - int DstX0, - int DstY0, - int DstX1, - int DstY1) - { - if (Texture.TryGetImageHandler(SrcKey, out ImageHandler SrcTex) && - Texture.TryGetImageHandler(DstKey, out ImageHandler DstTex)) - { - if (SrcTex.HasColor != DstTex.HasColor || - SrcTex.HasDepth != DstTex.HasDepth || - SrcTex.HasStencil != DstTex.HasStencil) - { - throw new NotImplementedException(); - } - - if (SrcFb == 0) - { - SrcFb = GL.GenFramebuffer(); - } - - if (DstFb == 0) - { - DstFb = GL.GenFramebuffer(); - } - - GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, SrcFb); - GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, DstFb); - - FramebufferAttachment Attachment = GetAttachment(SrcTex); - - if (ImageUtils.IsArray(SrcImage.TextureTarget) && SrcLayer > 0) - { - GL.FramebufferTextureLayer(FramebufferTarget.ReadFramebuffer, Attachment, SrcTex.Handle, 0, SrcLayer); - } - else - { - GL.FramebufferTexture(FramebufferTarget.ReadFramebuffer, Attachment, SrcTex.Handle, 0); - } - - if (ImageUtils.IsArray(DstImage.TextureTarget) && DstLayer > 0) - { - GL.FramebufferTextureLayer(FramebufferTarget.DrawFramebuffer, Attachment, DstTex.Handle, 0, DstLayer); - } - else - { - GL.FramebufferTexture(FramebufferTarget.DrawFramebuffer, Attachment, DstTex.Handle, 0); - } - - - BlitFramebufferFilter Filter = BlitFramebufferFilter.Nearest; - - if (SrcTex.HasColor) - { - GL.DrawBuffer(DrawBufferMode.ColorAttachment0); - - Filter = BlitFramebufferFilter.Linear; - } - - ClearBufferMask Mask = GetClearMask(SrcTex); - - GL.BlitFramebuffer(SrcX0, SrcY0, SrcX1, SrcY1, DstX0, DstY0, DstX1, DstY1, Mask, Filter); - } - } - - public void Reinterpret(long Key, GalImage NewImage) - { - if (!Texture.TryGetImage(Key, out GalImage OldImage)) - { - return; - } - - if (NewImage.Format == OldImage.Format && - NewImage.Width == OldImage.Width && - NewImage.Height == OldImage.Height && - NewImage.Depth == OldImage.Depth && - NewImage.LayerCount == OldImage.LayerCount && - NewImage.TextureTarget == OldImage.TextureTarget) - { - return; - } - - if (CopyPBO == 0) - { - CopyPBO = GL.GenBuffer(); - } - - GL.BindBuffer(BufferTarget.PixelPackBuffer, CopyPBO); - - //The buffer should be large enough to hold the largest texture. - int BufferSize = Math.Max(ImageUtils.GetSize(OldImage), - ImageUtils.GetSize(NewImage)); - - GL.BufferData(BufferTarget.PixelPackBuffer, BufferSize, IntPtr.Zero, BufferUsageHint.StreamCopy); - - if (!Texture.TryGetImageHandler(Key, out ImageHandler CachedImage)) - { - throw new InvalidOperationException(); - } - - (_, PixelFormat Format, PixelType Type) = OGLEnumConverter.GetImageFormat(CachedImage.Format); - - TextureTarget Target = ImageUtils.GetTextureTarget(NewImage.TextureTarget); - - GL.BindTexture(Target, CachedImage.Handle); - - GL.GetTexImage(Target, 0, Format, Type, IntPtr.Zero); - - GL.BindBuffer(BufferTarget.PixelPackBuffer, 0); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, CopyPBO); - - GL.PixelStore(PixelStoreParameter.UnpackRowLength, OldImage.Width); - - Texture.Create(Key, ImageUtils.GetSize(NewImage), NewImage); - - GL.PixelStore(PixelStoreParameter.UnpackRowLength, 0); - - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); - } - - private static FramebufferAttachment GetAttachment(ImageHandler CachedImage) - { - if (CachedImage.HasColor) - { - return FramebufferAttachment.ColorAttachment0; - } - else if (CachedImage.HasDepth && CachedImage.HasStencil) - { - return FramebufferAttachment.DepthStencilAttachment; - } - else if (CachedImage.HasDepth) - { - return FramebufferAttachment.DepthAttachment; - } - else if (CachedImage.HasStencil) - { - return FramebufferAttachment.StencilAttachment; - } - else - { - throw new InvalidOperationException(); - } - } - - private static ClearBufferMask GetClearMask(ImageHandler CachedImage) - { - return (CachedImage.HasColor ? ClearBufferMask.ColorBufferBit : 0) | - (CachedImage.HasDepth ? ClearBufferMask.DepthBufferBit : 0) | - (CachedImage.HasStencil ? ClearBufferMask.StencilBufferBit : 0); - } - } -} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs deleted file mode 100644 index 14fb9018..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Concurrent; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - public class OGLRenderer : IGalRenderer - { - public IGalConstBuffer Buffer { get; private set; } - - public IGalRenderTarget RenderTarget { get; private set; } - - public IGalRasterizer Rasterizer { get; private set; } - - public IGalShader Shader { get; private set; } - - public IGalPipeline Pipeline { get; private set; } - - public IGalTexture Texture { get; private set; } - - private ConcurrentQueue ActionsQueue; - - public OGLRenderer() - { - Buffer = new OGLConstBuffer(); - - Texture = new OGLTexture(); - - RenderTarget = new OGLRenderTarget(Texture as OGLTexture); - - Rasterizer = new OGLRasterizer(); - - Shader = new OGLShader(Buffer as OGLConstBuffer); - - Pipeline = new OGLPipeline( - Buffer as OGLConstBuffer, - RenderTarget as OGLRenderTarget, - Rasterizer as OGLRasterizer, - Shader as OGLShader); - - ActionsQueue = new ConcurrentQueue(); - } - - public void QueueAction(Action ActionMthd) - { - ActionsQueue.Enqueue(ActionMthd); - } - - public void RunActions() - { - int Count = ActionsQueue.Count; - - while (Count-- > 0 && ActionsQueue.TryDequeue(out Action RenderAction)) - { - RenderAction(); - } - } - } -} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs deleted file mode 100644 index dc168ff9..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs +++ /dev/null @@ -1,298 +0,0 @@ -using OpenTK.Graphics.OpenGL; -using Ryujinx.Graphics.Gal.Shader; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - class OGLShader : IGalShader - { - public const int ReservedCbufCount = 1; - - private const int ExtraDataSize = 4; - - public OGLShaderProgram Current; - - private ConcurrentDictionary Stages; - - private Dictionary Programs; - - public int CurrentProgramHandle { get; private set; } - - private OGLConstBuffer Buffer; - - private int ExtraUboHandle; - - public OGLShader(OGLConstBuffer Buffer) - { - this.Buffer = Buffer; - - Stages = new ConcurrentDictionary(); - - Programs = new Dictionary(); - } - - public void Create(IGalMemory Memory, long Key, GalShaderType Type) - { - Stages.GetOrAdd(Key, (Stage) => ShaderStageFactory(Memory, Key, 0, false, Type)); - } - - public void Create(IGalMemory Memory, long VpAPos, long Key, GalShaderType Type) - { - Stages.GetOrAdd(Key, (Stage) => ShaderStageFactory(Memory, VpAPos, Key, true, Type)); - } - - private OGLShaderStage ShaderStageFactory( - IGalMemory Memory, - long Position, - long PositionB, - bool IsDualVp, - GalShaderType Type) - { - GlslProgram Program; - - GlslDecompiler Decompiler = new GlslDecompiler(OGLLimit.MaxUboSize, OGLExtension.NvidiaDrvier); - - int ShaderDumpIndex = ShaderDumper.DumpIndex; - - if (IsDualVp) - { - ShaderDumper.Dump(Memory, Position, Type, "a"); - ShaderDumper.Dump(Memory, PositionB, Type, "b"); - - Program = Decompiler.Decompile(Memory, Position, PositionB, Type); - } - else - { - ShaderDumper.Dump(Memory, Position, Type); - - Program = Decompiler.Decompile(Memory, Position, Type); - } - - string Code = Program.Code; - - if (ShaderDumper.IsDumpEnabled()) - { - Code = "//Shader " + ShaderDumpIndex + Environment.NewLine + Code; - } - - return new OGLShaderStage(Type, Code, Program.Uniforms, Program.Textures); - } - - public IEnumerable GetConstBufferUsage(long Key) - { - if (Stages.TryGetValue(Key, out OGLShaderStage Stage)) - { - return Stage.ConstBufferUsage; - } - - return Enumerable.Empty(); - } - - public IEnumerable GetTextureUsage(long Key) - { - if (Stages.TryGetValue(Key, out OGLShaderStage Stage)) - { - return Stage.TextureUsage; - } - - return Enumerable.Empty(); - } - - public unsafe void SetExtraData(float FlipX, float FlipY, int Instance) - { - BindProgram(); - - EnsureExtraBlock(); - - GL.BindBuffer(BufferTarget.UniformBuffer, ExtraUboHandle); - - float* Data = stackalloc float[ExtraDataSize]; - Data[0] = FlipX; - Data[1] = FlipY; - Data[2] = BitConverter.Int32BitsToSingle(Instance); - - //Invalidate buffer - GL.BufferData(BufferTarget.UniformBuffer, ExtraDataSize * sizeof(float), IntPtr.Zero, BufferUsageHint.StreamDraw); - - GL.BufferSubData(BufferTarget.UniformBuffer, IntPtr.Zero, ExtraDataSize * sizeof(float), (IntPtr)Data); - } - - public void Bind(long Key) - { - if (Stages.TryGetValue(Key, out OGLShaderStage Stage)) - { - Bind(Stage); - } - } - - private void Bind(OGLShaderStage Stage) - { - if (Stage.Type == GalShaderType.Geometry) - { - //Enhanced layouts are required for Geometry shaders - //skip this stage if current driver has no ARB_enhanced_layouts - if (!OGLExtension.EnhancedLayouts) - { - return; - } - } - - switch (Stage.Type) - { - case GalShaderType.Vertex: Current.Vertex = Stage; break; - case GalShaderType.TessControl: Current.TessControl = Stage; break; - case GalShaderType.TessEvaluation: Current.TessEvaluation = Stage; break; - case GalShaderType.Geometry: Current.Geometry = Stage; break; - case GalShaderType.Fragment: Current.Fragment = Stage; break; - } - } - - public void Unbind(GalShaderType Type) - { - switch (Type) - { - case GalShaderType.Vertex: Current.Vertex = null; break; - case GalShaderType.TessControl: Current.TessControl = null; break; - case GalShaderType.TessEvaluation: Current.TessEvaluation = null; break; - case GalShaderType.Geometry: Current.Geometry = null; break; - case GalShaderType.Fragment: Current.Fragment = null; break; - } - } - - public void BindProgram() - { - if (Current.Vertex == null || - Current.Fragment == null) - { - return; - } - - if (!Programs.TryGetValue(Current, out int Handle)) - { - Handle = GL.CreateProgram(); - - AttachIfNotNull(Handle, Current.Vertex); - AttachIfNotNull(Handle, Current.TessControl); - AttachIfNotNull(Handle, Current.TessEvaluation); - AttachIfNotNull(Handle, Current.Geometry); - AttachIfNotNull(Handle, Current.Fragment); - - GL.LinkProgram(Handle); - - CheckProgramLink(Handle); - - BindUniformBlocks(Handle); - BindTextureLocations(Handle); - - Programs.Add(Current, Handle); - } - - GL.UseProgram(Handle); - - CurrentProgramHandle = Handle; - } - - private void EnsureExtraBlock() - { - if (ExtraUboHandle == 0) - { - ExtraUboHandle = GL.GenBuffer(); - - GL.BindBuffer(BufferTarget.UniformBuffer, ExtraUboHandle); - - GL.BufferData(BufferTarget.UniformBuffer, ExtraDataSize * sizeof(float), IntPtr.Zero, BufferUsageHint.StreamDraw); - - GL.BindBufferBase(BufferRangeTarget.UniformBuffer, 0, ExtraUboHandle); - } - } - - private void AttachIfNotNull(int ProgramHandle, OGLShaderStage Stage) - { - if (Stage != null) - { - Stage.Compile(); - - GL.AttachShader(ProgramHandle, Stage.Handle); - } - } - - private void BindUniformBlocks(int ProgramHandle) - { - int ExtraBlockindex = GL.GetUniformBlockIndex(ProgramHandle, GlslDecl.ExtraUniformBlockName); - - GL.UniformBlockBinding(ProgramHandle, ExtraBlockindex, 0); - - int FreeBinding = ReservedCbufCount; - - void BindUniformBlocksIfNotNull(OGLShaderStage Stage) - { - if (Stage != null) - { - foreach (ShaderDeclInfo DeclInfo in Stage.ConstBufferUsage) - { - int BlockIndex = GL.GetUniformBlockIndex(ProgramHandle, DeclInfo.Name); - - if (BlockIndex < 0) - { - //It is expected that its found, if it's not then driver might be in a malfunction - throw new InvalidOperationException(); - } - - GL.UniformBlockBinding(ProgramHandle, BlockIndex, FreeBinding); - - FreeBinding++; - } - } - } - - BindUniformBlocksIfNotNull(Current.Vertex); - BindUniformBlocksIfNotNull(Current.TessControl); - BindUniformBlocksIfNotNull(Current.TessEvaluation); - BindUniformBlocksIfNotNull(Current.Geometry); - BindUniformBlocksIfNotNull(Current.Fragment); - } - - private void BindTextureLocations(int ProgramHandle) - { - int Index = 0; - - void BindTexturesIfNotNull(OGLShaderStage Stage) - { - if (Stage != null) - { - foreach (ShaderDeclInfo Decl in Stage.TextureUsage) - { - int Location = GL.GetUniformLocation(ProgramHandle, Decl.Name); - - GL.Uniform1(Location, Index); - - Index++; - } - } - } - - GL.UseProgram(ProgramHandle); - - BindTexturesIfNotNull(Current.Vertex); - BindTexturesIfNotNull(Current.TessControl); - BindTexturesIfNotNull(Current.TessEvaluation); - BindTexturesIfNotNull(Current.Geometry); - BindTexturesIfNotNull(Current.Fragment); - } - - private static void CheckProgramLink(int Handle) - { - int Status = 0; - - GL.GetProgram(Handle, GetProgramParameterName.LinkStatus, out Status); - - if (Status == 0) - { - throw new ShaderException(GL.GetProgramInfoLog(Handle)); - } - } - } -} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLShaderProgram.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLShaderProgram.cs deleted file mode 100644 index c87b0d40..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLShaderProgram.cs +++ /dev/null @@ -1,86 +0,0 @@ -using OpenTK.Graphics.OpenGL; -using System; -using System.Collections.Generic; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - struct OGLShaderProgram - { - public OGLShaderStage Vertex; - public OGLShaderStage TessControl; - public OGLShaderStage TessEvaluation; - public OGLShaderStage Geometry; - public OGLShaderStage Fragment; - } - - class OGLShaderStage : IDisposable - { - public int Handle { get; private set; } - - public bool IsCompiled { get; private set; } - - public GalShaderType Type { get; private set; } - - public string Code { get; private set; } - - public IEnumerable ConstBufferUsage { get; private set; } - public IEnumerable TextureUsage { get; private set; } - - public OGLShaderStage( - GalShaderType Type, - string Code, - IEnumerable ConstBufferUsage, - IEnumerable TextureUsage) - { - this.Type = Type; - this.Code = Code; - this.ConstBufferUsage = ConstBufferUsage; - this.TextureUsage = TextureUsage; - } - - public void Compile() - { - if (Handle == 0) - { - Handle = GL.CreateShader(OGLEnumConverter.GetShaderType(Type)); - - CompileAndCheck(Handle, Code); - } - } - - public void Dispose() - { - Dispose(true); - } - - protected virtual void Dispose(bool Disposing) - { - if (Disposing && Handle != 0) - { - GL.DeleteShader(Handle); - - Handle = 0; - } - } - - public static void CompileAndCheck(int Handle, string Code) - { - GL.ShaderSource(Handle, Code); - GL.CompileShader(Handle); - - CheckCompilation(Handle); - } - - private static void CheckCompilation(int Handle) - { - int Status = 0; - - GL.GetShader(Handle, ShaderParameter.CompileStatus, out Status); - - if (Status == 0) - { - throw new ShaderException(GL.GetShaderInfoLog(Handle)); - } - } - } -} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs deleted file mode 100644 index 4fef11d2..00000000 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs +++ /dev/null @@ -1,381 +0,0 @@ -using OpenTK.Graphics.OpenGL; -using Ryujinx.Graphics.Texture; -using System; - -namespace Ryujinx.Graphics.Gal.OpenGL -{ - class OGLTexture : IGalTexture - { - private const long MaxTextureCacheSize = 768 * 1024 * 1024; - - private OGLCachedResource TextureCache; - - public EventHandler TextureDeleted { get; set; } - - public OGLTexture() - { - TextureCache = new OGLCachedResource(DeleteTexture, MaxTextureCacheSize); - } - - public void LockCache() - { - TextureCache.Lock(); - } - - public void UnlockCache() - { - TextureCache.Unlock(); - } - - private void DeleteTexture(ImageHandler CachedImage) - { - TextureDeleted?.Invoke(this, CachedImage.Handle); - - GL.DeleteTexture(CachedImage.Handle); - } - - public void Create(long Key, int Size, GalImage Image) - { - int Handle = GL.GenTexture(); - - TextureTarget Target = ImageUtils.GetTextureTarget(Image.TextureTarget); - - GL.BindTexture(Target, Handle); - - const int Level = 0; //TODO: Support mipmap textures. - const int Border = 0; - - TextureCache.AddOrUpdate(Key, new ImageHandler(Handle, Image), (uint)Size); - - if (ImageUtils.IsCompressed(Image.Format)) - { - throw new InvalidOperationException("Surfaces with compressed formats are not supported!"); - } - - (PixelInternalFormat InternalFmt, - PixelFormat Format, - PixelType Type) = OGLEnumConverter.GetImageFormat(Image.Format); - - switch (Target) - { - case TextureTarget.Texture1D: - GL.TexImage1D( - Target, - Level, - InternalFmt, - Image.Width, - Border, - Format, - Type, - IntPtr.Zero); - break; - - case TextureTarget.Texture2D: - GL.TexImage2D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Border, - Format, - Type, - IntPtr.Zero); - break; - case TextureTarget.Texture3D: - GL.TexImage3D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Image.Depth, - Border, - Format, - Type, - IntPtr.Zero); - break; - case TextureTarget.Texture2DArray: - GL.TexImage3D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Image.LayerCount, - Border, - Format, - Type, - IntPtr.Zero); - break; - default: - throw new NotImplementedException($"Unsupported texture target type: {Target}"); - } - } - - public void Create(long Key, byte[] Data, GalImage Image) - { - int Handle = GL.GenTexture(); - - TextureTarget Target = ImageUtils.GetTextureTarget(Image.TextureTarget); - - GL.BindTexture(Target, Handle); - - const int Level = 0; //TODO: Support mipmap textures. - const int Border = 0; - - TextureCache.AddOrUpdate(Key, new ImageHandler(Handle, Image), (uint)Data.Length); - - if (ImageUtils.IsCompressed(Image.Format) && !IsAstc(Image.Format)) - { - InternalFormat InternalFmt = OGLEnumConverter.GetCompressedImageFormat(Image.Format); - - switch (Target) - { - case TextureTarget.Texture1D: - GL.CompressedTexImage1D( - Target, - Level, - InternalFmt, - Image.Width, - Border, - Data.Length, - Data); - break; - case TextureTarget.Texture2D: - GL.CompressedTexImage2D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Border, - Data.Length, - Data); - break; - case TextureTarget.Texture3D: - GL.CompressedTexImage3D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Image.Depth, - Border, - Data.Length, - Data); - break; - case TextureTarget.Texture2DArray: - GL.CompressedTexImage3D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Image.LayerCount, - Border, - Data.Length, - Data); - break; - default: - throw new NotImplementedException($"Unsupported texture target type: {Target}"); - } - } - else - { - //TODO: Use KHR_texture_compression_astc_hdr when available - if (IsAstc(Image.Format)) - { - int TextureBlockWidth = ImageUtils.GetBlockWidth(Image.Format); - int TextureBlockHeight = ImageUtils.GetBlockHeight(Image.Format); - int TextureBlockDepth = ImageUtils.GetBlockDepth(Image.Format); - - Data = ASTCDecoder.DecodeToRGBA8888( - Data, - TextureBlockWidth, - TextureBlockHeight, - TextureBlockDepth, - Image.Width, - Image.Height, - Image.Depth); - - Image.Format = GalImageFormat.RGBA8 | (Image.Format & GalImageFormat.TypeMask); - } - - (PixelInternalFormat InternalFmt, - PixelFormat Format, - PixelType Type) = OGLEnumConverter.GetImageFormat(Image.Format); - - - switch (Target) - { - case TextureTarget.Texture1D: - GL.TexImage1D( - Target, - Level, - InternalFmt, - Image.Width, - Border, - Format, - Type, - Data); - break; - case TextureTarget.Texture2D: - GL.TexImage2D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Border, - Format, - Type, - Data); - break; - case TextureTarget.Texture3D: - GL.TexImage3D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Image.Depth, - Border, - Format, - Type, - Data); - break; - case TextureTarget.Texture2DArray: - GL.TexImage3D( - Target, - Level, - InternalFmt, - Image.Width, - Image.Height, - Image.LayerCount, - Border, - Format, - Type, - Data); - break; - case TextureTarget.TextureCubeMap: - Span Array = new Span(Data); - - int FaceSize = ImageUtils.GetSize(Image) / 6; - - for (int Face = 0; Face < 6; Face++) - { - GL.TexImage2D( - TextureTarget.TextureCubeMapPositiveX + Face, - Level, - InternalFmt, - Image.Width, - Image.Height, - Border, - Format, - Type, - Array.Slice(Face * FaceSize, FaceSize).ToArray()); - } - break; - default: - throw new NotImplementedException($"Unsupported texture target type: {Target}"); - } - } - } - - private static bool IsAstc(GalImageFormat Format) - { - Format &= GalImageFormat.FormatMask; - - return Format > GalImageFormat.Astc2DStart && Format < GalImageFormat.Astc2DEnd; - } - - public bool TryGetImage(long Key, out GalImage Image) - { - if (TextureCache.TryGetValue(Key, out ImageHandler CachedImage)) - { - Image = CachedImage.Image; - - return true; - } - - Image = default(GalImage); - - return false; - } - - public bool TryGetImageHandler(long Key, out ImageHandler CachedImage) - { - if (TextureCache.TryGetValue(Key, out CachedImage)) - { - return true; - } - - CachedImage = null; - - return false; - } - - public void Bind(long Key, int Index, GalImage Image) - { - if (TextureCache.TryGetValue(Key, out ImageHandler CachedImage)) - { - GL.ActiveTexture(TextureUnit.Texture0 + Index); - - TextureTarget Target = ImageUtils.GetTextureTarget(Image.TextureTarget); - - GL.BindTexture(Target, CachedImage.Handle); - - int[] SwizzleRgba = new int[] - { - (int)OGLEnumConverter.GetTextureSwizzle(Image.XSource), - (int)OGLEnumConverter.GetTextureSwizzle(Image.YSource), - (int)OGLEnumConverter.GetTextureSwizzle(Image.ZSource), - (int)OGLEnumConverter.GetTextureSwizzle(Image.WSource) - }; - - GL.TexParameter(Target, TextureParameterName.TextureSwizzleRgba, SwizzleRgba); - } - } - - public void SetSampler(GalImage Image, GalTextureSampler Sampler) - { - int WrapS = (int)OGLEnumConverter.GetTextureWrapMode(Sampler.AddressU); - int WrapT = (int)OGLEnumConverter.GetTextureWrapMode(Sampler.AddressV); - int WrapR = (int)OGLEnumConverter.GetTextureWrapMode(Sampler.AddressP); - - int MinFilter = (int)OGLEnumConverter.GetTextureMinFilter(Sampler.MinFilter, Sampler.MipFilter); - int MagFilter = (int)OGLEnumConverter.GetTextureMagFilter(Sampler.MagFilter); - - TextureTarget Target = ImageUtils.GetTextureTarget(Image.TextureTarget); - - GL.TexParameter(Target, TextureParameterName.TextureWrapS, WrapS); - GL.TexParameter(Target, TextureParameterName.TextureWrapT, WrapT); - GL.TexParameter(Target, TextureParameterName.TextureWrapR, WrapR); - - GL.TexParameter(Target, TextureParameterName.TextureMinFilter, MinFilter); - GL.TexParameter(Target, TextureParameterName.TextureMagFilter, MagFilter); - - float[] Color = new float[] - { - Sampler.BorderColor.Red, - Sampler.BorderColor.Green, - Sampler.BorderColor.Blue, - Sampler.BorderColor.Alpha - }; - - GL.TexParameter(Target, TextureParameterName.TextureBorderColor, Color); - - if (Sampler.DepthCompare) - { - GL.TexParameter(Target, TextureParameterName.TextureCompareMode, (int)All.CompareRToTexture); - GL.TexParameter(Target, TextureParameterName.TextureCompareFunc, (int)OGLEnumConverter.GetDepthCompareFunc(Sampler.DepthCompareFunc)); - } - else - { - GL.TexParameter(Target, TextureParameterName.TextureCompareMode, (int)All.None); - GL.TexParameter(Target, TextureParameterName.TextureCompareFunc, (int)All.Never); - } - } - } -} diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglCachedResource.cs b/Ryujinx.Graphics/Gal/OpenGL/OglCachedResource.cs new file mode 100644 index 00000000..91f0a7e1 --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglCachedResource.cs @@ -0,0 +1,191 @@ +using Ryujinx.Common; +using System; +using System.Collections.Generic; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + class OglCachedResource + { + public delegate void DeleteValue(T value); + + private const int MinTimeDelta = 5 * 60000; + private const int MaxRemovalsPerRun = 10; + + private struct CacheBucket + { + public T Value { get; private set; } + + public LinkedListNode Node { get; private set; } + + public long DataSize { get; private set; } + + public long Timestamp { get; private set; } + + public CacheBucket(T value, long dataSize, LinkedListNode node) + { + Value = value; + DataSize = dataSize; + Node = node; + + Timestamp = PerformanceCounter.ElapsedMilliseconds; + } + } + + private Dictionary _cache; + + private LinkedList _sortedCache; + + private DeleteValue _deleteValueCallback; + + private Queue _deletePending; + + private bool _locked; + + private long _maxSize; + private long _totalSize; + + public OglCachedResource(DeleteValue deleteValueCallback, long maxSize) + { + _maxSize = maxSize; + + if (deleteValueCallback == null) + { + throw new ArgumentNullException(nameof(deleteValueCallback)); + } + + _deleteValueCallback = deleteValueCallback; + + _cache = new Dictionary(); + + _sortedCache = new LinkedList(); + + _deletePending = new Queue(); + } + + public void Lock() + { + _locked = true; + } + + public void Unlock() + { + _locked = false; + + while (_deletePending.TryDequeue(out T value)) + { + _deleteValueCallback(value); + } + + ClearCacheIfNeeded(); + } + + public void AddOrUpdate(long key, T value, long size) + { + if (!_locked) + { + ClearCacheIfNeeded(); + } + + LinkedListNode node = _sortedCache.AddLast(key); + + CacheBucket newBucket = new CacheBucket(value, size, node); + + if (_cache.TryGetValue(key, out CacheBucket bucket)) + { + if (_locked) + { + _deletePending.Enqueue(bucket.Value); + } + else + { + _deleteValueCallback(bucket.Value); + } + + _sortedCache.Remove(bucket.Node); + + _totalSize -= bucket.DataSize; + + _cache[key] = newBucket; + } + else + { + _cache.Add(key, newBucket); + } + + _totalSize += size; + } + + public bool TryGetValue(long key, out T value) + { + if (_cache.TryGetValue(key, out CacheBucket bucket)) + { + value = bucket.Value; + + _sortedCache.Remove(bucket.Node); + + LinkedListNode node = _sortedCache.AddLast(key); + + _cache[key] = new CacheBucket(value, bucket.DataSize, node); + + return true; + } + + value = default(T); + + return false; + } + + public bool TryGetSize(long key, out long size) + { + if (_cache.TryGetValue(key, out CacheBucket bucket)) + { + size = bucket.DataSize; + + return true; + } + + size = 0; + + return false; + } + + private void ClearCacheIfNeeded() + { + long timestamp = PerformanceCounter.ElapsedMilliseconds; + + int count = 0; + + while (count++ < MaxRemovalsPerRun) + { + LinkedListNode node = _sortedCache.First; + + if (node == null) + { + break; + } + + CacheBucket bucket = _cache[node.Value]; + + long timeDelta = timestamp - bucket.Timestamp; + + if (timeDelta <= MinTimeDelta && !UnderMemoryPressure()) + { + break; + } + + _sortedCache.Remove(node); + + _cache.Remove(node.Value); + + _deleteValueCallback(bucket.Value); + + _totalSize -= bucket.DataSize; + } + } + + private bool UnderMemoryPressure() + { + return _totalSize >= _maxSize; + } + } +} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglConstBuffer.cs b/Ryujinx.Graphics/Gal/OpenGL/OglConstBuffer.cs new file mode 100644 index 00000000..e076be33 --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglConstBuffer.cs @@ -0,0 +1,74 @@ +using OpenTK.Graphics.OpenGL; +using System; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + class OglConstBuffer : IGalConstBuffer + { + private const long MaxConstBufferCacheSize = 64 * 1024 * 1024; + + private OglCachedResource _cache; + + public OglConstBuffer() + { + _cache = new OglCachedResource(DeleteBuffer, MaxConstBufferCacheSize); + } + + public void LockCache() + { + _cache.Lock(); + } + + public void UnlockCache() + { + _cache.Unlock(); + } + + public void Create(long key, long size) + { + OglStreamBuffer buffer = new OglStreamBuffer(BufferTarget.UniformBuffer, size); + + _cache.AddOrUpdate(key, buffer, size); + } + + public bool IsCached(long key, long size) + { + return _cache.TryGetSize(key, out long cachedSize) && cachedSize == size; + } + + public void SetData(long key, long size, IntPtr hostAddress) + { + if (_cache.TryGetValue(key, out OglStreamBuffer buffer)) + { + buffer.SetData(size, hostAddress); + } + } + + public void SetData(long key, byte[] data) + { + if (_cache.TryGetValue(key, out OglStreamBuffer buffer)) + { + buffer.SetData(data); + } + } + + public bool TryGetUbo(long key, out int uboHandle) + { + if (_cache.TryGetValue(key, out OglStreamBuffer buffer)) + { + uboHandle = buffer.Handle; + + return true; + } + + uboHandle = 0; + + return false; + } + + private static void DeleteBuffer(OglStreamBuffer buffer) + { + buffer.Dispose(); + } + } +} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLEnumConverter.cs b/Ryujinx.Graphics/Gal/OpenGL/OglEnumConverter.cs similarity index 79% rename from Ryujinx.Graphics/Gal/OpenGL/OGLEnumConverter.cs rename to Ryujinx.Graphics/Gal/OpenGL/OglEnumConverter.cs index 3a25fff7..a3f9957f 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLEnumConverter.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OglEnumConverter.cs @@ -3,34 +3,34 @@ using System; namespace Ryujinx.Graphics.Gal.OpenGL { - static class OGLEnumConverter + static class OglEnumConverter { - public static FrontFaceDirection GetFrontFace(GalFrontFace FrontFace) + public static FrontFaceDirection GetFrontFace(GalFrontFace frontFace) { - switch (FrontFace) + switch (frontFace) { - case GalFrontFace.CW: return FrontFaceDirection.Cw; - case GalFrontFace.CCW: return FrontFaceDirection.Ccw; + case GalFrontFace.Cw: return FrontFaceDirection.Cw; + case GalFrontFace.Ccw: return FrontFaceDirection.Ccw; } - throw new ArgumentException(nameof(FrontFace) + " \"" + FrontFace + "\" is not valid!"); + throw new ArgumentException(nameof(frontFace) + " \"" + frontFace + "\" is not valid!"); } - public static CullFaceMode GetCullFace(GalCullFace CullFace) + public static CullFaceMode GetCullFace(GalCullFace cullFace) { - switch (CullFace) + switch (cullFace) { case GalCullFace.Front: return CullFaceMode.Front; case GalCullFace.Back: return CullFaceMode.Back; case GalCullFace.FrontAndBack: return CullFaceMode.FrontAndBack; } - throw new ArgumentException(nameof(CullFace) + " \"" + CullFace + "\" is not valid!"); + throw new ArgumentException(nameof(cullFace) + " \"" + cullFace + "\" is not valid!"); } - public static StencilOp GetStencilOp(GalStencilOp Op) + public static StencilOp GetStencilOp(GalStencilOp op) { - switch (Op) + switch (op) { case GalStencilOp.Keep: return StencilOp.Keep; case GalStencilOp.Zero: return StencilOp.Zero; @@ -42,28 +42,28 @@ namespace Ryujinx.Graphics.Gal.OpenGL case GalStencilOp.DecrWrap: return StencilOp.DecrWrap; } - throw new ArgumentException(nameof(Op) + " \"" + Op + "\" is not valid!"); + throw new ArgumentException(nameof(op) + " \"" + op + "\" is not valid!"); } - public static DepthFunction GetDepthFunc(GalComparisonOp Func) + public static DepthFunction GetDepthFunc(GalComparisonOp func) { - return (DepthFunction)GetFunc(Func); + return (DepthFunction)GetFunc(func); } - public static StencilFunction GetStencilFunc(GalComparisonOp Func) + public static StencilFunction GetStencilFunc(GalComparisonOp func) { - return (StencilFunction)GetFunc(Func); + return (StencilFunction)GetFunc(func); } - private static All GetFunc(GalComparisonOp Func) + private static All GetFunc(GalComparisonOp func) { - if ((int)Func >= (int)All.Never && - (int)Func <= (int)All.Always) + if ((int)func >= (int)All.Never && + (int)func <= (int)All.Always) { - return (All)Func; + return (All)func; } - switch (Func) + switch (func) { case GalComparisonOp.Never: return All.Never; case GalComparisonOp.Less: return All.Less; @@ -75,24 +75,24 @@ namespace Ryujinx.Graphics.Gal.OpenGL case GalComparisonOp.Always: return All.Always; } - throw new ArgumentException(nameof(Func) + " \"" + Func + "\" is not valid!"); + throw new ArgumentException(nameof(func) + " \"" + func + "\" is not valid!"); } - public static DrawElementsType GetDrawElementsType(GalIndexFormat Format) + public static DrawElementsType GetDrawElementsType(GalIndexFormat format) { - switch (Format) + switch (format) { case GalIndexFormat.Byte: return DrawElementsType.UnsignedByte; case GalIndexFormat.Int16: return DrawElementsType.UnsignedShort; case GalIndexFormat.Int32: return DrawElementsType.UnsignedInt; } - throw new ArgumentException(nameof(Format) + " \"" + Format + "\" is not valid!"); + throw new ArgumentException(nameof(format) + " \"" + format + "\" is not valid!"); } - public static PrimitiveType GetPrimitiveType(GalPrimitiveType Type) + public static PrimitiveType GetPrimitiveType(GalPrimitiveType type) { - switch (Type) + switch (type) { case GalPrimitiveType.Points: return PrimitiveType.Points; case GalPrimitiveType.Lines: return PrimitiveType.Lines; @@ -109,12 +109,12 @@ namespace Ryujinx.Graphics.Gal.OpenGL case GalPrimitiveType.Patches: return PrimitiveType.Patches; } - throw new ArgumentException(nameof(Type) + " \"" + Type + "\" is not valid!"); + throw new ArgumentException(nameof(type) + " \"" + type + "\" is not valid!"); } - public static ShaderType GetShaderType(GalShaderType Type) + public static ShaderType GetShaderType(GalShaderType type) { - switch (Type) + switch (type) { case GalShaderType.Vertex: return ShaderType.VertexShader; case GalShaderType.TessControl: return ShaderType.TessControlShader; @@ -123,50 +123,50 @@ namespace Ryujinx.Graphics.Gal.OpenGL case GalShaderType.Fragment: return ShaderType.FragmentShader; } - throw new ArgumentException(nameof(Type) + " \"" + Type + "\" is not valid!"); + throw new ArgumentException(nameof(type) + " \"" + type + "\" is not valid!"); } - public static (PixelInternalFormat, PixelFormat, PixelType) GetImageFormat(GalImageFormat Format) + public static (PixelInternalFormat, PixelFormat, PixelType) GetImageFormat(GalImageFormat format) { - switch (Format) + switch (format) { - case GalImageFormat.RGBA32 | GalImageFormat.Float: return (PixelInternalFormat.Rgba32f, PixelFormat.Rgba, PixelType.Float); - case GalImageFormat.RGBA32 | GalImageFormat.Sint: return (PixelInternalFormat.Rgba32i, PixelFormat.RgbaInteger, PixelType.Int); - case GalImageFormat.RGBA32 | GalImageFormat.Uint: return (PixelInternalFormat.Rgba32ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt); - case GalImageFormat.RGBA16 | GalImageFormat.Float: return (PixelInternalFormat.Rgba16f, PixelFormat.Rgba, PixelType.HalfFloat); - case GalImageFormat.RGBA16 | GalImageFormat.Sint: return (PixelInternalFormat.Rgba16i, PixelFormat.RgbaInteger, PixelType.Short); - case GalImageFormat.RGBA16 | GalImageFormat.Uint: return (PixelInternalFormat.Rgba16ui, PixelFormat.RgbaInteger, PixelType.UnsignedShort); - case GalImageFormat.RGBA16 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba16, PixelFormat.Rgba, PixelType.UnsignedShort); - case GalImageFormat.RG32 | GalImageFormat.Float: return (PixelInternalFormat.Rg32f, PixelFormat.Rg, PixelType.Float); - case GalImageFormat.RG32 | GalImageFormat.Sint: return (PixelInternalFormat.Rg32i, PixelFormat.RgInteger, PixelType.Int); - case GalImageFormat.RG32 | GalImageFormat.Uint: return (PixelInternalFormat.Rg32ui, PixelFormat.RgInteger, PixelType.UnsignedInt); - case GalImageFormat.RGBX8 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgb8, PixelFormat.Rgba, PixelType.UnsignedByte); - case GalImageFormat.RGBA8 | GalImageFormat.Snorm: return (PixelInternalFormat.Rgba8Snorm, PixelFormat.Rgba, PixelType.Byte); - case GalImageFormat.RGBA8 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba8, PixelFormat.Rgba, PixelType.UnsignedByte); - case GalImageFormat.RGBA8 | GalImageFormat.Sint: return (PixelInternalFormat.Rgba8i, PixelFormat.RgbaInteger, PixelType.Byte); - case GalImageFormat.RGBA8 | GalImageFormat.Uint: return (PixelInternalFormat.Rgba8ui, PixelFormat.RgbaInteger, PixelType.UnsignedByte); - case GalImageFormat.RGBA8 | GalImageFormat.Srgb: return (PixelInternalFormat.Srgb8Alpha8, PixelFormat.Rgba, PixelType.UnsignedByte); - case GalImageFormat.BGRA8 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba8, PixelFormat.Bgra, PixelType.UnsignedByte); - case GalImageFormat.BGRA8 | GalImageFormat.Srgb: return (PixelInternalFormat.Srgb8Alpha8, PixelFormat.Bgra, PixelType.UnsignedByte); - case GalImageFormat.RGBA4 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba4, PixelFormat.Rgba, PixelType.UnsignedShort4444Reversed); - case GalImageFormat.RGB10A2 | GalImageFormat.Uint: return (PixelInternalFormat.Rgb10A2ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt2101010Reversed); - case GalImageFormat.RGB10A2 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgb10A2, PixelFormat.Rgba, PixelType.UnsignedInt2101010Reversed); + case GalImageFormat.Rgba32 | GalImageFormat.Float: return (PixelInternalFormat.Rgba32f, PixelFormat.Rgba, PixelType.Float); + case GalImageFormat.Rgba32 | GalImageFormat.Sint: return (PixelInternalFormat.Rgba32i, PixelFormat.RgbaInteger, PixelType.Int); + case GalImageFormat.Rgba32 | GalImageFormat.Uint: return (PixelInternalFormat.Rgba32ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt); + case GalImageFormat.Rgba16 | GalImageFormat.Float: return (PixelInternalFormat.Rgba16f, PixelFormat.Rgba, PixelType.HalfFloat); + case GalImageFormat.Rgba16 | GalImageFormat.Sint: return (PixelInternalFormat.Rgba16i, PixelFormat.RgbaInteger, PixelType.Short); + case GalImageFormat.Rgba16 | GalImageFormat.Uint: return (PixelInternalFormat.Rgba16ui, PixelFormat.RgbaInteger, PixelType.UnsignedShort); + case GalImageFormat.Rgba16 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba16, PixelFormat.Rgba, PixelType.UnsignedShort); + case GalImageFormat.Rg32 | GalImageFormat.Float: return (PixelInternalFormat.Rg32f, PixelFormat.Rg, PixelType.Float); + case GalImageFormat.Rg32 | GalImageFormat.Sint: return (PixelInternalFormat.Rg32i, PixelFormat.RgInteger, PixelType.Int); + case GalImageFormat.Rg32 | GalImageFormat.Uint: return (PixelInternalFormat.Rg32ui, PixelFormat.RgInteger, PixelType.UnsignedInt); + case GalImageFormat.Rgbx8 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgb8, PixelFormat.Rgba, PixelType.UnsignedByte); + case GalImageFormat.Rgba8 | GalImageFormat.Snorm: return (PixelInternalFormat.Rgba8Snorm, PixelFormat.Rgba, PixelType.Byte); + case GalImageFormat.Rgba8 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba8, PixelFormat.Rgba, PixelType.UnsignedByte); + case GalImageFormat.Rgba8 | GalImageFormat.Sint: return (PixelInternalFormat.Rgba8i, PixelFormat.RgbaInteger, PixelType.Byte); + case GalImageFormat.Rgba8 | GalImageFormat.Uint: return (PixelInternalFormat.Rgba8ui, PixelFormat.RgbaInteger, PixelType.UnsignedByte); + case GalImageFormat.Rgba8 | GalImageFormat.Srgb: return (PixelInternalFormat.Srgb8Alpha8, PixelFormat.Rgba, PixelType.UnsignedByte); + case GalImageFormat.Bgra8 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba8, PixelFormat.Bgra, PixelType.UnsignedByte); + case GalImageFormat.Bgra8 | GalImageFormat.Srgb: return (PixelInternalFormat.Srgb8Alpha8, PixelFormat.Bgra, PixelType.UnsignedByte); + case GalImageFormat.Rgba4 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba4, PixelFormat.Rgba, PixelType.UnsignedShort4444Reversed); + case GalImageFormat.Rgb10A2 | GalImageFormat.Uint: return (PixelInternalFormat.Rgb10A2ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt2101010Reversed); + case GalImageFormat.Rgb10A2 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgb10A2, PixelFormat.Rgba, PixelType.UnsignedInt2101010Reversed); case GalImageFormat.R32 | GalImageFormat.Float: return (PixelInternalFormat.R32f, PixelFormat.Red, PixelType.Float); case GalImageFormat.R32 | GalImageFormat.Sint: return (PixelInternalFormat.R32i, PixelFormat.Red, PixelType.Int); case GalImageFormat.R32 | GalImageFormat.Uint: return (PixelInternalFormat.R32ui, PixelFormat.Red, PixelType.UnsignedInt); - case GalImageFormat.BGR5A1 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgb5A1, PixelFormat.Rgba, PixelType.UnsignedShort5551); - case GalImageFormat.RGB5A1 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgb5A1, PixelFormat.Rgba, PixelType.UnsignedShort1555Reversed); - case GalImageFormat.RGB565 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba, PixelFormat.Rgb, PixelType.UnsignedShort565Reversed); - case GalImageFormat.BGR565 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba, PixelFormat.Rgb, PixelType.UnsignedShort565); - case GalImageFormat.RG16 | GalImageFormat.Float: return (PixelInternalFormat.Rg16f, PixelFormat.Rg, PixelType.HalfFloat); - case GalImageFormat.RG16 | GalImageFormat.Sint: return (PixelInternalFormat.Rg16i, PixelFormat.RgInteger, PixelType.Short); - case GalImageFormat.RG16 | GalImageFormat.Snorm: return (PixelInternalFormat.Rg16Snorm, PixelFormat.Rg, PixelType.Short); - case GalImageFormat.RG16 | GalImageFormat.Uint: return (PixelInternalFormat.Rg16ui, PixelFormat.RgInteger, PixelType.UnsignedShort); - case GalImageFormat.RG16 | GalImageFormat.Unorm: return (PixelInternalFormat.Rg16, PixelFormat.Rg, PixelType.UnsignedShort); - case GalImageFormat.RG8 | GalImageFormat.Sint: return (PixelInternalFormat.Rg8i, PixelFormat.RgInteger, PixelType.Byte); - case GalImageFormat.RG8 | GalImageFormat.Snorm: return (PixelInternalFormat.Rg8Snorm, PixelFormat.Rg, PixelType.Byte); - case GalImageFormat.RG8 | GalImageFormat.Uint: return (PixelInternalFormat.Rg8ui, PixelFormat.RgInteger, PixelType.UnsignedByte); - case GalImageFormat.RG8 | GalImageFormat.Unorm: return (PixelInternalFormat.Rg8, PixelFormat.Rg, PixelType.UnsignedByte); + case GalImageFormat.Bgr5A1 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgb5A1, PixelFormat.Rgba, PixelType.UnsignedShort5551); + case GalImageFormat.Rgb5A1 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgb5A1, PixelFormat.Rgba, PixelType.UnsignedShort1555Reversed); + case GalImageFormat.Rgb565 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba, PixelFormat.Rgb, PixelType.UnsignedShort565Reversed); + case GalImageFormat.Bgr565 | GalImageFormat.Unorm: return (PixelInternalFormat.Rgba, PixelFormat.Rgb, PixelType.UnsignedShort565); + case GalImageFormat.Rg16 | GalImageFormat.Float: return (PixelInternalFormat.Rg16f, PixelFormat.Rg, PixelType.HalfFloat); + case GalImageFormat.Rg16 | GalImageFormat.Sint: return (PixelInternalFormat.Rg16i, PixelFormat.RgInteger, PixelType.Short); + case GalImageFormat.Rg16 | GalImageFormat.Snorm: return (PixelInternalFormat.Rg16Snorm, PixelFormat.Rg, PixelType.Short); + case GalImageFormat.Rg16 | GalImageFormat.Uint: return (PixelInternalFormat.Rg16ui, PixelFormat.RgInteger, PixelType.UnsignedShort); + case GalImageFormat.Rg16 | GalImageFormat.Unorm: return (PixelInternalFormat.Rg16, PixelFormat.Rg, PixelType.UnsignedShort); + case GalImageFormat.Rg8 | GalImageFormat.Sint: return (PixelInternalFormat.Rg8i, PixelFormat.RgInteger, PixelType.Byte); + case GalImageFormat.Rg8 | GalImageFormat.Snorm: return (PixelInternalFormat.Rg8Snorm, PixelFormat.Rg, PixelType.Byte); + case GalImageFormat.Rg8 | GalImageFormat.Uint: return (PixelInternalFormat.Rg8ui, PixelFormat.RgInteger, PixelType.UnsignedByte); + case GalImageFormat.Rg8 | GalImageFormat.Unorm: return (PixelInternalFormat.Rg8, PixelFormat.Rg, PixelType.UnsignedByte); case GalImageFormat.R16 | GalImageFormat.Float: return (PixelInternalFormat.R16f, PixelFormat.Red, PixelType.HalfFloat); case GalImageFormat.R16 | GalImageFormat.Sint: return (PixelInternalFormat.R16i, PixelFormat.RedInteger, PixelType.Short); case GalImageFormat.R16 | GalImageFormat.Snorm: return (PixelInternalFormat.R16Snorm, PixelFormat.Red, PixelType.Short); @@ -186,12 +186,12 @@ namespace Ryujinx.Graphics.Gal.OpenGL case GalImageFormat.D32S8 | GalImageFormat.Float: return (PixelInternalFormat.Depth32fStencil8, PixelFormat.DepthStencil, PixelType.Float32UnsignedInt248Rev); } - throw new NotImplementedException($"{Format & GalImageFormat.FormatMask} {Format & GalImageFormat.TypeMask}"); + throw new NotImplementedException($"{format & GalImageFormat.FormatMask} {format & GalImageFormat.TypeMask}"); } - public static All GetDepthCompareFunc(DepthCompareFunc DepthCompareFunc) + public static All GetDepthCompareFunc(DepthCompareFunc depthCompareFunc) { - switch (DepthCompareFunc) + switch (depthCompareFunc) { case DepthCompareFunc.LEqual: return All.Lequal; @@ -210,13 +210,13 @@ namespace Ryujinx.Graphics.Gal.OpenGL case DepthCompareFunc.Never: return All.Never; default: - throw new ArgumentException(nameof(DepthCompareFunc) + " \"" + DepthCompareFunc + "\" is not valid!"); + throw new ArgumentException(nameof(depthCompareFunc) + " \"" + depthCompareFunc + "\" is not valid!"); } } - public static InternalFormat GetCompressedImageFormat(GalImageFormat Format) + public static InternalFormat GetCompressedImageFormat(GalImageFormat format) { - switch (Format) + switch (format) { case GalImageFormat.BptcSfloat | GalImageFormat.Float: return InternalFormat.CompressedRgbBptcSignedFloat; case GalImageFormat.BptcUfloat | GalImageFormat.Float: return InternalFormat.CompressedRgbBptcUnsignedFloat; @@ -234,12 +234,12 @@ namespace Ryujinx.Graphics.Gal.OpenGL case GalImageFormat.BC5 | GalImageFormat.Unorm: return InternalFormat.CompressedRgRgtc2; } - throw new NotImplementedException($"{Format & GalImageFormat.FormatMask} {Format & GalImageFormat.TypeMask}"); + throw new NotImplementedException($"{format & GalImageFormat.FormatMask} {format & GalImageFormat.TypeMask}"); } - public static All GetTextureSwizzle(GalTextureSource Source) + public static All GetTextureSwizzle(GalTextureSource source) { - switch (Source) + switch (source) { case GalTextureSource.Zero: return All.Zero; case GalTextureSource.Red: return All.Red; @@ -250,12 +250,12 @@ namespace Ryujinx.Graphics.Gal.OpenGL case GalTextureSource.OneFloat: return All.One; } - throw new ArgumentException(nameof(Source) + " \"" + Source + "\" is not valid!"); + throw new ArgumentException(nameof(source) + " \"" + source + "\" is not valid!"); } - public static TextureWrapMode GetTextureWrapMode(GalTextureWrap Wrap) + public static TextureWrapMode GetTextureWrapMode(GalTextureWrap wrap) { - switch (Wrap) + switch (wrap) { case GalTextureWrap.Repeat: return TextureWrapMode.Repeat; case GalTextureWrap.MirroredRepeat: return TextureWrapMode.MirroredRepeat; @@ -264,9 +264,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL case GalTextureWrap.Clamp: return TextureWrapMode.Clamp; } - if (OGLExtension.TextureMirrorClamp) + if (OglExtension.TextureMirrorClamp) { - switch (Wrap) + switch (wrap) { case GalTextureWrap.MirrorClampToEdge: return (TextureWrapMode)ExtTextureMirrorClamp.MirrorClampToEdgeExt; case GalTextureWrap.MirrorClampToBorder: return (TextureWrapMode)ExtTextureMirrorClamp.MirrorClampToBorderExt; @@ -276,7 +276,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL else { //Fallback to non-mirrored clamps - switch (Wrap) + switch (wrap) { case GalTextureWrap.MirrorClampToEdge: return TextureWrapMode.ClampToEdge; case GalTextureWrap.MirrorClampToBorder: return TextureWrapMode.ClampToBorder; @@ -284,37 +284,37 @@ namespace Ryujinx.Graphics.Gal.OpenGL } } - throw new ArgumentException(nameof(Wrap) + " \"" + Wrap + "\" is not valid!"); + throw new ArgumentException(nameof(wrap) + " \"" + wrap + "\" is not valid!"); } public static TextureMinFilter GetTextureMinFilter( - GalTextureFilter MinFilter, - GalTextureMipFilter MipFilter) + GalTextureFilter minFilter, + GalTextureMipFilter mipFilter) { //TODO: Mip (needs mipmap support first). - switch (MinFilter) + switch (minFilter) { case GalTextureFilter.Nearest: return TextureMinFilter.Nearest; case GalTextureFilter.Linear: return TextureMinFilter.Linear; } - throw new ArgumentException(nameof(MinFilter) + " \"" + MinFilter + "\" is not valid!"); + throw new ArgumentException(nameof(minFilter) + " \"" + minFilter + "\" is not valid!"); } - public static TextureMagFilter GetTextureMagFilter(GalTextureFilter Filter) + public static TextureMagFilter GetTextureMagFilter(GalTextureFilter filter) { - switch (Filter) + switch (filter) { case GalTextureFilter.Nearest: return TextureMagFilter.Nearest; case GalTextureFilter.Linear: return TextureMagFilter.Linear; } - throw new ArgumentException(nameof(Filter) + " \"" + Filter + "\" is not valid!"); + throw new ArgumentException(nameof(filter) + " \"" + filter + "\" is not valid!"); } - public static BlendEquationMode GetBlendEquation(GalBlendEquation BlendEquation) + public static BlendEquationMode GetBlendEquation(GalBlendEquation blendEquation) { - switch (BlendEquation) + switch (blendEquation) { case GalBlendEquation.FuncAdd: case GalBlendEquation.FuncAddGl: @@ -337,12 +337,12 @@ namespace Ryujinx.Graphics.Gal.OpenGL return BlendEquationMode.Max; } - throw new ArgumentException(nameof(BlendEquation) + " \"" + BlendEquation + "\" is not valid!"); + throw new ArgumentException(nameof(blendEquation) + " \"" + blendEquation + "\" is not valid!"); } - public static BlendingFactor GetBlendFactor(GalBlendFactor BlendFactor) + public static BlendingFactor GetBlendFactor(GalBlendFactor blendFactor) { - switch (BlendFactor) + switch (blendFactor) { case GalBlendFactor.Zero: case GalBlendFactor.ZeroGl: @@ -421,7 +421,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL return BlendingFactor.ConstantColor; } - throw new ArgumentException(nameof(BlendFactor) + " \"" + BlendFactor + "\" is not valid!"); + throw new ArgumentException(nameof(blendFactor) + " \"" + blendFactor + "\" is not valid!"); } } } diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglExtension.cs b/Ryujinx.Graphics/Gal/OpenGL/OglExtension.cs new file mode 100644 index 00000000..8a1a0510 --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglExtension.cs @@ -0,0 +1,70 @@ +using OpenTK.Graphics.OpenGL; +using Ryujinx.Common.Logging; +using System; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + static class OglExtension + { + // Private lazy backing variables + private static Lazy _enhancedLayouts = new Lazy(() => HasExtension("GL_ARB_enhanced_layouts")); + private static Lazy _textureMirrorClamp = new Lazy(() => HasExtension("GL_EXT_texture_mirror_clamp")); + private static Lazy _viewportArray = new Lazy(() => HasExtension("GL_ARB_viewport_array")); + + private static Lazy _nvidiaDriver = new Lazy(() => IsNvidiaDriver()); + + // Public accessors + public static bool EnhancedLayouts => _enhancedLayouts.Value; + public static bool TextureMirrorClamp => _textureMirrorClamp.Value; + public static bool ViewportArray => _viewportArray.Value; + + public static bool NvidiaDriver => _nvidiaDriver.Value; + + private static bool HasExtension(string name) + { + int numExtensions = GL.GetInteger(GetPName.NumExtensions); + + for (int extension = 0; extension < numExtensions; extension++) + { + if (GL.GetString(StringNameIndexed.Extensions, extension) == name) + { + return true; + } + } + + Logger.PrintInfo(LogClass.Gpu, $"OpenGL extension {name} unavailable. You may experience some performance degradation"); + + return false; + } + + private static bool IsNvidiaDriver() + { + return GL.GetString(StringName.Vendor).Equals("NVIDIA Corporation"); + } + + public static class Required + { + // Public accessors + public static bool EnhancedLayouts => _enhancedLayoutsRequired.Value; + public static bool TextureMirrorClamp => _textureMirrorClampRequired.Value; + public static bool ViewportArray => _viewportArrayRequired.Value; + + // Private lazy backing variables + private static Lazy _enhancedLayoutsRequired = new Lazy(() => HasExtensionRequired(OglExtension.EnhancedLayouts, "GL_ARB_enhanced_layouts")); + private static Lazy _textureMirrorClampRequired = new Lazy(() => HasExtensionRequired(OglExtension.TextureMirrorClamp, "GL_EXT_texture_mirror_clamp")); + private static Lazy _viewportArrayRequired = new Lazy(() => HasExtensionRequired(OglExtension.ViewportArray, "GL_ARB_viewport_array")); + + private static bool HasExtensionRequired(bool value, string name) + { + if (value) + { + return true; + } + + Logger.PrintWarning(LogClass.Gpu, $"Required OpenGL extension {name} unavailable. You may experience some rendering issues"); + + return false; + } + } + } +} diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglLimit.cs b/Ryujinx.Graphics/Gal/OpenGL/OglLimit.cs new file mode 100644 index 00000000..2a227a37 --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglLimit.cs @@ -0,0 +1,12 @@ +using OpenTK.Graphics.OpenGL; +using System; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + static class OglLimit + { + private static Lazy _sMaxUboSize = new Lazy(() => GL.GetInteger(GetPName.MaxUniformBlockSize)); + + public static int MaxUboSize => _sMaxUboSize.Value; + } +} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLPipeline.cs b/Ryujinx.Graphics/Gal/OpenGL/OglPipeline.cs similarity index 56% rename from Ryujinx.Graphics/Gal/OpenGL/OGLPipeline.cs rename to Ryujinx.Graphics/Gal/OpenGL/OglPipeline.cs index 96d42e02..3c8ada3e 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLPipeline.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OglPipeline.cs @@ -4,9 +4,9 @@ using System.Collections.Generic; namespace Ryujinx.Graphics.Gal.OpenGL { - class OGLPipeline : IGalPipeline + class OglPipeline : IGalPipeline { - private static Dictionary AttribElements = + private static Dictionary _attribElements = new Dictionary() { { GalVertexAttribSize._32_32_32_32, 4 }, @@ -25,7 +25,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL { GalVertexAttribSize._11_11_10, 3 } }; - private static Dictionary FloatAttribTypes = + private static Dictionary _floatAttribTypes = new Dictionary() { { GalVertexAttribSize._32_32_32_32, VertexAttribPointerType.Float }, @@ -38,7 +38,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL { GalVertexAttribSize._16, VertexAttribPointerType.HalfFloat } }; - private static Dictionary SignedAttribTypes = + private static Dictionary _signedAttribTypes = new Dictionary() { { GalVertexAttribSize._32_32_32_32, VertexAttribPointerType.Int }, @@ -56,7 +56,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL { GalVertexAttribSize._10_10_10_2, VertexAttribPointerType.Int2101010Rev } }; - private static Dictionary UnsignedAttribTypes = + private static Dictionary _unsignedAttribTypes = new Dictionary() { { GalVertexAttribSize._32_32_32_32, VertexAttribPointerType.UnsignedInt }, @@ -75,30 +75,30 @@ namespace Ryujinx.Graphics.Gal.OpenGL { GalVertexAttribSize._11_11_10, VertexAttribPointerType.UnsignedInt10F11F11FRev } }; - private GalPipelineState Old; + private GalPipelineState _old; - private OGLConstBuffer Buffer; - private OGLRenderTarget RenderTarget; - private OGLRasterizer Rasterizer; - private OGLShader Shader; + private OglConstBuffer _buffer; + private OglRenderTarget _renderTarget; + private OglRasterizer _rasterizer; + private OglShader _shader; - private int VaoHandle; + private int _vaoHandle; - public OGLPipeline( - OGLConstBuffer Buffer, - OGLRenderTarget RenderTarget, - OGLRasterizer Rasterizer, - OGLShader Shader) + public OglPipeline( + OglConstBuffer buffer, + OglRenderTarget renderTarget, + OglRasterizer rasterizer, + OglShader shader) { - this.Buffer = Buffer; - this.RenderTarget = RenderTarget; - this.Rasterizer = Rasterizer; - this.Shader = Shader; + _buffer = buffer; + _renderTarget = renderTarget; + _rasterizer = rasterizer; + _shader = shader; //These values match OpenGL's defaults - Old = new GalPipelineState + _old = new GalPipelineState { - FrontFace = GalFrontFace.CCW, + FrontFace = GalFrontFace.Ccw, CullFaceEnabled = false, CullFace = GalCullFace.Back, @@ -133,11 +133,11 @@ namespace Ryujinx.Graphics.Gal.OpenGL PrimitiveRestartIndex = 0 }; - for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++) + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) { - Old.Blends[Index] = BlendState.Default; + _old.Blends[index] = BlendState.Default; - Old.ColorMasks[Index] = ColorMaskState.Default; + _old.ColorMasks[index] = ColorMaskState.Default; } } @@ -147,122 +147,122 @@ namespace Ryujinx.Graphics.Gal.OpenGL BindVertexLayout(New); - if (New.FramebufferSrgb != Old.FramebufferSrgb) + if (New.FramebufferSrgb != _old.FramebufferSrgb) { Enable(EnableCap.FramebufferSrgb, New.FramebufferSrgb); - RenderTarget.FramebufferSrgb = New.FramebufferSrgb; + _renderTarget.FramebufferSrgb = New.FramebufferSrgb; } - if (New.FlipX != Old.FlipX || New.FlipY != Old.FlipY || New.Instance != Old.Instance) + if (New.FlipX != _old.FlipX || New.FlipY != _old.FlipY || New.Instance != _old.Instance) { - Shader.SetExtraData(New.FlipX, New.FlipY, New.Instance); + _shader.SetExtraData(New.FlipX, New.FlipY, New.Instance); } - if (New.FrontFace != Old.FrontFace) + if (New.FrontFace != _old.FrontFace) { - GL.FrontFace(OGLEnumConverter.GetFrontFace(New.FrontFace)); + GL.FrontFace(OglEnumConverter.GetFrontFace(New.FrontFace)); } - if (New.CullFaceEnabled != Old.CullFaceEnabled) + if (New.CullFaceEnabled != _old.CullFaceEnabled) { Enable(EnableCap.CullFace, New.CullFaceEnabled); } if (New.CullFaceEnabled) { - if (New.CullFace != Old.CullFace) + if (New.CullFace != _old.CullFace) { - GL.CullFace(OGLEnumConverter.GetCullFace(New.CullFace)); + GL.CullFace(OglEnumConverter.GetCullFace(New.CullFace)); } } - if (New.DepthTestEnabled != Old.DepthTestEnabled) + if (New.DepthTestEnabled != _old.DepthTestEnabled) { Enable(EnableCap.DepthTest, New.DepthTestEnabled); } - if (New.DepthWriteEnabled != Old.DepthWriteEnabled) + if (New.DepthWriteEnabled != _old.DepthWriteEnabled) { GL.DepthMask(New.DepthWriteEnabled); } if (New.DepthTestEnabled) { - if (New.DepthFunc != Old.DepthFunc) + if (New.DepthFunc != _old.DepthFunc) { - GL.DepthFunc(OGLEnumConverter.GetDepthFunc(New.DepthFunc)); + GL.DepthFunc(OglEnumConverter.GetDepthFunc(New.DepthFunc)); } } - if (New.DepthRangeNear != Old.DepthRangeNear || - New.DepthRangeFar != Old.DepthRangeFar) + if (New.DepthRangeNear != _old.DepthRangeNear || + New.DepthRangeFar != _old.DepthRangeFar) { GL.DepthRange(New.DepthRangeNear, New.DepthRangeFar); } - if (New.StencilTestEnabled != Old.StencilTestEnabled) + if (New.StencilTestEnabled != _old.StencilTestEnabled) { Enable(EnableCap.StencilTest, New.StencilTestEnabled); } - if (New.StencilTwoSideEnabled != Old.StencilTwoSideEnabled) + if (New.StencilTwoSideEnabled != _old.StencilTwoSideEnabled) { Enable((EnableCap)All.StencilTestTwoSideExt, New.StencilTwoSideEnabled); } if (New.StencilTestEnabled) { - if (New.StencilBackFuncFunc != Old.StencilBackFuncFunc || - New.StencilBackFuncRef != Old.StencilBackFuncRef || - New.StencilBackFuncMask != Old.StencilBackFuncMask) + if (New.StencilBackFuncFunc != _old.StencilBackFuncFunc || + New.StencilBackFuncRef != _old.StencilBackFuncRef || + New.StencilBackFuncMask != _old.StencilBackFuncMask) { GL.StencilFuncSeparate( StencilFace.Back, - OGLEnumConverter.GetStencilFunc(New.StencilBackFuncFunc), + OglEnumConverter.GetStencilFunc(New.StencilBackFuncFunc), New.StencilBackFuncRef, New.StencilBackFuncMask); } - if (New.StencilBackOpFail != Old.StencilBackOpFail || - New.StencilBackOpZFail != Old.StencilBackOpZFail || - New.StencilBackOpZPass != Old.StencilBackOpZPass) + if (New.StencilBackOpFail != _old.StencilBackOpFail || + New.StencilBackOpZFail != _old.StencilBackOpZFail || + New.StencilBackOpZPass != _old.StencilBackOpZPass) { GL.StencilOpSeparate( StencilFace.Back, - OGLEnumConverter.GetStencilOp(New.StencilBackOpFail), - OGLEnumConverter.GetStencilOp(New.StencilBackOpZFail), - OGLEnumConverter.GetStencilOp(New.StencilBackOpZPass)); + OglEnumConverter.GetStencilOp(New.StencilBackOpFail), + OglEnumConverter.GetStencilOp(New.StencilBackOpZFail), + OglEnumConverter.GetStencilOp(New.StencilBackOpZPass)); } - if (New.StencilBackMask != Old.StencilBackMask) + if (New.StencilBackMask != _old.StencilBackMask) { GL.StencilMaskSeparate(StencilFace.Back, New.StencilBackMask); } - if (New.StencilFrontFuncFunc != Old.StencilFrontFuncFunc || - New.StencilFrontFuncRef != Old.StencilFrontFuncRef || - New.StencilFrontFuncMask != Old.StencilFrontFuncMask) + if (New.StencilFrontFuncFunc != _old.StencilFrontFuncFunc || + New.StencilFrontFuncRef != _old.StencilFrontFuncRef || + New.StencilFrontFuncMask != _old.StencilFrontFuncMask) { GL.StencilFuncSeparate( StencilFace.Front, - OGLEnumConverter.GetStencilFunc(New.StencilFrontFuncFunc), + OglEnumConverter.GetStencilFunc(New.StencilFrontFuncFunc), New.StencilFrontFuncRef, New.StencilFrontFuncMask); } - if (New.StencilFrontOpFail != Old.StencilFrontOpFail || - New.StencilFrontOpZFail != Old.StencilFrontOpZFail || - New.StencilFrontOpZPass != Old.StencilFrontOpZPass) + if (New.StencilFrontOpFail != _old.StencilFrontOpFail || + New.StencilFrontOpZFail != _old.StencilFrontOpZFail || + New.StencilFrontOpZPass != _old.StencilFrontOpZPass) { GL.StencilOpSeparate( StencilFace.Front, - OGLEnumConverter.GetStencilOp(New.StencilFrontOpFail), - OGLEnumConverter.GetStencilOp(New.StencilFrontOpZFail), - OGLEnumConverter.GetStencilOp(New.StencilFrontOpZPass)); + OglEnumConverter.GetStencilOp(New.StencilFrontOpFail), + OglEnumConverter.GetStencilOp(New.StencilFrontOpZFail), + OglEnumConverter.GetStencilOp(New.StencilFrontOpZPass)); } - if (New.StencilFrontMask != Old.StencilFrontMask) + if (New.StencilFrontMask != _old.StencilFrontMask) { GL.StencilMaskSeparate(StencilFace.Front, New.StencilFrontMask); } @@ -277,42 +277,42 @@ namespace Ryujinx.Graphics.Gal.OpenGL int scissorsApplied = 0; bool applyToAll = false; - for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++) + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) { - if (New.ScissorTestEnabled[Index]) + if (New.ScissorTestEnabled[index]) { // If viewport arrays are unavailable apply first scissor test to all or // there is only 1 scissor test and it's the first, the scissor test applies to all viewports - if (!OGLExtension.Required.ViewportArray || (Index == 0 && New.ScissorTestCount == 1)) + if (!OglExtension.Required.ViewportArray || (index == 0 && New.ScissorTestCount == 1)) { GL.Enable(EnableCap.ScissorTest); applyToAll = true; } else { - GL.Enable(IndexedEnableCap.ScissorTest, Index); + GL.Enable(IndexedEnableCap.ScissorTest, index); } - if (New.ScissorTestEnabled[Index] != Old.ScissorTestEnabled[Index] || - New.ScissorTestX[Index] != Old.ScissorTestX[Index] || - New.ScissorTestY[Index] != Old.ScissorTestY[Index] || - New.ScissorTestWidth[Index] != Old.ScissorTestWidth[Index] || - New.ScissorTestHeight[Index] != Old.ScissorTestHeight[Index]) + if (New.ScissorTestEnabled[index] != _old.ScissorTestEnabled[index] || + New.ScissorTestX[index] != _old.ScissorTestX[index] || + New.ScissorTestY[index] != _old.ScissorTestY[index] || + New.ScissorTestWidth[index] != _old.ScissorTestWidth[index] || + New.ScissorTestHeight[index] != _old.ScissorTestHeight[index]) { if (applyToAll) { - GL.Scissor(New.ScissorTestX[Index], New.ScissorTestY[Index], - New.ScissorTestWidth[Index], New.ScissorTestHeight[Index]); + GL.Scissor(New.ScissorTestX[index], New.ScissorTestY[index], + New.ScissorTestWidth[index], New.ScissorTestHeight[index]); } else { - GL.ScissorIndexed(Index, New.ScissorTestX[Index], New.ScissorTestY[Index], - New.ScissorTestWidth[Index], New.ScissorTestHeight[Index]); + GL.ScissorIndexed(index, New.ScissorTestX[index], New.ScissorTestY[index], + New.ScissorTestWidth[index], New.ScissorTestHeight[index]); } } - // If all scissor tests have been applied, or viewport arrays are unavailable we can skip remaining itterations - if (!OGLExtension.Required.ViewportArray || ++scissorsApplied == New.ScissorTestCount) + // If all scissor tests have been applied, or viewport arrays are unavailable we can skip remaining iterations + if (!OglExtension.Required.ViewportArray || ++scissorsApplied == New.ScissorTestCount) { break; } @@ -323,26 +323,26 @@ namespace Ryujinx.Graphics.Gal.OpenGL if (New.BlendIndependent) { - for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++) + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) { - SetBlendState(Index, New.Blends[Index], Old.Blends[Index]); + SetBlendState(index, New.Blends[index], _old.Blends[index]); } } else { - if (New.BlendIndependent != Old.BlendIndependent) + if (New.BlendIndependent != _old.BlendIndependent) { SetAllBlendState(New.Blends[0]); } else { - SetBlendState(New.Blends[0], Old.Blends[0]); + SetBlendState(New.Blends[0], _old.Blends[0]); } } if (New.ColorMaskCommon) { - if (New.ColorMaskCommon != Old.ColorMaskCommon || !New.ColorMasks[0].Equals(Old.ColorMasks[0])) + if (New.ColorMaskCommon != _old.ColorMaskCommon || !New.ColorMasks[0].Equals(_old.ColorMasks[0])) { GL.ColorMask( New.ColorMasks[0].Red, @@ -353,39 +353,39 @@ namespace Ryujinx.Graphics.Gal.OpenGL } else { - for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++) + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) { - if (!New.ColorMasks[Index].Equals(Old.ColorMasks[Index])) + if (!New.ColorMasks[index].Equals(_old.ColorMasks[index])) { GL.ColorMask( - Index, - New.ColorMasks[Index].Red, - New.ColorMasks[Index].Green, - New.ColorMasks[Index].Blue, - New.ColorMasks[Index].Alpha); + index, + New.ColorMasks[index].Red, + New.ColorMasks[index].Green, + New.ColorMasks[index].Blue, + New.ColorMasks[index].Alpha); } } } - if (New.PrimitiveRestartEnabled != Old.PrimitiveRestartEnabled) + if (New.PrimitiveRestartEnabled != _old.PrimitiveRestartEnabled) { Enable(EnableCap.PrimitiveRestart, New.PrimitiveRestartEnabled); } if (New.PrimitiveRestartEnabled) { - if (New.PrimitiveRestartIndex != Old.PrimitiveRestartIndex) + if (New.PrimitiveRestartIndex != _old.PrimitiveRestartIndex) { GL.PrimitiveRestartIndex(New.PrimitiveRestartIndex); } } - Old = New; + _old = New; } - public void Unbind(GalPipelineState State) + public void Unbind(GalPipelineState state) { - if (State.ScissorTestCount > 0) + if (state.ScissorTestCount > 0) { GL.Disable(EnableCap.ScissorTest); } @@ -400,29 +400,29 @@ namespace Ryujinx.Graphics.Gal.OpenGL if (New.SeparateAlpha) { GL.BlendEquationSeparate( - OGLEnumConverter.GetBlendEquation(New.EquationRgb), - OGLEnumConverter.GetBlendEquation(New.EquationAlpha)); + OglEnumConverter.GetBlendEquation(New.EquationRgb), + OglEnumConverter.GetBlendEquation(New.EquationAlpha)); GL.BlendFuncSeparate( - (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.FuncSrcRgb), - (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.FuncDstRgb), - (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.FuncSrcAlpha), - (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.FuncDstAlpha)); + (BlendingFactorSrc) OglEnumConverter.GetBlendFactor(New.FuncSrcRgb), + (BlendingFactorDest)OglEnumConverter.GetBlendFactor(New.FuncDstRgb), + (BlendingFactorSrc) OglEnumConverter.GetBlendFactor(New.FuncSrcAlpha), + (BlendingFactorDest)OglEnumConverter.GetBlendFactor(New.FuncDstAlpha)); } else { - GL.BlendEquation(OGLEnumConverter.GetBlendEquation(New.EquationRgb)); + GL.BlendEquation(OglEnumConverter.GetBlendEquation(New.EquationRgb)); GL.BlendFunc( - OGLEnumConverter.GetBlendFactor(New.FuncSrcRgb), - OGLEnumConverter.GetBlendFactor(New.FuncDstRgb)); + OglEnumConverter.GetBlendFactor(New.FuncSrcRgb), + OglEnumConverter.GetBlendFactor(New.FuncDstRgb)); } } } - private void SetBlendState(BlendState New, BlendState Old) + private void SetBlendState(BlendState New, BlendState old) { - if (New.Enabled != Old.Enabled) + if (New.Enabled != old.Enabled) { Enable(EnableCap.Blend, New.Enabled); } @@ -431,91 +431,91 @@ namespace Ryujinx.Graphics.Gal.OpenGL { if (New.SeparateAlpha) { - if (New.EquationRgb != Old.EquationRgb || - New.EquationAlpha != Old.EquationAlpha) + if (New.EquationRgb != old.EquationRgb || + New.EquationAlpha != old.EquationAlpha) { GL.BlendEquationSeparate( - OGLEnumConverter.GetBlendEquation(New.EquationRgb), - OGLEnumConverter.GetBlendEquation(New.EquationAlpha)); + OglEnumConverter.GetBlendEquation(New.EquationRgb), + OglEnumConverter.GetBlendEquation(New.EquationAlpha)); } - if (New.FuncSrcRgb != Old.FuncSrcRgb || - New.FuncDstRgb != Old.FuncDstRgb || - New.FuncSrcAlpha != Old.FuncSrcAlpha || - New.FuncDstAlpha != Old.FuncDstAlpha) + if (New.FuncSrcRgb != old.FuncSrcRgb || + New.FuncDstRgb != old.FuncDstRgb || + New.FuncSrcAlpha != old.FuncSrcAlpha || + New.FuncDstAlpha != old.FuncDstAlpha) { GL.BlendFuncSeparate( - (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.FuncSrcRgb), - (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.FuncDstRgb), - (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.FuncSrcAlpha), - (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.FuncDstAlpha)); + (BlendingFactorSrc) OglEnumConverter.GetBlendFactor(New.FuncSrcRgb), + (BlendingFactorDest)OglEnumConverter.GetBlendFactor(New.FuncDstRgb), + (BlendingFactorSrc) OglEnumConverter.GetBlendFactor(New.FuncSrcAlpha), + (BlendingFactorDest)OglEnumConverter.GetBlendFactor(New.FuncDstAlpha)); } } else { - if (New.EquationRgb != Old.EquationRgb) + if (New.EquationRgb != old.EquationRgb) { - GL.BlendEquation(OGLEnumConverter.GetBlendEquation(New.EquationRgb)); + GL.BlendEquation(OglEnumConverter.GetBlendEquation(New.EquationRgb)); } - if (New.FuncSrcRgb != Old.FuncSrcRgb || - New.FuncDstRgb != Old.FuncDstRgb) + if (New.FuncSrcRgb != old.FuncSrcRgb || + New.FuncDstRgb != old.FuncDstRgb) { GL.BlendFunc( - OGLEnumConverter.GetBlendFactor(New.FuncSrcRgb), - OGLEnumConverter.GetBlendFactor(New.FuncDstRgb)); + OglEnumConverter.GetBlendFactor(New.FuncSrcRgb), + OglEnumConverter.GetBlendFactor(New.FuncDstRgb)); } } } } - private void SetBlendState(int Index, BlendState New, BlendState Old) + private void SetBlendState(int index, BlendState New, BlendState old) { - if (New.Enabled != Old.Enabled) + if (New.Enabled != old.Enabled) { - Enable(IndexedEnableCap.Blend, Index, New.Enabled); + Enable(IndexedEnableCap.Blend, index, New.Enabled); } if (New.Enabled) { if (New.SeparateAlpha) { - if (New.EquationRgb != Old.EquationRgb || - New.EquationAlpha != Old.EquationAlpha) + if (New.EquationRgb != old.EquationRgb || + New.EquationAlpha != old.EquationAlpha) { GL.BlendEquationSeparate( - Index, - OGLEnumConverter.GetBlendEquation(New.EquationRgb), - OGLEnumConverter.GetBlendEquation(New.EquationAlpha)); + index, + OglEnumConverter.GetBlendEquation(New.EquationRgb), + OglEnumConverter.GetBlendEquation(New.EquationAlpha)); } - if (New.FuncSrcRgb != Old.FuncSrcRgb || - New.FuncDstRgb != Old.FuncDstRgb || - New.FuncSrcAlpha != Old.FuncSrcAlpha || - New.FuncDstAlpha != Old.FuncDstAlpha) + if (New.FuncSrcRgb != old.FuncSrcRgb || + New.FuncDstRgb != old.FuncDstRgb || + New.FuncSrcAlpha != old.FuncSrcAlpha || + New.FuncDstAlpha != old.FuncDstAlpha) { GL.BlendFuncSeparate( - Index, - (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.FuncSrcRgb), - (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.FuncDstRgb), - (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.FuncSrcAlpha), - (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.FuncDstAlpha)); + index, + (BlendingFactorSrc) OglEnumConverter.GetBlendFactor(New.FuncSrcRgb), + (BlendingFactorDest)OglEnumConverter.GetBlendFactor(New.FuncDstRgb), + (BlendingFactorSrc) OglEnumConverter.GetBlendFactor(New.FuncSrcAlpha), + (BlendingFactorDest)OglEnumConverter.GetBlendFactor(New.FuncDstAlpha)); } } else { - if (New.EquationRgb != Old.EquationRgb) + if (New.EquationRgb != old.EquationRgb) { - GL.BlendEquation(Index, OGLEnumConverter.GetBlendEquation(New.EquationRgb)); + GL.BlendEquation(index, OglEnumConverter.GetBlendEquation(New.EquationRgb)); } - if (New.FuncSrcRgb != Old.FuncSrcRgb || - New.FuncDstRgb != Old.FuncDstRgb) + if (New.FuncSrcRgb != old.FuncSrcRgb || + New.FuncDstRgb != old.FuncDstRgb) { GL.BlendFunc( - Index, - (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.FuncSrcRgb), - (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.FuncDstRgb)); + index, + (BlendingFactorSrc) OglEnumConverter.GetBlendFactor(New.FuncSrcRgb), + (BlendingFactorDest)OglEnumConverter.GetBlendFactor(New.FuncDstRgb)); } } } @@ -523,310 +523,310 @@ namespace Ryujinx.Graphics.Gal.OpenGL private void BindConstBuffers(GalPipelineState New) { - int FreeBinding = OGLShader.ReservedCbufCount; + int freeBinding = OglShader.ReservedCbufCount; - void BindIfNotNull(OGLShaderStage Stage) + void BindIfNotNull(OglShaderStage stage) { - if (Stage != null) + if (stage != null) { - foreach (ShaderDeclInfo DeclInfo in Stage.ConstBufferUsage) + foreach (ShaderDeclInfo declInfo in stage.ConstBufferUsage) { - long Key = New.ConstBufferKeys[(int)Stage.Type][DeclInfo.Cbuf]; + long key = New.ConstBufferKeys[(int)stage.Type][declInfo.Cbuf]; - if (Key != 0 && Buffer.TryGetUbo(Key, out int UboHandle)) + if (key != 0 && _buffer.TryGetUbo(key, out int uboHandle)) { - GL.BindBufferBase(BufferRangeTarget.UniformBuffer, FreeBinding, UboHandle); + GL.BindBufferBase(BufferRangeTarget.UniformBuffer, freeBinding, uboHandle); } - FreeBinding++; + freeBinding++; } } } - BindIfNotNull(Shader.Current.Vertex); - BindIfNotNull(Shader.Current.TessControl); - BindIfNotNull(Shader.Current.TessEvaluation); - BindIfNotNull(Shader.Current.Geometry); - BindIfNotNull(Shader.Current.Fragment); + BindIfNotNull(_shader.Current.Vertex); + BindIfNotNull(_shader.Current.TessControl); + BindIfNotNull(_shader.Current.TessEvaluation); + BindIfNotNull(_shader.Current.Geometry); + BindIfNotNull(_shader.Current.Fragment); } private void BindVertexLayout(GalPipelineState New) { - foreach (GalVertexBinding Binding in New.VertexBindings) + foreach (GalVertexBinding binding in New.VertexBindings) { - if (!Binding.Enabled || !Rasterizer.TryGetVbo(Binding.VboKey, out int VboHandle)) + if (!binding.Enabled || !_rasterizer.TryGetVbo(binding.VboKey, out int vboHandle)) { continue; } - if (VaoHandle == 0) + if (_vaoHandle == 0) { - VaoHandle = GL.GenVertexArray(); + _vaoHandle = GL.GenVertexArray(); //Vertex arrays shouldn't be used anywhere else in OpenGL's backend //if you want to use it, move this line out of the if - GL.BindVertexArray(VaoHandle); + GL.BindVertexArray(_vaoHandle); } - foreach (GalVertexAttrib Attrib in Binding.Attribs) + foreach (GalVertexAttrib attrib in binding.Attribs) { //Skip uninitialized attributes. - if (Attrib.Size == 0) + if (attrib.Size == 0) { continue; } - GL.BindBuffer(BufferTarget.ArrayBuffer, VboHandle); + GL.BindBuffer(BufferTarget.ArrayBuffer, vboHandle); - bool Unsigned = - Attrib.Type == GalVertexAttribType.Unorm || - Attrib.Type == GalVertexAttribType.Uint || - Attrib.Type == GalVertexAttribType.Uscaled; + bool unsigned = + attrib.Type == GalVertexAttribType.Unorm || + attrib.Type == GalVertexAttribType.Uint || + attrib.Type == GalVertexAttribType.Uscaled; - bool Normalize = - Attrib.Type == GalVertexAttribType.Snorm || - Attrib.Type == GalVertexAttribType.Unorm; + bool normalize = + attrib.Type == GalVertexAttribType.Snorm || + attrib.Type == GalVertexAttribType.Unorm; - VertexAttribPointerType Type = 0; + VertexAttribPointerType type = 0; - if (Attrib.Type == GalVertexAttribType.Float) + if (attrib.Type == GalVertexAttribType.Float) { - Type = GetType(FloatAttribTypes, Attrib); + type = GetType(_floatAttribTypes, attrib); } else { - if (Unsigned) + if (unsigned) { - Type = GetType(UnsignedAttribTypes, Attrib); + type = GetType(_unsignedAttribTypes, attrib); } else { - Type = GetType(SignedAttribTypes, Attrib); + type = GetType(_signedAttribTypes, attrib); } } - if (!AttribElements.TryGetValue(Attrib.Size, out int Size)) + if (!_attribElements.TryGetValue(attrib.Size, out int size)) { - throw new InvalidOperationException("Invalid attribute size \"" + Attrib.Size + "\"!"); + throw new InvalidOperationException("Invalid attribute size \"" + attrib.Size + "\"!"); } - int Offset = Attrib.Offset; + int offset = attrib.Offset; - if (Binding.Stride != 0) + if (binding.Stride != 0) { - GL.EnableVertexAttribArray(Attrib.Index); + GL.EnableVertexAttribArray(attrib.Index); - if (Attrib.Type == GalVertexAttribType.Sint || - Attrib.Type == GalVertexAttribType.Uint) + if (attrib.Type == GalVertexAttribType.Sint || + attrib.Type == GalVertexAttribType.Uint) { - IntPtr Pointer = new IntPtr(Offset); + IntPtr pointer = new IntPtr(offset); - VertexAttribIntegerType IType = (VertexAttribIntegerType)Type; + VertexAttribIntegerType iType = (VertexAttribIntegerType)type; - GL.VertexAttribIPointer(Attrib.Index, Size, IType, Binding.Stride, Pointer); + GL.VertexAttribIPointer(attrib.Index, size, iType, binding.Stride, pointer); } else { - GL.VertexAttribPointer(Attrib.Index, Size, Type, Normalize, Binding.Stride, Offset); + GL.VertexAttribPointer(attrib.Index, size, type, normalize, binding.Stride, offset); } } else { - GL.DisableVertexAttribArray(Attrib.Index); + GL.DisableVertexAttribArray(attrib.Index); - SetConstAttrib(Attrib); + SetConstAttrib(attrib); } - if (Binding.Instanced && Binding.Divisor != 0) + if (binding.Instanced && binding.Divisor != 0) { - GL.VertexAttribDivisor(Attrib.Index, 1); + GL.VertexAttribDivisor(attrib.Index, 1); } else { - GL.VertexAttribDivisor(Attrib.Index, 0); + GL.VertexAttribDivisor(attrib.Index, 0); } } } } - private static VertexAttribPointerType GetType(Dictionary Dict, GalVertexAttrib Attrib) + private static VertexAttribPointerType GetType(Dictionary dict, GalVertexAttrib attrib) { - if (!Dict.TryGetValue(Attrib.Size, out VertexAttribPointerType Type)) + if (!dict.TryGetValue(attrib.Size, out VertexAttribPointerType type)) { - ThrowUnsupportedAttrib(Attrib); + ThrowUnsupportedAttrib(attrib); } - return Type; + return type; } - private unsafe static void SetConstAttrib(GalVertexAttrib Attrib) + private static unsafe void SetConstAttrib(GalVertexAttrib attrib) { - if (Attrib.Size == GalVertexAttribSize._10_10_10_2 || - Attrib.Size == GalVertexAttribSize._11_11_10) + if (attrib.Size == GalVertexAttribSize._10_10_10_2 || + attrib.Size == GalVertexAttribSize._11_11_10) { - ThrowUnsupportedAttrib(Attrib); + ThrowUnsupportedAttrib(attrib); } - fixed (byte* Ptr = Attrib.Data) + fixed (byte* ptr = attrib.Data) { - if (Attrib.Type == GalVertexAttribType.Unorm) + if (attrib.Type == GalVertexAttribType.Unorm) { - switch (Attrib.Size) + switch (attrib.Size) { case GalVertexAttribSize._8: case GalVertexAttribSize._8_8: case GalVertexAttribSize._8_8_8: case GalVertexAttribSize._8_8_8_8: - GL.VertexAttrib4N((uint)Attrib.Index, Ptr); + GL.VertexAttrib4N((uint)attrib.Index, ptr); break; case GalVertexAttribSize._16: case GalVertexAttribSize._16_16: case GalVertexAttribSize._16_16_16: case GalVertexAttribSize._16_16_16_16: - GL.VertexAttrib4N((uint)Attrib.Index, (ushort*)Ptr); + GL.VertexAttrib4N((uint)attrib.Index, (ushort*)ptr); break; case GalVertexAttribSize._32: case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32_32: - GL.VertexAttrib4N((uint)Attrib.Index, (uint*)Ptr); + GL.VertexAttrib4N((uint)attrib.Index, (uint*)ptr); break; } } - else if (Attrib.Type == GalVertexAttribType.Snorm) + else if (attrib.Type == GalVertexAttribType.Snorm) { - switch (Attrib.Size) + switch (attrib.Size) { case GalVertexAttribSize._8: case GalVertexAttribSize._8_8: case GalVertexAttribSize._8_8_8: case GalVertexAttribSize._8_8_8_8: - GL.VertexAttrib4N((uint)Attrib.Index, (sbyte*)Ptr); + GL.VertexAttrib4N((uint)attrib.Index, (sbyte*)ptr); break; case GalVertexAttribSize._16: case GalVertexAttribSize._16_16: case GalVertexAttribSize._16_16_16: case GalVertexAttribSize._16_16_16_16: - GL.VertexAttrib4N((uint)Attrib.Index, (short*)Ptr); + GL.VertexAttrib4N((uint)attrib.Index, (short*)ptr); break; case GalVertexAttribSize._32: case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32_32: - GL.VertexAttrib4N((uint)Attrib.Index, (int*)Ptr); + GL.VertexAttrib4N((uint)attrib.Index, (int*)ptr); break; } } - else if (Attrib.Type == GalVertexAttribType.Uint) + else if (attrib.Type == GalVertexAttribType.Uint) { - switch (Attrib.Size) + switch (attrib.Size) { case GalVertexAttribSize._8: case GalVertexAttribSize._8_8: case GalVertexAttribSize._8_8_8: case GalVertexAttribSize._8_8_8_8: - GL.VertexAttribI4((uint)Attrib.Index, Ptr); + GL.VertexAttribI4((uint)attrib.Index, ptr); break; case GalVertexAttribSize._16: case GalVertexAttribSize._16_16: case GalVertexAttribSize._16_16_16: case GalVertexAttribSize._16_16_16_16: - GL.VertexAttribI4((uint)Attrib.Index, (ushort*)Ptr); + GL.VertexAttribI4((uint)attrib.Index, (ushort*)ptr); break; case GalVertexAttribSize._32: case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32_32: - GL.VertexAttribI4((uint)Attrib.Index, (uint*)Ptr); + GL.VertexAttribI4((uint)attrib.Index, (uint*)ptr); break; } } - else if (Attrib.Type == GalVertexAttribType.Sint) + else if (attrib.Type == GalVertexAttribType.Sint) { - switch (Attrib.Size) + switch (attrib.Size) { case GalVertexAttribSize._8: case GalVertexAttribSize._8_8: case GalVertexAttribSize._8_8_8: case GalVertexAttribSize._8_8_8_8: - GL.VertexAttribI4((uint)Attrib.Index, (sbyte*)Ptr); + GL.VertexAttribI4((uint)attrib.Index, (sbyte*)ptr); break; case GalVertexAttribSize._16: case GalVertexAttribSize._16_16: case GalVertexAttribSize._16_16_16: case GalVertexAttribSize._16_16_16_16: - GL.VertexAttribI4((uint)Attrib.Index, (short*)Ptr); + GL.VertexAttribI4((uint)attrib.Index, (short*)ptr); break; case GalVertexAttribSize._32: case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32_32: - GL.VertexAttribI4((uint)Attrib.Index, (int*)Ptr); + GL.VertexAttribI4((uint)attrib.Index, (int*)ptr); break; } } - else if (Attrib.Type == GalVertexAttribType.Float) + else if (attrib.Type == GalVertexAttribType.Float) { - switch (Attrib.Size) + switch (attrib.Size) { case GalVertexAttribSize._32: case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32_32: - GL.VertexAttrib4(Attrib.Index, (float*)Ptr); + GL.VertexAttrib4(attrib.Index, (float*)ptr); break; - default: ThrowUnsupportedAttrib(Attrib); break; + default: ThrowUnsupportedAttrib(attrib); break; } } } } - private static void ThrowUnsupportedAttrib(GalVertexAttrib Attrib) + private static void ThrowUnsupportedAttrib(GalVertexAttrib attrib) { - throw new NotImplementedException("Unsupported size \"" + Attrib.Size + "\" on type \"" + Attrib.Type + "\"!"); + throw new NotImplementedException("Unsupported size \"" + attrib.Size + "\" on type \"" + attrib.Type + "\"!"); } - private void Enable(EnableCap Cap, bool Enabled) + private void Enable(EnableCap cap, bool enabled) { - if (Enabled) + if (enabled) { - GL.Enable(Cap); + GL.Enable(cap); } else { - GL.Disable(Cap); + GL.Disable(cap); } } - private void Enable(IndexedEnableCap Cap, int Index, bool Enabled) + private void Enable(IndexedEnableCap cap, int index, bool enabled) { - if (Enabled) + if (enabled) { - GL.Enable(Cap, Index); + GL.Enable(cap, index); } else { - GL.Disable(Cap, Index); + GL.Disable(cap, index); } } public void ResetDepthMask() { - Old.DepthWriteEnabled = true; + _old.DepthWriteEnabled = true; } - public void ResetColorMask(int Index) + public void ResetColorMask(int index) { - Old.ColorMasks[Index] = ColorMaskState.Default; + _old.ColorMasks[index] = ColorMaskState.Default; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglRasterizer.cs b/Ryujinx.Graphics/Gal/OpenGL/OglRasterizer.cs new file mode 100644 index 00000000..c19911c5 --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglRasterizer.cs @@ -0,0 +1,207 @@ +using OpenTK.Graphics.OpenGL; +using System; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + class OglRasterizer : IGalRasterizer + { + private const long MaxVertexBufferCacheSize = 128 * 1024 * 1024; + private const long MaxIndexBufferCacheSize = 64 * 1024 * 1024; + + private int[] _vertexBuffers; + + private OglCachedResource _vboCache; + private OglCachedResource _iboCache; + + private struct IbInfo + { + public int Count; + public int ElemSizeLog2; + + public DrawElementsType Type; + } + + private IbInfo _indexBuffer; + + public OglRasterizer() + { + _vertexBuffers = new int[32]; + + _vboCache = new OglCachedResource(GL.DeleteBuffer, MaxVertexBufferCacheSize); + _iboCache = new OglCachedResource(GL.DeleteBuffer, MaxIndexBufferCacheSize); + + _indexBuffer = new IbInfo(); + } + + public void LockCaches() + { + _vboCache.Lock(); + _iboCache.Lock(); + } + + public void UnlockCaches() + { + _vboCache.Unlock(); + _iboCache.Unlock(); + } + + public void ClearBuffers( + GalClearBufferFlags flags, + int attachment, + float red, + float green, + float blue, + float alpha, + float depth, + int stencil) + { + GL.ColorMask( + attachment, + flags.HasFlag(GalClearBufferFlags.ColorRed), + flags.HasFlag(GalClearBufferFlags.ColorGreen), + flags.HasFlag(GalClearBufferFlags.ColorBlue), + flags.HasFlag(GalClearBufferFlags.ColorAlpha)); + + GL.ClearBuffer(ClearBuffer.Color, attachment, new float[] { red, green, blue, alpha }); + + GL.ColorMask(attachment, true, true, true, true); + GL.DepthMask(true); + + if (flags.HasFlag(GalClearBufferFlags.Depth)) + { + GL.ClearBuffer(ClearBuffer.Depth, 0, ref depth); + } + + if (flags.HasFlag(GalClearBufferFlags.Stencil)) + { + GL.ClearBuffer(ClearBuffer.Stencil, 0, ref stencil); + } + } + + public bool IsVboCached(long key, long dataSize) + { + return _vboCache.TryGetSize(key, out long size) && size == dataSize; + } + + public bool IsIboCached(long key, long dataSize) + { + return _iboCache.TryGetSize(key, out long size) && size == dataSize; + } + + public void CreateVbo(long key, int dataSize, IntPtr hostAddress) + { + int handle = GL.GenBuffer(); + + _vboCache.AddOrUpdate(key, handle, dataSize); + + IntPtr length = new IntPtr(dataSize); + + GL.BindBuffer(BufferTarget.ArrayBuffer, handle); + GL.BufferData(BufferTarget.ArrayBuffer, length, hostAddress, BufferUsageHint.StreamDraw); + } + + public void CreateVbo(long key, byte[] data) + { + int handle = GL.GenBuffer(); + + _vboCache.AddOrUpdate(key, handle, data.Length); + + IntPtr length = new IntPtr(data.Length); + + GL.BindBuffer(BufferTarget.ArrayBuffer, handle); + GL.BufferData(BufferTarget.ArrayBuffer, length, data, BufferUsageHint.StreamDraw); + } + + public void CreateIbo(long key, int dataSize, IntPtr hostAddress) + { + int handle = GL.GenBuffer(); + + _iboCache.AddOrUpdate(key, handle, (uint)dataSize); + + IntPtr length = new IntPtr(dataSize); + + GL.BindBuffer(BufferTarget.ElementArrayBuffer, handle); + GL.BufferData(BufferTarget.ElementArrayBuffer, length, hostAddress, BufferUsageHint.StreamDraw); + } + + public void CreateIbo(long key, int dataSize, byte[] buffer) + { + int handle = GL.GenBuffer(); + + _iboCache.AddOrUpdate(key, handle, dataSize); + + IntPtr length = new IntPtr(buffer.Length); + + GL.BindBuffer(BufferTarget.ElementArrayBuffer, handle); + GL.BufferData(BufferTarget.ElementArrayBuffer, length, buffer, BufferUsageHint.StreamDraw); + } + + public void SetIndexArray(int size, GalIndexFormat format) + { + _indexBuffer.Type = OglEnumConverter.GetDrawElementsType(format); + + _indexBuffer.Count = size >> (int)format; + + _indexBuffer.ElemSizeLog2 = (int)format; + } + + public void DrawArrays(int first, int count, GalPrimitiveType primType) + { + if (count == 0) + { + return; + } + + if (primType == GalPrimitiveType.Quads) + { + for (int offset = 0; offset < count; offset += 4) + { + GL.DrawArrays(PrimitiveType.TriangleFan, first + offset, 4); + } + } + else if (primType == GalPrimitiveType.QuadStrip) + { + GL.DrawArrays(PrimitiveType.TriangleFan, first, 4); + + for (int offset = 2; offset < count; offset += 2) + { + GL.DrawArrays(PrimitiveType.TriangleFan, first + offset, 4); + } + } + else + { + GL.DrawArrays(OglEnumConverter.GetPrimitiveType(primType), first, count); + } + } + + public void DrawElements(long iboKey, int first, int vertexBase, GalPrimitiveType primType) + { + if (!_iboCache.TryGetValue(iboKey, out int iboHandle)) + { + return; + } + + PrimitiveType mode = OglEnumConverter.GetPrimitiveType(primType); + + GL.BindBuffer(BufferTarget.ElementArrayBuffer, iboHandle); + + first <<= _indexBuffer.ElemSizeLog2; + + if (vertexBase != 0) + { + IntPtr indices = new IntPtr(first); + + GL.DrawElementsBaseVertex(mode, _indexBuffer.Count, _indexBuffer.Type, indices, vertexBase); + } + else + { + GL.DrawElements(mode, _indexBuffer.Count, _indexBuffer.Type, first); + } + } + + public bool TryGetVbo(long vboKey, out int vboHandle) + { + return _vboCache.TryGetValue(vboKey, out vboHandle); + } + } +} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglRenderTarget.cs b/Ryujinx.Graphics/Gal/OpenGL/OglRenderTarget.cs new file mode 100644 index 00000000..d36bac1b --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglRenderTarget.cs @@ -0,0 +1,549 @@ +using OpenTK.Graphics.OpenGL; +using Ryujinx.Graphics.Texture; +using System; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + class OglRenderTarget : IGalRenderTarget + { + private const int NativeWidth = 1280; + private const int NativeHeight = 720; + + private const int RenderTargetsCount = GalPipelineState.RenderTargetsCount; + + private struct Rect + { + public int X { get; private set; } + public int Y { get; private set; } + public int Width { get; private set; } + public int Height { get; private set; } + + public Rect(int x, int y, int width, int height) + { + X = x; + Y = y; + Width = width; + Height = height; + } + } + + private class FrameBufferAttachments + { + public int MapCount { get; set; } + + public DrawBuffersEnum[] Map { get; private set; } + + public long[] Colors { get; private set; } + + public long Zeta { get; set; } + + public FrameBufferAttachments() + { + Colors = new long[RenderTargetsCount]; + + Map = new DrawBuffersEnum[RenderTargetsCount]; + } + + public void Update(FrameBufferAttachments source) + { + for (int index = 0; index < RenderTargetsCount; index++) + { + Map[index] = source.Map[index]; + + Colors[index] = source.Colors[index]; + } + + MapCount = source.MapCount; + Zeta = source.Zeta; + } + } + + private int[] _colorHandles; + private int _zetaHandle; + + private OglTexture _texture; + + private ImageHandler _readTex; + + private Rect _window; + + private float[] _viewports; + + private bool _flipX; + private bool _flipY; + + private int _cropTop; + private int _cropLeft; + private int _cropRight; + private int _cropBottom; + + //This framebuffer is used to attach guest rendertargets, + //think of it as a dummy OpenGL VAO + private int _dummyFrameBuffer; + + //These framebuffers are used to blit images + private int _srcFb; + private int _dstFb; + + private FrameBufferAttachments _attachments; + private FrameBufferAttachments _oldAttachments; + + private int _copyPbo; + + public bool FramebufferSrgb { get; set; } + + public OglRenderTarget(OglTexture texture) + { + _attachments = new FrameBufferAttachments(); + + _oldAttachments = new FrameBufferAttachments(); + + _colorHandles = new int[RenderTargetsCount]; + + _viewports = new float[RenderTargetsCount * 4]; + + _texture = texture; + + texture.TextureDeleted += TextureDeletionHandler; + } + + private void TextureDeletionHandler(object sender, int handle) + { + //Texture was deleted, the handle is no longer valid, so + //reset all uses of this handle on a render target. + for (int attachment = 0; attachment < RenderTargetsCount; attachment++) + { + if (_colorHandles[attachment] == handle) + { + _colorHandles[attachment] = 0; + } + } + + if (_zetaHandle == handle) + { + _zetaHandle = 0; + } + } + + public void Bind() + { + if (_dummyFrameBuffer == 0) + { + _dummyFrameBuffer = GL.GenFramebuffer(); + } + + GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, _dummyFrameBuffer); + + ImageHandler cachedImage; + + for (int attachment = 0; attachment < RenderTargetsCount; attachment++) + { + long key = _attachments.Colors[attachment]; + + int handle = 0; + + if (key != 0 && _texture.TryGetImageHandler(key, out cachedImage)) + { + handle = cachedImage.Handle; + } + + if (handle == _colorHandles[attachment]) + { + continue; + } + + GL.FramebufferTexture( + FramebufferTarget.DrawFramebuffer, + FramebufferAttachment.ColorAttachment0 + attachment, + handle, + 0); + + _colorHandles[attachment] = handle; + } + + if (_attachments.Zeta != 0 && _texture.TryGetImageHandler(_attachments.Zeta, out cachedImage)) + { + if (cachedImage.Handle != _zetaHandle) + { + if (cachedImage.HasDepth && cachedImage.HasStencil) + { + GL.FramebufferTexture( + FramebufferTarget.DrawFramebuffer, + FramebufferAttachment.DepthStencilAttachment, + cachedImage.Handle, + 0); + } + else if (cachedImage.HasDepth) + { + GL.FramebufferTexture( + FramebufferTarget.DrawFramebuffer, + FramebufferAttachment.DepthAttachment, + cachedImage.Handle, + 0); + + GL.FramebufferTexture( + FramebufferTarget.DrawFramebuffer, + FramebufferAttachment.StencilAttachment, + 0, + 0); + } + else + { + throw new InvalidOperationException("Invalid image format \"" + cachedImage.Format + "\" used as Zeta!"); + } + + _zetaHandle = cachedImage.Handle; + } + } + else if (_zetaHandle != 0) + { + GL.FramebufferTexture( + FramebufferTarget.DrawFramebuffer, + FramebufferAttachment.DepthStencilAttachment, + 0, + 0); + + _zetaHandle = 0; + } + + if (OglExtension.ViewportArray) + { + GL.ViewportArray(0, RenderTargetsCount, _viewports); + } + else + { + GL.Viewport( + (int)_viewports[0], + (int)_viewports[1], + (int)_viewports[2], + (int)_viewports[3]); + } + + if (_attachments.MapCount > 1) + { + GL.DrawBuffers(_attachments.MapCount, _attachments.Map); + } + else if (_attachments.MapCount == 1) + { + GL.DrawBuffer((DrawBufferMode)_attachments.Map[0]); + } + else + { + GL.DrawBuffer(DrawBufferMode.None); + } + + _oldAttachments.Update(_attachments); + } + + public void BindColor(long key, int attachment) + { + _attachments.Colors[attachment] = key; + } + + public void UnbindColor(int attachment) + { + _attachments.Colors[attachment] = 0; + } + + public void BindZeta(long key) + { + _attachments.Zeta = key; + } + + public void UnbindZeta() + { + _attachments.Zeta = 0; + } + + public void Present(long key) + { + _texture.TryGetImageHandler(key, out _readTex); + } + + public void SetMap(int[] map) + { + if (map != null) + { + _attachments.MapCount = map.Length; + + for (int attachment = 0; attachment < _attachments.MapCount; attachment++) + { + _attachments.Map[attachment] = DrawBuffersEnum.ColorAttachment0 + map[attachment]; + } + } + else + { + _attachments.MapCount = 0; + } + } + + public void SetTransform(bool flipX, bool flipY, int top, int left, int right, int bottom) + { + _flipX = flipX; + _flipY = flipY; + + _cropTop = top; + _cropLeft = left; + _cropRight = right; + _cropBottom = bottom; + } + + public void SetWindowSize(int width, int height) + { + _window = new Rect(0, 0, width, height); + } + + public void SetViewport(int attachment, int x, int y, int width, int height) + { + int offset = attachment * 4; + + _viewports[offset + 0] = x; + _viewports[offset + 1] = y; + _viewports[offset + 2] = width; + _viewports[offset + 3] = height; + } + + public void Render() + { + if (_readTex == null) + { + return; + } + + int srcX0, srcX1, srcY0, srcY1; + + if (_cropLeft == 0 && _cropRight == 0) + { + srcX0 = 0; + srcX1 = _readTex.Width; + } + else + { + srcX0 = _cropLeft; + srcX1 = _cropRight; + } + + if (_cropTop == 0 && _cropBottom == 0) + { + srcY0 = 0; + srcY1 = _readTex.Height; + } + else + { + srcY0 = _cropTop; + srcY1 = _cropBottom; + } + + float ratioX = MathF.Min(1f, (_window.Height * (float)NativeWidth) / ((float)NativeHeight * _window.Width)); + float ratioY = MathF.Min(1f, (_window.Width * (float)NativeHeight) / ((float)NativeWidth * _window.Height)); + + int dstWidth = (int)(_window.Width * ratioX); + int dstHeight = (int)(_window.Height * ratioY); + + int dstPaddingX = (_window.Width - dstWidth) / 2; + int dstPaddingY = (_window.Height - dstHeight) / 2; + + int dstX0 = _flipX ? _window.Width - dstPaddingX : dstPaddingX; + int dstX1 = _flipX ? dstPaddingX : _window.Width - dstPaddingX; + + int dstY0 = _flipY ? dstPaddingY : _window.Height - dstPaddingY; + int dstY1 = _flipY ? _window.Height - dstPaddingY : dstPaddingY; + + GL.Viewport(0, 0, _window.Width, _window.Height); + + if (_srcFb == 0) + { + _srcFb = GL.GenFramebuffer(); + } + + GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, _srcFb); + GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, 0); + + GL.FramebufferTexture(FramebufferTarget.ReadFramebuffer, FramebufferAttachment.ColorAttachment0, _readTex.Handle, 0); + + GL.ReadBuffer(ReadBufferMode.ColorAttachment0); + + GL.Clear(ClearBufferMask.ColorBufferBit); + + GL.Disable(EnableCap.FramebufferSrgb); + + GL.BlitFramebuffer( + srcX0, + srcY0, + srcX1, + srcY1, + dstX0, + dstY0, + dstX1, + dstY1, + ClearBufferMask.ColorBufferBit, + BlitFramebufferFilter.Linear); + + if (FramebufferSrgb) + { + GL.Enable(EnableCap.FramebufferSrgb); + } + } + + public void Copy( + GalImage srcImage, + GalImage dstImage, + long srcKey, + long dstKey, + int srcLayer, + int dstLayer, + int srcX0, + int srcY0, + int srcX1, + int srcY1, + int dstX0, + int dstY0, + int dstX1, + int dstY1) + { + if (_texture.TryGetImageHandler(srcKey, out ImageHandler srcTex) && + _texture.TryGetImageHandler(dstKey, out ImageHandler dstTex)) + { + if (srcTex.HasColor != dstTex.HasColor || + srcTex.HasDepth != dstTex.HasDepth || + srcTex.HasStencil != dstTex.HasStencil) + { + throw new NotImplementedException(); + } + + if (_srcFb == 0) + { + _srcFb = GL.GenFramebuffer(); + } + + if (_dstFb == 0) + { + _dstFb = GL.GenFramebuffer(); + } + + GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, _srcFb); + GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, _dstFb); + + FramebufferAttachment attachment = GetAttachment(srcTex); + + if (ImageUtils.IsArray(srcImage.TextureTarget) && srcLayer > 0) + { + GL.FramebufferTextureLayer(FramebufferTarget.ReadFramebuffer, attachment, srcTex.Handle, 0, srcLayer); + } + else + { + GL.FramebufferTexture(FramebufferTarget.ReadFramebuffer, attachment, srcTex.Handle, 0); + } + + if (ImageUtils.IsArray(dstImage.TextureTarget) && dstLayer > 0) + { + GL.FramebufferTextureLayer(FramebufferTarget.DrawFramebuffer, attachment, dstTex.Handle, 0, dstLayer); + } + else + { + GL.FramebufferTexture(FramebufferTarget.DrawFramebuffer, attachment, dstTex.Handle, 0); + } + + + BlitFramebufferFilter filter = BlitFramebufferFilter.Nearest; + + if (srcTex.HasColor) + { + GL.DrawBuffer(DrawBufferMode.ColorAttachment0); + + filter = BlitFramebufferFilter.Linear; + } + + ClearBufferMask mask = GetClearMask(srcTex); + + GL.BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + } + } + + public void Reinterpret(long key, GalImage newImage) + { + if (!_texture.TryGetImage(key, out GalImage oldImage)) + { + return; + } + + if (newImage.Format == oldImage.Format && + newImage.Width == oldImage.Width && + newImage.Height == oldImage.Height && + newImage.Depth == oldImage.Depth && + newImage.LayerCount == oldImage.LayerCount && + newImage.TextureTarget == oldImage.TextureTarget) + { + return; + } + + if (_copyPbo == 0) + { + _copyPbo = GL.GenBuffer(); + } + + GL.BindBuffer(BufferTarget.PixelPackBuffer, _copyPbo); + + //The buffer should be large enough to hold the largest texture. + int bufferSize = Math.Max(ImageUtils.GetSize(oldImage), + ImageUtils.GetSize(newImage)); + + GL.BufferData(BufferTarget.PixelPackBuffer, bufferSize, IntPtr.Zero, BufferUsageHint.StreamCopy); + + if (!_texture.TryGetImageHandler(key, out ImageHandler cachedImage)) + { + throw new InvalidOperationException(); + } + + (_, PixelFormat format, PixelType type) = OglEnumConverter.GetImageFormat(cachedImage.Format); + + TextureTarget target = ImageUtils.GetTextureTarget(newImage.TextureTarget); + + GL.BindTexture(target, cachedImage.Handle); + + GL.GetTexImage(target, 0, format, type, IntPtr.Zero); + + GL.BindBuffer(BufferTarget.PixelPackBuffer, 0); + GL.BindBuffer(BufferTarget.PixelUnpackBuffer, _copyPbo); + + GL.PixelStore(PixelStoreParameter.UnpackRowLength, oldImage.Width); + + _texture.Create(key, ImageUtils.GetSize(newImage), newImage); + + GL.PixelStore(PixelStoreParameter.UnpackRowLength, 0); + + GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); + } + + private static FramebufferAttachment GetAttachment(ImageHandler cachedImage) + { + if (cachedImage.HasColor) + { + return FramebufferAttachment.ColorAttachment0; + } + else if (cachedImage.HasDepth && cachedImage.HasStencil) + { + return FramebufferAttachment.DepthStencilAttachment; + } + else if (cachedImage.HasDepth) + { + return FramebufferAttachment.DepthAttachment; + } + else if (cachedImage.HasStencil) + { + return FramebufferAttachment.StencilAttachment; + } + else + { + throw new InvalidOperationException(); + } + } + + private static ClearBufferMask GetClearMask(ImageHandler cachedImage) + { + return (cachedImage.HasColor ? ClearBufferMask.ColorBufferBit : 0) | + (cachedImage.HasDepth ? ClearBufferMask.DepthBufferBit : 0) | + (cachedImage.HasStencil ? ClearBufferMask.StencilBufferBit : 0); + } + } +} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglRenderer.cs b/Ryujinx.Graphics/Gal/OpenGL/OglRenderer.cs new file mode 100644 index 00000000..1ff8c7ad --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglRenderer.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Concurrent; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + public class OglRenderer : IGalRenderer + { + public IGalConstBuffer Buffer { get; private set; } + + public IGalRenderTarget RenderTarget { get; private set; } + + public IGalRasterizer Rasterizer { get; private set; } + + public IGalShader Shader { get; private set; } + + public IGalPipeline Pipeline { get; private set; } + + public IGalTexture Texture { get; private set; } + + private ConcurrentQueue _actionsQueue; + + public OglRenderer() + { + Buffer = new OglConstBuffer(); + + Texture = new OglTexture(); + + RenderTarget = new OglRenderTarget(Texture as OglTexture); + + Rasterizer = new OglRasterizer(); + + Shader = new OglShader(Buffer as OglConstBuffer); + + Pipeline = new OglPipeline( + Buffer as OglConstBuffer, + RenderTarget as OglRenderTarget, + Rasterizer as OglRasterizer, + Shader as OglShader); + + _actionsQueue = new ConcurrentQueue(); + } + + public void QueueAction(Action actionMthd) + { + _actionsQueue.Enqueue(actionMthd); + } + + public void RunActions() + { + int count = _actionsQueue.Count; + + while (count-- > 0 && _actionsQueue.TryDequeue(out Action renderAction)) + { + renderAction(); + } + } + } +} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglShader.cs b/Ryujinx.Graphics/Gal/OpenGL/OglShader.cs new file mode 100644 index 00000000..8faa9053 --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglShader.cs @@ -0,0 +1,298 @@ +using OpenTK.Graphics.OpenGL; +using Ryujinx.Graphics.Gal.Shader; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + class OglShader : IGalShader + { + public const int ReservedCbufCount = 1; + + private const int ExtraDataSize = 4; + + public OglShaderProgram Current; + + private ConcurrentDictionary _stages; + + private Dictionary _programs; + + public int CurrentProgramHandle { get; private set; } + + private OglConstBuffer _buffer; + + private int _extraUboHandle; + + public OglShader(OglConstBuffer buffer) + { + _buffer = buffer; + + _stages = new ConcurrentDictionary(); + + _programs = new Dictionary(); + } + + public void Create(IGalMemory memory, long key, GalShaderType type) + { + _stages.GetOrAdd(key, (stage) => ShaderStageFactory(memory, key, 0, false, type)); + } + + public void Create(IGalMemory memory, long vpAPos, long key, GalShaderType type) + { + _stages.GetOrAdd(key, (stage) => ShaderStageFactory(memory, vpAPos, key, true, type)); + } + + private OglShaderStage ShaderStageFactory( + IGalMemory memory, + long position, + long positionB, + bool isDualVp, + GalShaderType type) + { + GlslProgram program; + + GlslDecompiler decompiler = new GlslDecompiler(OglLimit.MaxUboSize, OglExtension.NvidiaDriver); + + int shaderDumpIndex = ShaderDumper.DumpIndex; + + if (isDualVp) + { + ShaderDumper.Dump(memory, position, type, "a"); + ShaderDumper.Dump(memory, positionB, type, "b"); + + program = decompiler.Decompile(memory, position, positionB, type); + } + else + { + ShaderDumper.Dump(memory, position, type); + + program = decompiler.Decompile(memory, position, type); + } + + string code = program.Code; + + if (ShaderDumper.IsDumpEnabled()) + { + code = "//Shader " + shaderDumpIndex + Environment.NewLine + code; + } + + return new OglShaderStage(type, code, program.Uniforms, program.Textures); + } + + public IEnumerable GetConstBufferUsage(long key) + { + if (_stages.TryGetValue(key, out OglShaderStage stage)) + { + return stage.ConstBufferUsage; + } + + return Enumerable.Empty(); + } + + public IEnumerable GetTextureUsage(long key) + { + if (_stages.TryGetValue(key, out OglShaderStage stage)) + { + return stage.TextureUsage; + } + + return Enumerable.Empty(); + } + + public unsafe void SetExtraData(float flipX, float flipY, int instance) + { + BindProgram(); + + EnsureExtraBlock(); + + GL.BindBuffer(BufferTarget.UniformBuffer, _extraUboHandle); + + float* data = stackalloc float[ExtraDataSize]; + data[0] = flipX; + data[1] = flipY; + data[2] = BitConverter.Int32BitsToSingle(instance); + + //Invalidate buffer + GL.BufferData(BufferTarget.UniformBuffer, ExtraDataSize * sizeof(float), IntPtr.Zero, BufferUsageHint.StreamDraw); + + GL.BufferSubData(BufferTarget.UniformBuffer, IntPtr.Zero, ExtraDataSize * sizeof(float), (IntPtr)data); + } + + public void Bind(long key) + { + if (_stages.TryGetValue(key, out OglShaderStage stage)) + { + Bind(stage); + } + } + + private void Bind(OglShaderStage stage) + { + if (stage.Type == GalShaderType.Geometry) + { + //Enhanced layouts are required for Geometry shaders + //skip this stage if current driver has no ARB_enhanced_layouts + if (!OglExtension.EnhancedLayouts) + { + return; + } + } + + switch (stage.Type) + { + case GalShaderType.Vertex: Current.Vertex = stage; break; + case GalShaderType.TessControl: Current.TessControl = stage; break; + case GalShaderType.TessEvaluation: Current.TessEvaluation = stage; break; + case GalShaderType.Geometry: Current.Geometry = stage; break; + case GalShaderType.Fragment: Current.Fragment = stage; break; + } + } + + public void Unbind(GalShaderType type) + { + switch (type) + { + case GalShaderType.Vertex: Current.Vertex = null; break; + case GalShaderType.TessControl: Current.TessControl = null; break; + case GalShaderType.TessEvaluation: Current.TessEvaluation = null; break; + case GalShaderType.Geometry: Current.Geometry = null; break; + case GalShaderType.Fragment: Current.Fragment = null; break; + } + } + + public void BindProgram() + { + if (Current.Vertex == null || + Current.Fragment == null) + { + return; + } + + if (!_programs.TryGetValue(Current, out int handle)) + { + handle = GL.CreateProgram(); + + AttachIfNotNull(handle, Current.Vertex); + AttachIfNotNull(handle, Current.TessControl); + AttachIfNotNull(handle, Current.TessEvaluation); + AttachIfNotNull(handle, Current.Geometry); + AttachIfNotNull(handle, Current.Fragment); + + GL.LinkProgram(handle); + + CheckProgramLink(handle); + + BindUniformBlocks(handle); + BindTextureLocations(handle); + + _programs.Add(Current, handle); + } + + GL.UseProgram(handle); + + CurrentProgramHandle = handle; + } + + private void EnsureExtraBlock() + { + if (_extraUboHandle == 0) + { + _extraUboHandle = GL.GenBuffer(); + + GL.BindBuffer(BufferTarget.UniformBuffer, _extraUboHandle); + + GL.BufferData(BufferTarget.UniformBuffer, ExtraDataSize * sizeof(float), IntPtr.Zero, BufferUsageHint.StreamDraw); + + GL.BindBufferBase(BufferRangeTarget.UniformBuffer, 0, _extraUboHandle); + } + } + + private void AttachIfNotNull(int programHandle, OglShaderStage stage) + { + if (stage != null) + { + stage.Compile(); + + GL.AttachShader(programHandle, stage.Handle); + } + } + + private void BindUniformBlocks(int programHandle) + { + int extraBlockindex = GL.GetUniformBlockIndex(programHandle, GlslDecl.ExtraUniformBlockName); + + GL.UniformBlockBinding(programHandle, extraBlockindex, 0); + + int freeBinding = ReservedCbufCount; + + void BindUniformBlocksIfNotNull(OglShaderStage stage) + { + if (stage != null) + { + foreach (ShaderDeclInfo declInfo in stage.ConstBufferUsage) + { + int blockIndex = GL.GetUniformBlockIndex(programHandle, declInfo.Name); + + if (blockIndex < 0) + { + //It is expected that its found, if it's not then driver might be in a malfunction + throw new InvalidOperationException(); + } + + GL.UniformBlockBinding(programHandle, blockIndex, freeBinding); + + freeBinding++; + } + } + } + + BindUniformBlocksIfNotNull(Current.Vertex); + BindUniformBlocksIfNotNull(Current.TessControl); + BindUniformBlocksIfNotNull(Current.TessEvaluation); + BindUniformBlocksIfNotNull(Current.Geometry); + BindUniformBlocksIfNotNull(Current.Fragment); + } + + private void BindTextureLocations(int programHandle) + { + int index = 0; + + void BindTexturesIfNotNull(OglShaderStage stage) + { + if (stage != null) + { + foreach (ShaderDeclInfo decl in stage.TextureUsage) + { + int location = GL.GetUniformLocation(programHandle, decl.Name); + + GL.Uniform1(location, index); + + index++; + } + } + } + + GL.UseProgram(programHandle); + + BindTexturesIfNotNull(Current.Vertex); + BindTexturesIfNotNull(Current.TessControl); + BindTexturesIfNotNull(Current.TessEvaluation); + BindTexturesIfNotNull(Current.Geometry); + BindTexturesIfNotNull(Current.Fragment); + } + + private static void CheckProgramLink(int handle) + { + int status = 0; + + GL.GetProgram(handle, GetProgramParameterName.LinkStatus, out status); + + if (status == 0) + { + throw new ShaderException(GL.GetProgramInfoLog(handle)); + } + } + } +} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglShaderProgram.cs b/Ryujinx.Graphics/Gal/OpenGL/OglShaderProgram.cs new file mode 100644 index 00000000..9e68a8e6 --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglShaderProgram.cs @@ -0,0 +1,86 @@ +using OpenTK.Graphics.OpenGL; +using System; +using System.Collections.Generic; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + struct OglShaderProgram + { + public OglShaderStage Vertex; + public OglShaderStage TessControl; + public OglShaderStage TessEvaluation; + public OglShaderStage Geometry; + public OglShaderStage Fragment; + } + + class OglShaderStage : IDisposable + { + public int Handle { get; private set; } + + public bool IsCompiled { get; private set; } + + public GalShaderType Type { get; private set; } + + public string Code { get; private set; } + + public IEnumerable ConstBufferUsage { get; private set; } + public IEnumerable TextureUsage { get; private set; } + + public OglShaderStage( + GalShaderType type, + string code, + IEnumerable constBufferUsage, + IEnumerable textureUsage) + { + Type = type; + Code = code; + ConstBufferUsage = constBufferUsage; + TextureUsage = textureUsage; + } + + public void Compile() + { + if (Handle == 0) + { + Handle = GL.CreateShader(OglEnumConverter.GetShaderType(Type)); + + CompileAndCheck(Handle, Code); + } + } + + public void Dispose() + { + Dispose(true); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing && Handle != 0) + { + GL.DeleteShader(Handle); + + Handle = 0; + } + } + + public static void CompileAndCheck(int handle, string code) + { + GL.ShaderSource(handle, code); + GL.CompileShader(handle); + + CheckCompilation(handle); + } + + private static void CheckCompilation(int handle) + { + int status = 0; + + GL.GetShader(handle, ShaderParameter.CompileStatus, out status); + + if (status == 0) + { + throw new ShaderException(GL.GetShaderInfoLog(handle)); + } + } + } +} \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLStreamBuffer.cs b/Ryujinx.Graphics/Gal/OpenGL/OglStreamBuffer.cs similarity index 51% rename from Ryujinx.Graphics/Gal/OpenGL/OGLStreamBuffer.cs rename to Ryujinx.Graphics/Gal/OpenGL/OglStreamBuffer.cs index 411d33aa..58b3ace5 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLStreamBuffer.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OglStreamBuffer.cs @@ -3,7 +3,7 @@ using System; namespace Ryujinx.Graphics.Gal.OpenGL { - class OGLStreamBuffer : IDisposable + class OglStreamBuffer : IDisposable { public int Handle { get; protected set; } @@ -11,30 +11,30 @@ namespace Ryujinx.Graphics.Gal.OpenGL protected BufferTarget Target { get; private set; } - public OGLStreamBuffer(BufferTarget Target, long Size) + public OglStreamBuffer(BufferTarget target, long size) { - this.Target = Target; - this.Size = Size; + Target = target; + Size = size; Handle = GL.GenBuffer(); - GL.BindBuffer(Target, Handle); + GL.BindBuffer(target, Handle); - GL.BufferData(Target, (IntPtr)Size, IntPtr.Zero, BufferUsageHint.StreamDraw); + GL.BufferData(target, (IntPtr)size, IntPtr.Zero, BufferUsageHint.StreamDraw); } - public void SetData(long Size, IntPtr HostAddress) + public void SetData(long size, IntPtr hostAddress) { GL.BindBuffer(Target, Handle); - GL.BufferSubData(Target, IntPtr.Zero, (IntPtr)Size, HostAddress); + GL.BufferSubData(Target, IntPtr.Zero, (IntPtr)size, hostAddress); } - public void SetData(byte[] Data) + public void SetData(byte[] data) { GL.BindBuffer(Target, Handle); - GL.BufferSubData(Target, IntPtr.Zero, (IntPtr)Data.Length, Data); + GL.BufferSubData(Target, IntPtr.Zero, (IntPtr)data.Length, data); } public void Dispose() @@ -42,9 +42,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing && Handle != 0) + if (disposing && Handle != 0) { GL.DeleteBuffer(Handle); diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglTexture.cs b/Ryujinx.Graphics/Gal/OpenGL/OglTexture.cs new file mode 100644 index 00000000..f836702f --- /dev/null +++ b/Ryujinx.Graphics/Gal/OpenGL/OglTexture.cs @@ -0,0 +1,381 @@ +using OpenTK.Graphics.OpenGL; +using Ryujinx.Graphics.Texture; +using System; + +namespace Ryujinx.Graphics.Gal.OpenGL +{ + class OglTexture : IGalTexture + { + private const long MaxTextureCacheSize = 768 * 1024 * 1024; + + private OglCachedResource _textureCache; + + public EventHandler TextureDeleted { get; set; } + + public OglTexture() + { + _textureCache = new OglCachedResource(DeleteTexture, MaxTextureCacheSize); + } + + public void LockCache() + { + _textureCache.Lock(); + } + + public void UnlockCache() + { + _textureCache.Unlock(); + } + + private void DeleteTexture(ImageHandler cachedImage) + { + TextureDeleted?.Invoke(this, cachedImage.Handle); + + GL.DeleteTexture(cachedImage.Handle); + } + + public void Create(long key, int size, GalImage image) + { + int handle = GL.GenTexture(); + + TextureTarget target = ImageUtils.GetTextureTarget(image.TextureTarget); + + GL.BindTexture(target, handle); + + const int level = 0; //TODO: Support mipmap textures. + const int border = 0; + + _textureCache.AddOrUpdate(key, new ImageHandler(handle, image), (uint)size); + + if (ImageUtils.IsCompressed(image.Format)) + { + throw new InvalidOperationException("Surfaces with compressed formats are not supported!"); + } + + (PixelInternalFormat internalFmt, + PixelFormat format, + PixelType type) = OglEnumConverter.GetImageFormat(image.Format); + + switch (target) + { + case TextureTarget.Texture1D: + GL.TexImage1D( + target, + level, + internalFmt, + image.Width, + border, + format, + type, + IntPtr.Zero); + break; + + case TextureTarget.Texture2D: + GL.TexImage2D( + target, + level, + internalFmt, + image.Width, + image.Height, + border, + format, + type, + IntPtr.Zero); + break; + case TextureTarget.Texture3D: + GL.TexImage3D( + target, + level, + internalFmt, + image.Width, + image.Height, + image.Depth, + border, + format, + type, + IntPtr.Zero); + break; + case TextureTarget.Texture2DArray: + GL.TexImage3D( + target, + level, + internalFmt, + image.Width, + image.Height, + image.LayerCount, + border, + format, + type, + IntPtr.Zero); + break; + default: + throw new NotImplementedException($"Unsupported texture target type: {target}"); + } + } + + public void Create(long key, byte[] data, GalImage image) + { + int handle = GL.GenTexture(); + + TextureTarget target = ImageUtils.GetTextureTarget(image.TextureTarget); + + GL.BindTexture(target, handle); + + const int level = 0; //TODO: Support mipmap textures. + const int border = 0; + + _textureCache.AddOrUpdate(key, new ImageHandler(handle, image), (uint)data.Length); + + if (ImageUtils.IsCompressed(image.Format) && !IsAstc(image.Format)) + { + InternalFormat internalFmt = OglEnumConverter.GetCompressedImageFormat(image.Format); + + switch (target) + { + case TextureTarget.Texture1D: + GL.CompressedTexImage1D( + target, + level, + internalFmt, + image.Width, + border, + data.Length, + data); + break; + case TextureTarget.Texture2D: + GL.CompressedTexImage2D( + target, + level, + internalFmt, + image.Width, + image.Height, + border, + data.Length, + data); + break; + case TextureTarget.Texture3D: + GL.CompressedTexImage3D( + target, + level, + internalFmt, + image.Width, + image.Height, + image.Depth, + border, + data.Length, + data); + break; + case TextureTarget.Texture2DArray: + GL.CompressedTexImage3D( + target, + level, + internalFmt, + image.Width, + image.Height, + image.LayerCount, + border, + data.Length, + data); + break; + default: + throw new NotImplementedException($"Unsupported texture target type: {target}"); + } + } + else + { + //TODO: Use KHR_texture_compression_astc_hdr when available + if (IsAstc(image.Format)) + { + int textureBlockWidth = ImageUtils.GetBlockWidth(image.Format); + int textureBlockHeight = ImageUtils.GetBlockHeight(image.Format); + int textureBlockDepth = ImageUtils.GetBlockDepth(image.Format); + + data = AstcDecoder.DecodeToRgba8888( + data, + textureBlockWidth, + textureBlockHeight, + textureBlockDepth, + image.Width, + image.Height, + image.Depth); + + image.Format = GalImageFormat.Rgba8 | (image.Format & GalImageFormat.TypeMask); + } + + (PixelInternalFormat internalFmt, + PixelFormat format, + PixelType type) = OglEnumConverter.GetImageFormat(image.Format); + + + switch (target) + { + case TextureTarget.Texture1D: + GL.TexImage1D( + target, + level, + internalFmt, + image.Width, + border, + format, + type, + data); + break; + case TextureTarget.Texture2D: + GL.TexImage2D( + target, + level, + internalFmt, + image.Width, + image.Height, + border, + format, + type, + data); + break; + case TextureTarget.Texture3D: + GL.TexImage3D( + target, + level, + internalFmt, + image.Width, + image.Height, + image.Depth, + border, + format, + type, + data); + break; + case TextureTarget.Texture2DArray: + GL.TexImage3D( + target, + level, + internalFmt, + image.Width, + image.Height, + image.LayerCount, + border, + format, + type, + data); + break; + case TextureTarget.TextureCubeMap: + Span array = new Span(data); + + int faceSize = ImageUtils.GetSize(image) / 6; + + for (int face = 0; face < 6; face++) + { + GL.TexImage2D( + TextureTarget.TextureCubeMapPositiveX + face, + level, + internalFmt, + image.Width, + image.Height, + border, + format, + type, + array.Slice(face * faceSize, faceSize).ToArray()); + } + break; + default: + throw new NotImplementedException($"Unsupported texture target type: {target}"); + } + } + } + + private static bool IsAstc(GalImageFormat format) + { + format &= GalImageFormat.FormatMask; + + return format > GalImageFormat.Astc2DStart && format < GalImageFormat.Astc2DEnd; + } + + public bool TryGetImage(long key, out GalImage image) + { + if (_textureCache.TryGetValue(key, out ImageHandler cachedImage)) + { + image = cachedImage.Image; + + return true; + } + + image = default(GalImage); + + return false; + } + + public bool TryGetImageHandler(long key, out ImageHandler cachedImage) + { + if (_textureCache.TryGetValue(key, out cachedImage)) + { + return true; + } + + cachedImage = null; + + return false; + } + + public void Bind(long key, int index, GalImage image) + { + if (_textureCache.TryGetValue(key, out ImageHandler cachedImage)) + { + GL.ActiveTexture(TextureUnit.Texture0 + index); + + TextureTarget target = ImageUtils.GetTextureTarget(image.TextureTarget); + + GL.BindTexture(target, cachedImage.Handle); + + int[] swizzleRgba = new int[] + { + (int)OglEnumConverter.GetTextureSwizzle(image.XSource), + (int)OglEnumConverter.GetTextureSwizzle(image.YSource), + (int)OglEnumConverter.GetTextureSwizzle(image.ZSource), + (int)OglEnumConverter.GetTextureSwizzle(image.WSource) + }; + + GL.TexParameter(target, TextureParameterName.TextureSwizzleRgba, swizzleRgba); + } + } + + public void SetSampler(GalImage image, GalTextureSampler sampler) + { + int wrapS = (int)OglEnumConverter.GetTextureWrapMode(sampler.AddressU); + int wrapT = (int)OglEnumConverter.GetTextureWrapMode(sampler.AddressV); + int wrapR = (int)OglEnumConverter.GetTextureWrapMode(sampler.AddressP); + + int minFilter = (int)OglEnumConverter.GetTextureMinFilter(sampler.MinFilter, sampler.MipFilter); + int magFilter = (int)OglEnumConverter.GetTextureMagFilter(sampler.MagFilter); + + TextureTarget target = ImageUtils.GetTextureTarget(image.TextureTarget); + + GL.TexParameter(target, TextureParameterName.TextureWrapS, wrapS); + GL.TexParameter(target, TextureParameterName.TextureWrapT, wrapT); + GL.TexParameter(target, TextureParameterName.TextureWrapR, wrapR); + + GL.TexParameter(target, TextureParameterName.TextureMinFilter, minFilter); + GL.TexParameter(target, TextureParameterName.TextureMagFilter, magFilter); + + float[] color = new float[] + { + sampler.BorderColor.Red, + sampler.BorderColor.Green, + sampler.BorderColor.Blue, + sampler.BorderColor.Alpha + }; + + GL.TexParameter(target, TextureParameterName.TextureBorderColor, color); + + if (sampler.DepthCompare) + { + GL.TexParameter(target, TextureParameterName.TextureCompareMode, (int)All.CompareRToTexture); + GL.TexParameter(target, TextureParameterName.TextureCompareFunc, (int)OglEnumConverter.GetDepthCompareFunc(sampler.DepthCompareFunc)); + } + else + { + GL.TexParameter(target, TextureParameterName.TextureCompareMode, (int)All.None); + GL.TexParameter(target, TextureParameterName.TextureCompareFunc, (int)All.Never); + } + } + } +} diff --git a/Ryujinx.Graphics/Gal/Shader/GlslDecl.cs b/Ryujinx.Graphics/Gal/Shader/GlslDecl.cs index f7ae34fa..73426762 100644 --- a/Ryujinx.Graphics/Gal/Shader/GlslDecl.cs +++ b/Ryujinx.Graphics/Gal/Shader/GlslDecl.cs @@ -1,4 +1,3 @@ -using Ryujinx.Graphics.Gal.OpenGL; using Ryujinx.Graphics.Texture; using System; using System.Collections.Generic; @@ -51,9 +50,9 @@ namespace Ryujinx.Graphics.Gal.Shader public const string SsyStackName = "ssy_stack"; public const string SsyCursorName = "ssy_cursor"; - private string[] StagePrefixes = new string[] { "vp", "tcp", "tep", "gp", "fp" }; + private string[] _stagePrefixes = new string[] { "vp", "tcp", "tep", "gp", "fp" }; - private string StagePrefix; + private string _stagePrefix; private Dictionary m_CbTextures; @@ -83,9 +82,9 @@ namespace Ryujinx.Graphics.Gal.Shader public GalShaderType ShaderType { get; private set; } - private GlslDecl(GalShaderType ShaderType) + private GlslDecl(GalShaderType shaderType) { - this.ShaderType = ShaderType; + ShaderType = shaderType; m_CbTextures = new Dictionary(); @@ -101,187 +100,187 @@ namespace Ryujinx.Graphics.Gal.Shader m_Preds = new Dictionary(); } - public GlslDecl(ShaderIrBlock[] Blocks, GalShaderType ShaderType, ShaderHeader Header) : this(ShaderType) + public GlslDecl(ShaderIrBlock[] blocks, GalShaderType shaderType, ShaderHeader header) : this(shaderType) { - StagePrefix = StagePrefixes[(int)ShaderType] + "_"; + _stagePrefix = _stagePrefixes[(int)shaderType] + "_"; - if (ShaderType == GalShaderType.Fragment) + if (shaderType == GalShaderType.Fragment) { - int Index = 0; + int index = 0; - for (int Attachment = 0; Attachment < 8; Attachment++) + for (int attachment = 0; attachment < 8; attachment++) { - for (int Component = 0; Component < 4; Component++) + for (int component = 0; component < 4; component++) { - if (Header.OmapTargets[Attachment].ComponentEnabled(Component)) + if (header.OmapTargets[attachment].ComponentEnabled(component)) { - m_Gprs.TryAdd(Index, new ShaderDeclInfo(GetGprName(Index), Index)); + m_Gprs.TryAdd(index, new ShaderDeclInfo(GetGprName(index), index)); - Index++; + index++; } } } - if (Header.OmapDepth) + if (header.OmapDepth) { - Index = Header.DepthRegister; + index = header.DepthRegister; - m_Gprs.TryAdd(Index, new ShaderDeclInfo(GetGprName(Index), Index)); + m_Gprs.TryAdd(index, new ShaderDeclInfo(GetGprName(index), index)); } } - foreach (ShaderIrBlock Block in Blocks) + foreach (ShaderIrBlock block in blocks) { - ShaderIrNode[] Nodes = Block.GetNodes(); + ShaderIrNode[] nodes = block.GetNodes(); - foreach (ShaderIrNode Node in Nodes) + foreach (ShaderIrNode node in nodes) { - Traverse(Nodes, null, Node); + Traverse(nodes, null, node); } } } - public static GlslDecl Merge(GlslDecl VpA, GlslDecl VpB) + public static GlslDecl Merge(GlslDecl vpA, GlslDecl vpB) { - GlslDecl Combined = new GlslDecl(GalShaderType.Vertex); + GlslDecl combined = new GlslDecl(GalShaderType.Vertex); - Merge(Combined.m_Textures, VpA.m_Textures, VpB.m_Textures); - Merge(Combined.m_Uniforms, VpA.m_Uniforms, VpB.m_Uniforms); + Merge(combined.m_Textures, vpA.m_Textures, vpB.m_Textures); + Merge(combined.m_Uniforms, vpA.m_Uniforms, vpB.m_Uniforms); - Merge(Combined.m_Attributes, VpA.m_Attributes, VpB.m_Attributes); - Merge(Combined.m_OutAttributes, VpA.m_OutAttributes, VpB.m_OutAttributes); + Merge(combined.m_Attributes, vpA.m_Attributes, vpB.m_Attributes); + Merge(combined.m_OutAttributes, vpA.m_OutAttributes, vpB.m_OutAttributes); - Merge(Combined.m_Gprs, VpA.m_Gprs, VpB.m_Gprs); - Merge(Combined.m_GprsHalf, VpA.m_GprsHalf, VpB.m_GprsHalf); - Merge(Combined.m_Preds, VpA.m_Preds, VpB.m_Preds); + Merge(combined.m_Gprs, vpA.m_Gprs, vpB.m_Gprs); + Merge(combined.m_GprsHalf, vpA.m_GprsHalf, vpB.m_GprsHalf); + Merge(combined.m_Preds, vpA.m_Preds, vpB.m_Preds); //Merge input attributes. - foreach (KeyValuePair KV in VpA.m_InAttributes) + foreach (KeyValuePair kv in vpA.m_InAttributes) { - Combined.m_InAttributes.TryAdd(KV.Key, KV.Value); + combined.m_InAttributes.TryAdd(kv.Key, kv.Value); } - foreach (KeyValuePair KV in VpB.m_InAttributes) + foreach (KeyValuePair kv in vpB.m_InAttributes) { //If Vertex Program A already writes to this attribute, //then we don't need to add it as an input attribute since //Vertex Program A will already have written to it anyway, //and there's no guarantee that there is an input attribute //for this slot. - if (!VpA.m_OutAttributes.ContainsKey(KV.Key)) + if (!vpA.m_OutAttributes.ContainsKey(kv.Key)) { - Combined.m_InAttributes.TryAdd(KV.Key, KV.Value); + combined.m_InAttributes.TryAdd(kv.Key, kv.Value); } } - return Combined; + return combined; } - public static string GetGprName(int Index) + public static string GetGprName(int index) { - return GprName + Index; + return GprName + index; } private static void Merge( - Dictionary C, - Dictionary A, - Dictionary B) + Dictionary c, + Dictionary a, + Dictionary b) { - foreach (KeyValuePair KV in A) + foreach (KeyValuePair kv in a) { - C.TryAdd(KV.Key, KV.Value); + c.TryAdd(kv.Key, kv.Value); } - foreach (KeyValuePair KV in B) + foreach (KeyValuePair kv in b) { - C.TryAdd(KV.Key, KV.Value); + c.TryAdd(kv.Key, kv.Value); } } - private void Traverse(ShaderIrNode[] Nodes, ShaderIrNode Parent, ShaderIrNode Node) + private void Traverse(ShaderIrNode[] nodes, ShaderIrNode parent, ShaderIrNode node) { - switch (Node) + switch (node) { - case ShaderIrAsg Asg: + case ShaderIrAsg asg: { - Traverse(Nodes, Asg, Asg.Dst); - Traverse(Nodes, Asg, Asg.Src); + Traverse(nodes, asg, asg.Dst); + Traverse(nodes, asg, asg.Src); break; } - case ShaderIrCond Cond: + case ShaderIrCond cond: { - Traverse(Nodes, Cond, Cond.Pred); - Traverse(Nodes, Cond, Cond.Child); + Traverse(nodes, cond, cond.Pred); + Traverse(nodes, cond, cond.Child); break; } - case ShaderIrOp Op: + case ShaderIrOp op: { - Traverse(Nodes, Op, Op.OperandA); - Traverse(Nodes, Op, Op.OperandB); - Traverse(Nodes, Op, Op.OperandC); + Traverse(nodes, op, op.OperandA); + Traverse(nodes, op, op.OperandB); + Traverse(nodes, op, op.OperandC); - if (Op.Inst == ShaderIrInst.Texq || - Op.Inst == ShaderIrInst.Texs || - Op.Inst == ShaderIrInst.Tld4 || - Op.Inst == ShaderIrInst.Txlf) + if (op.Inst == ShaderIrInst.Texq || + op.Inst == ShaderIrInst.Texs || + op.Inst == ShaderIrInst.Tld4 || + op.Inst == ShaderIrInst.Txlf) { - int Handle = ((ShaderIrOperImm)Op.OperandC).Value; + int handle = ((ShaderIrOperImm)op.OperandC).Value; - int Index = Handle - TexStartIndex; + int index = handle - TexStartIndex; - string Name = StagePrefix + TextureName + Index; + string name = _stagePrefix + TextureName + index; - GalTextureTarget TextureTarget; + GalTextureTarget textureTarget; - TextureInstructionSuffix TextureInstructionSuffix; + TextureInstructionSuffix textureInstructionSuffix; // TODO: Non 2D texture type for TEXQ? - if (Op.Inst == ShaderIrInst.Texq) + if (op.Inst == ShaderIrInst.Texq) { - TextureTarget = GalTextureTarget.TwoD; - TextureInstructionSuffix = TextureInstructionSuffix.None; + textureTarget = GalTextureTarget.TwoD; + textureInstructionSuffix = TextureInstructionSuffix.None; } else { - ShaderIrMetaTex Meta = ((ShaderIrMetaTex)Op.MetaData); + ShaderIrMetaTex meta = ((ShaderIrMetaTex)op.MetaData); - TextureTarget = Meta.TextureTarget; - TextureInstructionSuffix = Meta.TextureInstructionSuffix; + textureTarget = meta.TextureTarget; + textureInstructionSuffix = meta.TextureInstructionSuffix; } - m_Textures.TryAdd(Handle, new ShaderDeclInfo(Name, Handle, false, 0, 1, TextureTarget, TextureInstructionSuffix)); + m_Textures.TryAdd(handle, new ShaderDeclInfo(name, handle, false, 0, 1, textureTarget, textureInstructionSuffix)); } - else if (Op.Inst == ShaderIrInst.Texb) + else if (op.Inst == ShaderIrInst.Texb) { - ShaderIrNode HandleSrc = null; + ShaderIrNode handleSrc = null; - int Index = Array.IndexOf(Nodes, Parent) - 1; + int index = Array.IndexOf(nodes, parent) - 1; - for (; Index >= 0; Index--) + for (; index >= 0; index--) { - ShaderIrNode Curr = Nodes[Index]; + ShaderIrNode curr = nodes[index]; - if (Curr is ShaderIrAsg Asg && Asg.Dst is ShaderIrOperGpr Gpr) + if (curr is ShaderIrAsg asg && asg.Dst is ShaderIrOperGpr gpr) { - if (Gpr.Index == ((ShaderIrOperGpr)Op.OperandC).Index) + if (gpr.Index == ((ShaderIrOperGpr)op.OperandC).Index) { - HandleSrc = Asg.Src; + handleSrc = asg.Src; break; } } } - if (HandleSrc != null && HandleSrc is ShaderIrOperCbuf Cbuf) + if (handleSrc != null && handleSrc is ShaderIrOperCbuf cbuf) { - ShaderIrMetaTex Meta = ((ShaderIrMetaTex)Op.MetaData); - string Name = StagePrefix + TextureName + "_cb" + Cbuf.Index + "_" + Cbuf.Pos; + ShaderIrMetaTex meta = ((ShaderIrMetaTex)op.MetaData); + string name = _stagePrefix + TextureName + "_cb" + cbuf.Index + "_" + cbuf.Pos; - m_CbTextures.Add(Op, new ShaderDeclInfo(Name, Cbuf.Pos, true, Cbuf.Index, 1, Meta.TextureTarget, Meta.TextureInstructionSuffix)); + m_CbTextures.Add(op, new ShaderDeclInfo(name, cbuf.Pos, true, cbuf.Index, 1, meta.TextureTarget, meta.TextureInstructionSuffix)); } else { @@ -291,93 +290,93 @@ namespace Ryujinx.Graphics.Gal.Shader break; } - case ShaderIrOperCbuf Cbuf: + case ShaderIrOperCbuf cbuf: { - if (!m_Uniforms.ContainsKey(Cbuf.Index)) + if (!m_Uniforms.ContainsKey(cbuf.Index)) { - string Name = StagePrefix + UniformName + Cbuf.Index; + string name = _stagePrefix + UniformName + cbuf.Index; - ShaderDeclInfo DeclInfo = new ShaderDeclInfo(Name, Cbuf.Pos, true, Cbuf.Index); + ShaderDeclInfo declInfo = new ShaderDeclInfo(name, cbuf.Pos, true, cbuf.Index); - m_Uniforms.Add(Cbuf.Index, DeclInfo); + m_Uniforms.Add(cbuf.Index, declInfo); } break; } - case ShaderIrOperAbuf Abuf: + case ShaderIrOperAbuf abuf: { //This is a built-in variable. - if (Abuf.Offs == LayerAttr || - Abuf.Offs == PointSizeAttr || - Abuf.Offs == PointCoordAttrX || - Abuf.Offs == PointCoordAttrY || - Abuf.Offs == VertexIdAttr || - Abuf.Offs == InstanceIdAttr || - Abuf.Offs == FaceAttr) + if (abuf.Offs == LayerAttr || + abuf.Offs == PointSizeAttr || + abuf.Offs == PointCoordAttrX || + abuf.Offs == PointCoordAttrY || + abuf.Offs == VertexIdAttr || + abuf.Offs == InstanceIdAttr || + abuf.Offs == FaceAttr) { break; } - int Index = Abuf.Offs >> 4; - int Elem = (Abuf.Offs >> 2) & 3; + int index = abuf.Offs >> 4; + int elem = (abuf.Offs >> 2) & 3; - int GlslIndex = Index - AttrStartIndex; + int glslIndex = index - AttrStartIndex; - if (GlslIndex < 0) + if (glslIndex < 0) { return; } - ShaderDeclInfo DeclInfo; + ShaderDeclInfo declInfo; - if (Parent is ShaderIrAsg Asg && Asg.Dst == Node) + if (parent is ShaderIrAsg asg && asg.Dst == node) { - if (!m_OutAttributes.TryGetValue(Index, out DeclInfo)) + if (!m_OutAttributes.TryGetValue(index, out declInfo)) { - DeclInfo = new ShaderDeclInfo(OutAttrName + GlslIndex, GlslIndex); + declInfo = new ShaderDeclInfo(OutAttrName + glslIndex, glslIndex); - m_OutAttributes.Add(Index, DeclInfo); + m_OutAttributes.Add(index, declInfo); } } else { - if (!m_InAttributes.TryGetValue(Index, out DeclInfo)) + if (!m_InAttributes.TryGetValue(index, out declInfo)) { - DeclInfo = new ShaderDeclInfo(InAttrName + GlslIndex, GlslIndex); + declInfo = new ShaderDeclInfo(InAttrName + glslIndex, glslIndex); - m_InAttributes.Add(Index, DeclInfo); + m_InAttributes.Add(index, declInfo); } } - DeclInfo.Enlarge(Elem + 1); + declInfo.Enlarge(elem + 1); - if (!m_Attributes.ContainsKey(Index)) + if (!m_Attributes.ContainsKey(index)) { - DeclInfo = new ShaderDeclInfo(AttrName + GlslIndex, GlslIndex, false, 0, 4); + declInfo = new ShaderDeclInfo(AttrName + glslIndex, glslIndex, false, 0, 4); - m_Attributes.Add(Index, DeclInfo); + m_Attributes.Add(index, declInfo); } - Traverse(Nodes, Abuf, Abuf.Vertex); + Traverse(nodes, abuf, abuf.Vertex); break; } - case ShaderIrOperGpr Gpr: + case ShaderIrOperGpr gpr: { - if (!Gpr.IsConst) + if (!gpr.IsConst) { - string Name = GetGprName(Gpr.Index); + string name = GetGprName(gpr.Index); - if (Gpr.RegisterSize == ShaderRegisterSize.Single) + if (gpr.RegisterSize == ShaderRegisterSize.Single) { - m_Gprs.TryAdd(Gpr.Index, new ShaderDeclInfo(Name, Gpr.Index)); + m_Gprs.TryAdd(gpr.Index, new ShaderDeclInfo(name, gpr.Index)); } - else if (Gpr.RegisterSize == ShaderRegisterSize.Half) + else if (gpr.RegisterSize == ShaderRegisterSize.Half) { - Name += "_h" + Gpr.HalfPart; + name += "_h" + gpr.HalfPart; - m_GprsHalf.TryAdd((Gpr.Index << 1) | Gpr.HalfPart, new ShaderDeclInfo(Name, Gpr.Index)); + m_GprsHalf.TryAdd((gpr.Index << 1) | gpr.HalfPart, new ShaderDeclInfo(name, gpr.Index)); } else /* if (Gpr.RegisterSize == ShaderRegisterSize.Double) */ { @@ -387,35 +386,35 @@ namespace Ryujinx.Graphics.Gal.Shader break; } - case ShaderIrOperPred Pred: + case ShaderIrOperPred pred: { - if (!Pred.IsConst && !HasName(m_Preds, Pred.Index)) + if (!pred.IsConst && !HasName(m_Preds, pred.Index)) { - string Name = PredName + Pred.Index; + string name = PredName + pred.Index; - m_Preds.TryAdd(Pred.Index, new ShaderDeclInfo(Name, Pred.Index)); + m_Preds.TryAdd(pred.Index, new ShaderDeclInfo(name, pred.Index)); } break; } } } - private bool HasName(Dictionary Decls, int Index) + private bool HasName(Dictionary decls, int index) { //This is used to check if the dictionary already contains //a entry for a vector at a given index position. //Used to enable turning gprs into vectors. - int VecIndex = Index & ~3; + int vecIndex = index & ~3; - if (Decls.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo)) + if (decls.TryGetValue(vecIndex, out ShaderDeclInfo declInfo)) { - if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size) + if (declInfo.Size > 1 && index < vecIndex + declInfo.Size) { return true; } } - return Decls.ContainsKey(Index); + return decls.ContainsKey(index); } } } diff --git a/Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs b/Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs index 5f809525..228a9018 100644 --- a/Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs +++ b/Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs @@ -10,9 +10,9 @@ namespace Ryujinx.Graphics.Gal.Shader { public class GlslDecompiler { - private delegate string GetInstExpr(ShaderIrOp Op); + private delegate string GetInstExpr(ShaderIrOp op); - private Dictionary InstsExpr; + private Dictionary _instsExpr; private enum OperType { @@ -25,21 +25,21 @@ namespace Ryujinx.Graphics.Gal.Shader private const int MaxVertexInput = 3; - private GlslDecl Decl; + private GlslDecl _decl; - private ShaderHeader Header, HeaderB; + private ShaderHeader _header, _headerB; - private ShaderIrBlock[] Blocks, BlocksB; + private ShaderIrBlock[] _blocks, _blocksB; - private StringBuilder SB; + private StringBuilder _sb; public int MaxUboSize { get; } - private bool IsNvidiaDriver; + private bool _isNvidiaDriver; - public GlslDecompiler(int MaxUboSize, bool IsNvidiaDriver) + public GlslDecompiler(int maxUboSize, bool isNvidiaDriver) { - InstsExpr = new Dictionary() + _instsExpr = new Dictionary() { { ShaderIrInst.Abs, GetAbsExpr }, { ShaderIrInst.Add, GetAddExpr }, @@ -114,48 +114,48 @@ namespace Ryujinx.Graphics.Gal.Shader { ShaderIrInst.Xor, GetXorExpr } }; - this.MaxUboSize = MaxUboSize / 16; - this.IsNvidiaDriver = IsNvidiaDriver; + MaxUboSize = maxUboSize / 16; + _isNvidiaDriver = isNvidiaDriver; } public GlslProgram Decompile( - IGalMemory Memory, - long VpAPosition, - long VpBPosition, - GalShaderType ShaderType) + IGalMemory memory, + long vpAPosition, + long vpBPosition, + GalShaderType shaderType) { - Header = new ShaderHeader(Memory, VpAPosition); - HeaderB = new ShaderHeader(Memory, VpBPosition); + _header = new ShaderHeader(memory, vpAPosition); + _headerB = new ShaderHeader(memory, vpBPosition); - Blocks = ShaderDecoder.Decode(Memory, VpAPosition); - BlocksB = ShaderDecoder.Decode(Memory, VpBPosition); + _blocks = ShaderDecoder.Decode(memory, vpAPosition); + _blocksB = ShaderDecoder.Decode(memory, vpBPosition); - GlslDecl DeclVpA = new GlslDecl(Blocks, ShaderType, Header); - GlslDecl DeclVpB = new GlslDecl(BlocksB, ShaderType, HeaderB); + GlslDecl declVpA = new GlslDecl(_blocks, shaderType, _header); + GlslDecl declVpB = new GlslDecl(_blocksB, shaderType, _headerB); - Decl = GlslDecl.Merge(DeclVpA, DeclVpB); + _decl = GlslDecl.Merge(declVpA, declVpB); return Decompile(); } - public GlslProgram Decompile(IGalMemory Memory, long Position, GalShaderType ShaderType) + public GlslProgram Decompile(IGalMemory memory, long position, GalShaderType shaderType) { - Header = new ShaderHeader(Memory, Position); - HeaderB = null; + _header = new ShaderHeader(memory, position); + _headerB = null; - Blocks = ShaderDecoder.Decode(Memory, Position); - BlocksB = null; + _blocks = ShaderDecoder.Decode(memory, position); + _blocksB = null; - Decl = new GlslDecl(Blocks, ShaderType, Header); + _decl = new GlslDecl(_blocks, shaderType, _header); return Decompile(); } private GlslProgram Decompile() { - SB = new StringBuilder(); + _sb = new StringBuilder(); - SB.AppendLine("#version 410 core"); + _sb.AppendLine("#version 410 core"); PrintDeclHeader(); PrintDeclTextures(); @@ -167,599 +167,599 @@ namespace Ryujinx.Graphics.Gal.Shader PrintDeclPreds(); PrintDeclSsy(); - if (BlocksB != null) + if (_blocksB != null) { - PrintBlockScope(Blocks, GlslDecl.BasicBlockAName); + PrintBlockScope(_blocks, GlslDecl.BasicBlockAName); - SB.AppendLine(); + _sb.AppendLine(); - PrintBlockScope(BlocksB, GlslDecl.BasicBlockBName); + PrintBlockScope(_blocksB, GlslDecl.BasicBlockBName); } else { - PrintBlockScope(Blocks, GlslDecl.BasicBlockName); + PrintBlockScope(_blocks, GlslDecl.BasicBlockName); } - SB.AppendLine(); + _sb.AppendLine(); PrintMain(); - string GlslCode = SB.ToString(); + string glslCode = _sb.ToString(); - List TextureInfo = new List(); + List textureInfo = new List(); - TextureInfo.AddRange(Decl.Textures.Values); - TextureInfo.AddRange(IterateCbTextures()); + textureInfo.AddRange(_decl.Textures.Values); + textureInfo.AddRange(IterateCbTextures()); - return new GlslProgram(GlslCode, TextureInfo, Decl.Uniforms.Values); + return new GlslProgram(glslCode, textureInfo, _decl.Uniforms.Values); } private void PrintDeclHeader() { - if (Decl.ShaderType == GalShaderType.Geometry) + if (_decl.ShaderType == GalShaderType.Geometry) { - int MaxVertices = Header.MaxOutputVertexCount; + int maxVertices = _header.MaxOutputVertexCount; - string OutputTopology; + string outputTopology; - switch (Header.OutputTopology) + switch (_header.OutputTopology) { - case ShaderHeader.PointList: OutputTopology = "points"; break; - case ShaderHeader.LineStrip: OutputTopology = "line_strip"; break; - case ShaderHeader.TriangleStrip: OutputTopology = "triangle_strip"; break; + case ShaderHeader.PointList: outputTopology = "points"; break; + case ShaderHeader.LineStrip: outputTopology = "line_strip"; break; + case ShaderHeader.TriangleStrip: outputTopology = "triangle_strip"; break; default: throw new InvalidOperationException(); } - SB.AppendLine("#extension GL_ARB_enhanced_layouts : require"); + _sb.AppendLine("#extension GL_ARB_enhanced_layouts : require"); - SB.AppendLine(); + _sb.AppendLine(); - SB.AppendLine("// Stubbed. Maxwell geometry shaders don't inform input geometry type"); + _sb.AppendLine("// Stubbed. Maxwell geometry shaders don't inform input geometry type"); - SB.AppendLine("layout(triangles) in;" + Environment.NewLine); + _sb.AppendLine("layout(triangles) in;" + Environment.NewLine); - SB.AppendLine($"layout({OutputTopology}, max_vertices = {MaxVertices}) out;"); + _sb.AppendLine($"layout({outputTopology}, max_vertices = {maxVertices}) out;"); - SB.AppendLine(); + _sb.AppendLine(); } } - private string GetSamplerType(TextureTarget TextureTarget, bool HasShadow) + private string GetSamplerType(TextureTarget textureTarget, bool hasShadow) { - string Result; + string result; - switch (TextureTarget) + switch (textureTarget) { case TextureTarget.Texture1D: - Result = "sampler1D"; + result = "sampler1D"; break; case TextureTarget.Texture2D: - Result = "sampler2D"; + result = "sampler2D"; break; case TextureTarget.Texture3D: - Result = "sampler3D"; + result = "sampler3D"; break; case TextureTarget.TextureCubeMap: - Result = "samplerCube"; + result = "samplerCube"; break; case TextureTarget.TextureRectangle: - Result = "sampler2DRect"; + result = "sampler2DRect"; break; case TextureTarget.Texture1DArray: - Result = "sampler1DArray"; + result = "sampler1DArray"; break; case TextureTarget.Texture2DArray: - Result = "sampler2DArray"; + result = "sampler2DArray"; break; case TextureTarget.TextureCubeMapArray: - Result = "samplerCubeArray"; + result = "samplerCubeArray"; break; case TextureTarget.TextureBuffer: - Result = "samplerBuffer"; + result = "samplerBuffer"; break; case TextureTarget.Texture2DMultisample: - Result = "sampler2DMS"; + result = "sampler2DMS"; break; case TextureTarget.Texture2DMultisampleArray: - Result = "sampler2DMSArray"; + result = "sampler2DMSArray"; break; default: throw new NotSupportedException(); } - if (HasShadow) - Result += "Shadow"; + if (hasShadow) + result += "Shadow"; - return Result; + return result; } private void PrintDeclTextures() { - foreach (ShaderDeclInfo DeclInfo in IterateCbTextures()) + foreach (ShaderDeclInfo declInfo in IterateCbTextures()) { - TextureTarget Target = ImageUtils.GetTextureTarget(DeclInfo.TextureTarget); - SB.AppendLine($"// {DeclInfo.TextureSuffix}"); - SB.AppendLine("uniform " + GetSamplerType(Target, (DeclInfo.TextureSuffix & TextureInstructionSuffix.DC) != 0) + " " + DeclInfo.Name + ";"); + TextureTarget target = ImageUtils.GetTextureTarget(declInfo.TextureTarget); + _sb.AppendLine($"// {declInfo.TextureSuffix}"); + _sb.AppendLine("uniform " + GetSamplerType(target, (declInfo.TextureSuffix & TextureInstructionSuffix.Dc) != 0) + " " + declInfo.Name + ";"); } - foreach (ShaderDeclInfo DeclInfo in Decl.Textures.Values.OrderBy(DeclKeySelector)) + foreach (ShaderDeclInfo declInfo in _decl.Textures.Values.OrderBy(DeclKeySelector)) { - TextureTarget Target = ImageUtils.GetTextureTarget(DeclInfo.TextureTarget); - SB.AppendLine($"// {DeclInfo.TextureSuffix}"); - SB.AppendLine("uniform " + GetSamplerType(Target, (DeclInfo.TextureSuffix & TextureInstructionSuffix.DC) != 0) + " " + DeclInfo.Name + ";"); + TextureTarget target = ImageUtils.GetTextureTarget(declInfo.TextureTarget); + _sb.AppendLine($"// {declInfo.TextureSuffix}"); + _sb.AppendLine("uniform " + GetSamplerType(target, (declInfo.TextureSuffix & TextureInstructionSuffix.Dc) != 0) + " " + declInfo.Name + ";"); } } private IEnumerable IterateCbTextures() { - HashSet Names = new HashSet(); + HashSet names = new HashSet(); - foreach (ShaderDeclInfo DeclInfo in Decl.CbTextures.Values.OrderBy(DeclKeySelector)) + foreach (ShaderDeclInfo declInfo in _decl.CbTextures.Values.OrderBy(DeclKeySelector)) { - if (Names.Add(DeclInfo.Name)) + if (names.Add(declInfo.Name)) { - yield return DeclInfo; + yield return declInfo; } } } private void PrintDeclUniforms() { - if (Decl.ShaderType == GalShaderType.Vertex) + if (_decl.ShaderType == GalShaderType.Vertex) { //Memory layout here is [flip_x, flip_y, instance, unused] //It's using 4 bytes, not 8 - SB.AppendLine("layout (std140) uniform " + GlslDecl.ExtraUniformBlockName + " {"); + _sb.AppendLine("layout (std140) uniform " + GlslDecl.ExtraUniformBlockName + " {"); - SB.AppendLine(IdentationStr + "vec2 " + GlslDecl.FlipUniformName + ";"); + _sb.AppendLine(IdentationStr + "vec2 " + GlslDecl.FlipUniformName + ";"); - SB.AppendLine(IdentationStr + "int " + GlslDecl.InstanceUniformName + ";"); + _sb.AppendLine(IdentationStr + "int " + GlslDecl.InstanceUniformName + ";"); - SB.AppendLine("};"); - SB.AppendLine(); + _sb.AppendLine("};"); + _sb.AppendLine(); } - foreach (ShaderDeclInfo DeclInfo in Decl.Uniforms.Values.OrderBy(DeclKeySelector)) + foreach (ShaderDeclInfo declInfo in _decl.Uniforms.Values.OrderBy(DeclKeySelector)) { - SB.AppendLine($"layout (std140) uniform {DeclInfo.Name} {{"); + _sb.AppendLine($"layout (std140) uniform {declInfo.Name} {{"); - SB.AppendLine($"{IdentationStr}vec4 {DeclInfo.Name}_data[{MaxUboSize}];"); + _sb.AppendLine($"{IdentationStr}vec4 {declInfo.Name}_data[{MaxUboSize}];"); - SB.AppendLine("};"); + _sb.AppendLine("};"); } - if (Decl.Uniforms.Count > 0) + if (_decl.Uniforms.Count > 0) { - SB.AppendLine(); + _sb.AppendLine(); } } private void PrintDeclAttributes() { - string GeometryArray = (Decl.ShaderType == GalShaderType.Geometry) ? "[" + MaxVertexInput + "]" : ""; + string geometryArray = (_decl.ShaderType == GalShaderType.Geometry) ? "[" + MaxVertexInput + "]" : ""; - PrintDecls(Decl.Attributes, Suffix: GeometryArray); + PrintDecls(_decl.Attributes, suffix: geometryArray); } private void PrintDeclInAttributes() { - if (Decl.ShaderType == GalShaderType.Fragment) + if (_decl.ShaderType == GalShaderType.Fragment) { - SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";"); + _sb.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";"); } - if (Decl.ShaderType == GalShaderType.Geometry) + if (_decl.ShaderType == GalShaderType.Geometry) { - if (Decl.InAttributes.Count > 0) + if (_decl.InAttributes.Count > 0) { - SB.AppendLine("in Vertex {"); + _sb.AppendLine("in Vertex {"); - foreach (ShaderDeclInfo DeclInfo in Decl.InAttributes.Values.OrderBy(DeclKeySelector)) + foreach (ShaderDeclInfo declInfo in _decl.InAttributes.Values.OrderBy(DeclKeySelector)) { - if (DeclInfo.Index >= 0) + if (declInfo.Index >= 0) { - SB.AppendLine(IdentationStr + "layout (location = " + DeclInfo.Index + ") vec4 " + DeclInfo.Name + "; "); + _sb.AppendLine(IdentationStr + "layout (location = " + declInfo.Index + ") vec4 " + declInfo.Name + "; "); } } - SB.AppendLine("} block_in[];" + Environment.NewLine); + _sb.AppendLine("} block_in[];" + Environment.NewLine); } } else { - PrintDeclAttributes(Decl.InAttributes.Values, "in"); + PrintDeclAttributes(_decl.InAttributes.Values, "in"); } } private void PrintDeclOutAttributes() { - if (Decl.ShaderType == GalShaderType.Fragment) + if (_decl.ShaderType == GalShaderType.Fragment) { - int Count = 0; + int count = 0; - for (int Attachment = 0; Attachment < 8; Attachment++) + for (int attachment = 0; attachment < 8; attachment++) { - if (Header.OmapTargets[Attachment].Enabled) + if (_header.OmapTargets[attachment].Enabled) { - SB.AppendLine("layout (location = " + Attachment + ") out vec4 " + GlslDecl.FragmentOutputName + Attachment + ";"); + _sb.AppendLine("layout (location = " + attachment + ") out vec4 " + GlslDecl.FragmentOutputName + attachment + ";"); - Count++; + count++; } } - if (Count > 0) + if (count > 0) { - SB.AppendLine(); + _sb.AppendLine(); } } else { - SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") out vec4 " + GlslDecl.PositionOutAttrName + ";"); - SB.AppendLine(); + _sb.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") out vec4 " + GlslDecl.PositionOutAttrName + ";"); + _sb.AppendLine(); } - PrintDeclAttributes(Decl.OutAttributes.Values, "out"); + PrintDeclAttributes(_decl.OutAttributes.Values, "out"); } - private void PrintDeclAttributes(IEnumerable Decls, string InOut) + private void PrintDeclAttributes(IEnumerable decls, string inOut) { - int Count = 0; + int count = 0; - foreach (ShaderDeclInfo DeclInfo in Decls.OrderBy(DeclKeySelector)) + foreach (ShaderDeclInfo declInfo in decls.OrderBy(DeclKeySelector)) { - if (DeclInfo.Index >= 0) + if (declInfo.Index >= 0) { - SB.AppendLine("layout (location = " + DeclInfo.Index + ") " + InOut + " vec4 " + DeclInfo.Name + ";"); + _sb.AppendLine("layout (location = " + declInfo.Index + ") " + inOut + " vec4 " + declInfo.Name + ";"); - Count++; + count++; } } - if (Count > 0) + if (count > 0) { - SB.AppendLine(); + _sb.AppendLine(); } } private void PrintDeclGprs() { - PrintDecls(Decl.Gprs); - PrintDecls(Decl.GprsHalf); + PrintDecls(_decl.Gprs); + PrintDecls(_decl.GprsHalf); } private void PrintDeclPreds() { - PrintDecls(Decl.Preds, "bool"); + PrintDecls(_decl.Preds, "bool"); } private void PrintDeclSsy() { - SB.AppendLine("uint " + GlslDecl.SsyCursorName + " = 0;"); + _sb.AppendLine("uint " + GlslDecl.SsyCursorName + " = 0;"); - SB.AppendLine("uint " + GlslDecl.SsyStackName + "[" + GlslDecl.SsyStackSize + "];" + Environment.NewLine); + _sb.AppendLine("uint " + GlslDecl.SsyStackName + "[" + GlslDecl.SsyStackSize + "];" + Environment.NewLine); } - private void PrintDecls(IReadOnlyDictionary Dict, string CustomType = null, string Suffix = "") + private void PrintDecls(IReadOnlyDictionary dict, string customType = null, string suffix = "") { - foreach (ShaderDeclInfo DeclInfo in Dict.Values.OrderBy(DeclKeySelector)) + foreach (ShaderDeclInfo declInfo in dict.Values.OrderBy(DeclKeySelector)) { - string Name; + string name; - if (CustomType != null) + if (customType != null) { - Name = CustomType + " " + DeclInfo.Name + Suffix + ";"; + name = customType + " " + declInfo.Name + suffix + ";"; } - else if (DeclInfo.Name.Contains(GlslDecl.FragmentOutputName)) + else if (declInfo.Name.Contains(GlslDecl.FragmentOutputName)) { - Name = "layout (location = " + DeclInfo.Index / 4 + ") out vec4 " + DeclInfo.Name + Suffix + ";"; + name = "layout (location = " + declInfo.Index / 4 + ") out vec4 " + declInfo.Name + suffix + ";"; } else { - Name = GetDecl(DeclInfo) + Suffix + ";"; + name = GetDecl(declInfo) + suffix + ";"; } - SB.AppendLine(Name); + _sb.AppendLine(name); } - if (Dict.Count > 0) + if (dict.Count > 0) { - SB.AppendLine(); + _sb.AppendLine(); } } - private int DeclKeySelector(ShaderDeclInfo DeclInfo) + private int DeclKeySelector(ShaderDeclInfo declInfo) { - return DeclInfo.Cbuf << 24 | DeclInfo.Index; + return declInfo.Cbuf << 24 | declInfo.Index; } - private string GetDecl(ShaderDeclInfo DeclInfo) + private string GetDecl(ShaderDeclInfo declInfo) { - if (DeclInfo.Size == 4) + if (declInfo.Size == 4) { - return "vec4 " + DeclInfo.Name; + return "vec4 " + declInfo.Name; } else { - return "float " + DeclInfo.Name; + return "float " + declInfo.Name; } } private void PrintMain() { - SB.AppendLine("void main() {"); + _sb.AppendLine("void main() {"); - foreach (KeyValuePair KV in Decl.InAttributes) + foreach (KeyValuePair kv in _decl.InAttributes) { - if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr)) + if (!_decl.Attributes.TryGetValue(kv.Key, out ShaderDeclInfo attr)) { continue; } - ShaderDeclInfo DeclInfo = KV.Value; + ShaderDeclInfo declInfo = kv.Value; - if (Decl.ShaderType == GalShaderType.Geometry) + if (_decl.ShaderType == GalShaderType.Geometry) { - for (int Vertex = 0; Vertex < MaxVertexInput; Vertex++) + for (int vertex = 0; vertex < MaxVertexInput; vertex++) { - string Dst = Attr.Name + "[" + Vertex + "]"; + string dst = attr.Name + "[" + vertex + "]"; - string Src = "block_in[" + Vertex + "]." + DeclInfo.Name; + string src = "block_in[" + vertex + "]." + declInfo.Name; - SB.AppendLine(IdentationStr + Dst + " = " + Src + ";"); + _sb.AppendLine(IdentationStr + dst + " = " + src + ";"); } } else { - SB.AppendLine(IdentationStr + Attr.Name + " = " + DeclInfo.Name + ";"); + _sb.AppendLine(IdentationStr + attr.Name + " = " + declInfo.Name + ";"); } } - SB.AppendLine(IdentationStr + "uint pc;"); + _sb.AppendLine(IdentationStr + "uint pc;"); - if (BlocksB != null) + if (_blocksB != null) { - PrintProgram(Blocks, GlslDecl.BasicBlockAName); - PrintProgram(BlocksB, GlslDecl.BasicBlockBName); + PrintProgram(_blocks, GlslDecl.BasicBlockAName); + PrintProgram(_blocksB, GlslDecl.BasicBlockBName); } else { - PrintProgram(Blocks, GlslDecl.BasicBlockName); + PrintProgram(_blocks, GlslDecl.BasicBlockName); } - if (Decl.ShaderType != GalShaderType.Geometry) + if (_decl.ShaderType != GalShaderType.Geometry) { PrintAttrToOutput(); } - if (Decl.ShaderType == GalShaderType.Fragment) + if (_decl.ShaderType == GalShaderType.Fragment) { - if (Header.OmapDepth) + if (_header.OmapDepth) { - SB.AppendLine(IdentationStr + "gl_FragDepth = " + GlslDecl.GetGprName(Header.DepthRegister) + ";"); + _sb.AppendLine(IdentationStr + "gl_FragDepth = " + GlslDecl.GetGprName(_header.DepthRegister) + ";"); } - int GprIndex = 0; + int gprIndex = 0; - for (int Attachment = 0; Attachment < 8; Attachment++) + for (int attachment = 0; attachment < 8; attachment++) { - string Output = GlslDecl.FragmentOutputName + Attachment; + string output = GlslDecl.FragmentOutputName + attachment; - OmapTarget Target = Header.OmapTargets[Attachment]; + OmapTarget target = _header.OmapTargets[attachment]; - for (int Component = 0; Component < 4; Component++) + for (int component = 0; component < 4; component++) { - if (Target.ComponentEnabled(Component)) + if (target.ComponentEnabled(component)) { - SB.AppendLine(IdentationStr + Output + "[" + Component + "] = " + GlslDecl.GetGprName(GprIndex) + ";"); + _sb.AppendLine(IdentationStr + output + "[" + component + "] = " + GlslDecl.GetGprName(gprIndex) + ";"); - GprIndex++; + gprIndex++; } } } } - SB.AppendLine("}"); + _sb.AppendLine("}"); } - private void PrintProgram(ShaderIrBlock[] Blocks, string Name) + private void PrintProgram(ShaderIrBlock[] blocks, string name) { - const string Ident1 = IdentationStr; - const string Ident2 = Ident1 + IdentationStr; - const string Ident3 = Ident2 + IdentationStr; - const string Ident4 = Ident3 + IdentationStr; + const string ident1 = IdentationStr; + const string ident2 = ident1 + IdentationStr; + const string ident3 = ident2 + IdentationStr; + const string ident4 = ident3 + IdentationStr; - SB.AppendLine(Ident1 + "pc = " + GetBlockPosition(Blocks[0]) + ";"); - SB.AppendLine(Ident1 + "do {"); - SB.AppendLine(Ident2 + "switch (pc) {"); + _sb.AppendLine(ident1 + "pc = " + GetBlockPosition(blocks[0]) + ";"); + _sb.AppendLine(ident1 + "do {"); + _sb.AppendLine(ident2 + "switch (pc) {"); - foreach (ShaderIrBlock Block in Blocks) + foreach (ShaderIrBlock block in blocks) { - string FunctionName = Block.Position.ToString("x8"); + string functionName = block.Position.ToString("x8"); - SB.AppendLine(Ident3 + "case 0x" + FunctionName + ": pc = " + Name + "_" + FunctionName + "(); break;"); + _sb.AppendLine(ident3 + "case 0x" + functionName + ": pc = " + name + "_" + functionName + "(); break;"); } - SB.AppendLine(Ident3 + "default:"); - SB.AppendLine(Ident4 + "pc = 0;"); - SB.AppendLine(Ident4 + "break;"); + _sb.AppendLine(ident3 + "default:"); + _sb.AppendLine(ident4 + "pc = 0;"); + _sb.AppendLine(ident4 + "break;"); - SB.AppendLine(Ident2 + "}"); - SB.AppendLine(Ident1 + "} while (pc != 0);"); + _sb.AppendLine(ident2 + "}"); + _sb.AppendLine(ident1 + "} while (pc != 0);"); } - private void PrintAttrToOutput(string Identation = IdentationStr) + private void PrintAttrToOutput(string identation = IdentationStr) { - foreach (KeyValuePair KV in Decl.OutAttributes) + foreach (KeyValuePair kv in _decl.OutAttributes) { - if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr)) + if (!_decl.Attributes.TryGetValue(kv.Key, out ShaderDeclInfo attr)) { continue; } - ShaderDeclInfo DeclInfo = KV.Value; + ShaderDeclInfo declInfo = kv.Value; - string Name = Attr.Name; + string name = attr.Name; - if (Decl.ShaderType == GalShaderType.Geometry) + if (_decl.ShaderType == GalShaderType.Geometry) { - Name += "[0]"; + name += "[0]"; } - SB.AppendLine(Identation + DeclInfo.Name + " = " + Name + ";"); + _sb.AppendLine(identation + declInfo.Name + " = " + name + ";"); } - if (Decl.ShaderType == GalShaderType.Vertex) + if (_decl.ShaderType == GalShaderType.Vertex) { - SB.AppendLine(Identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";"); + _sb.AppendLine(identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";"); } - if (Decl.ShaderType != GalShaderType.Fragment) + if (_decl.ShaderType != GalShaderType.Fragment) { - SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + " = gl_Position;"); - SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + ".w = 1;"); + _sb.AppendLine(identation + GlslDecl.PositionOutAttrName + " = gl_Position;"); + _sb.AppendLine(identation + GlslDecl.PositionOutAttrName + ".w = 1;"); } } - private void PrintBlockScope(ShaderIrBlock[] Blocks, string Name) + private void PrintBlockScope(ShaderIrBlock[] blocks, string name) { - foreach (ShaderIrBlock Block in Blocks) + foreach (ShaderIrBlock block in blocks) { - SB.AppendLine("uint " + Name + "_" + Block.Position.ToString("x8") + "() {"); + _sb.AppendLine("uint " + name + "_" + block.Position.ToString("x8") + "() {"); - PrintNodes(Block, Block.GetNodes()); + PrintNodes(block, block.GetNodes()); - SB.AppendLine("}" + Environment.NewLine); + _sb.AppendLine("}" + Environment.NewLine); } } - private void PrintNodes(ShaderIrBlock Block, ShaderIrNode[] Nodes) + private void PrintNodes(ShaderIrBlock block, ShaderIrNode[] nodes) { - foreach (ShaderIrNode Node in Nodes) + foreach (ShaderIrNode node in nodes) { - PrintNode(Block, Node, IdentationStr); + PrintNode(block, node, IdentationStr); } - if (Nodes.Length == 0) + if (nodes.Length == 0) { - SB.AppendLine(IdentationStr + "return 0u;"); + _sb.AppendLine(IdentationStr + "return 0u;"); return; } - ShaderIrNode Last = Nodes[Nodes.Length - 1]; + ShaderIrNode last = nodes[nodes.Length - 1]; - bool UnconditionalFlowChange = false; + bool unconditionalFlowChange = false; - if (Last is ShaderIrOp Op) + if (last is ShaderIrOp op) { - switch (Op.Inst) + switch (op.Inst) { case ShaderIrInst.Bra: case ShaderIrInst.Exit: case ShaderIrInst.Sync: - UnconditionalFlowChange = true; + unconditionalFlowChange = true; break; } } - if (!UnconditionalFlowChange) + if (!unconditionalFlowChange) { - if (Block.Next != null) + if (block.Next != null) { - SB.AppendLine(IdentationStr + "return " + GetBlockPosition(Block.Next) + ";"); + _sb.AppendLine(IdentationStr + "return " + GetBlockPosition(block.Next) + ";"); } else { - SB.AppendLine(IdentationStr + "return 0u;"); + _sb.AppendLine(IdentationStr + "return 0u;"); } } } - private void PrintNode(ShaderIrBlock Block, ShaderIrNode Node, string Identation) + private void PrintNode(ShaderIrBlock block, ShaderIrNode node, string identation) { - if (Node is ShaderIrCond Cond) + if (node is ShaderIrCond cond) { - string IfExpr = GetSrcExpr(Cond.Pred, true); + string ifExpr = GetSrcExpr(cond.Pred, true); - if (Cond.Not) + if (cond.Not) { - IfExpr = "!(" + IfExpr + ")"; + ifExpr = "!(" + ifExpr + ")"; } - SB.AppendLine(Identation + "if (" + IfExpr + ") {"); + _sb.AppendLine(identation + "if (" + ifExpr + ") {"); - PrintNode(Block, Cond.Child, Identation + IdentationStr); + PrintNode(block, cond.Child, identation + IdentationStr); - SB.AppendLine(Identation + "}"); + _sb.AppendLine(identation + "}"); } - else if (Node is ShaderIrAsg Asg) + else if (node is ShaderIrAsg asg) { - if (IsValidOutOper(Asg.Dst)) + if (IsValidOutOper(asg.Dst)) { - string Expr = GetSrcExpr(Asg.Src, true); + string expr = GetSrcExpr(asg.Src, true); - Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr); + expr = GetExprWithCast(asg.Dst, asg.Src, expr); - SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";"); + _sb.AppendLine(identation + GetDstOperName(asg.Dst) + " = " + expr + ";"); } } - else if (Node is ShaderIrOp Op) + else if (node is ShaderIrOp op) { - switch (Op.Inst) + switch (op.Inst) { case ShaderIrInst.Bra: { - SB.AppendLine(Identation + "return " + GetBlockPosition(Block.Branch) + ";"); + _sb.AppendLine(identation + "return " + GetBlockPosition(block.Branch) + ";"); break; } case ShaderIrInst.Emit: { - PrintAttrToOutput(Identation); + PrintAttrToOutput(identation); - SB.AppendLine(Identation + "EmitVertex();"); + _sb.AppendLine(identation + "EmitVertex();"); break; } case ShaderIrInst.Ssy: { - string StackIndex = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]"; + string stackIndex = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]"; - int TargetPosition = (Op.OperandA as ShaderIrOperImm).Value; + int targetPosition = (op.OperandA as ShaderIrOperImm).Value; - string Target = "0x" + TargetPosition.ToString("x8") + "u"; + string target = "0x" + targetPosition.ToString("x8") + "u"; - SB.AppendLine(Identation + StackIndex + " = " + Target + ";"); + _sb.AppendLine(identation + stackIndex + " = " + target + ";"); - SB.AppendLine(Identation + GlslDecl.SsyCursorName + "++;"); + _sb.AppendLine(identation + GlslDecl.SsyCursorName + "++;"); break; } case ShaderIrInst.Sync: { - SB.AppendLine(Identation + GlslDecl.SsyCursorName + "--;"); + _sb.AppendLine(identation + GlslDecl.SsyCursorName + "--;"); - string Target = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]"; + string target = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]"; - SB.AppendLine(Identation + "return " + Target + ";"); + _sb.AppendLine(identation + "return " + target + ";"); break; } default: - SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";"); + _sb.AppendLine(identation + GetSrcExpr(op, true) + ";"); break; } } - else if (Node is ShaderIrCmnt Cmnt) + else if (node is ShaderIrCmnt cmnt) { - SB.AppendLine(Identation + "// " + Cmnt.Comment); + _sb.AppendLine(identation + "// " + cmnt.Comment); } else { @@ -767,13 +767,13 @@ namespace Ryujinx.Graphics.Gal.Shader } } - private bool IsValidOutOper(ShaderIrNode Node) + private bool IsValidOutOper(ShaderIrNode node) { - if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst) + if (node is ShaderIrOperGpr gpr && gpr.IsConst) { return false; } - else if (Node is ShaderIrOperPred Pred && Pred.IsConst) + else if (node is ShaderIrOperPred pred && pred.IsConst) { return false; } @@ -781,61 +781,61 @@ namespace Ryujinx.Graphics.Gal.Shader return true; } - private string GetDstOperName(ShaderIrNode Node) + private string GetDstOperName(ShaderIrNode node) { - if (Node is ShaderIrOperAbuf Abuf) + if (node is ShaderIrOperAbuf abuf) { - return GetOutAbufName(Abuf); + return GetOutAbufName(abuf); } - else if (Node is ShaderIrOperGpr Gpr) + else if (node is ShaderIrOperGpr gpr) { - return GetName(Gpr); + return GetName(gpr); } - else if (Node is ShaderIrOperPred Pred) + else if (node is ShaderIrOperPred pred) { - return GetName(Pred); + return GetName(pred); } - throw new ArgumentException(nameof(Node)); + throw new ArgumentException(nameof(node)); } - private string GetSrcExpr(ShaderIrNode Node, bool Entry = false) + private string GetSrcExpr(ShaderIrNode node, bool entry = false) { - switch (Node) + switch (node) { - case ShaderIrOperAbuf Abuf: return GetName (Abuf); - case ShaderIrOperCbuf Cbuf: return GetName (Cbuf); - case ShaderIrOperGpr Gpr: return GetName (Gpr); - case ShaderIrOperImm Imm: return GetValue(Imm); - case ShaderIrOperImmf Immf: return GetValue(Immf); - case ShaderIrOperPred Pred: return GetName (Pred); + case ShaderIrOperAbuf abuf: return GetName (abuf); + case ShaderIrOperCbuf cbuf: return GetName (cbuf); + case ShaderIrOperGpr gpr: return GetName (gpr); + case ShaderIrOperImm imm: return GetValue(imm); + case ShaderIrOperImmf immf: return GetValue(immf); + case ShaderIrOperPred pred: return GetName (pred); - case ShaderIrOp Op: - string Expr; + case ShaderIrOp op: + string expr; - if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr)) + if (_instsExpr.TryGetValue(op.Inst, out GetInstExpr getExpr)) { - Expr = GetExpr(Op); + expr = getExpr(op); } else { - throw new NotImplementedException(Op.Inst.ToString()); + throw new NotImplementedException(op.Inst.ToString()); } - if (!Entry && NeedsParentheses(Op)) + if (!entry && NeedsParentheses(op)) { - Expr = "(" + Expr + ")"; + expr = "(" + expr + ")"; } - return Expr; + return expr; - default: throw new ArgumentException(nameof(Node)); + default: throw new ArgumentException(nameof(node)); } } - private static bool NeedsParentheses(ShaderIrOp Op) + private static bool NeedsParentheses(ShaderIrOp op) { - switch (Op.Inst) + switch (op.Inst) { case ShaderIrInst.Ipa: case ShaderIrInst.Texq: @@ -848,63 +848,63 @@ namespace Ryujinx.Graphics.Gal.Shader return true; } - private string GetName(ShaderIrOperCbuf Cbuf) + private string GetName(ShaderIrOperCbuf cbuf) { - if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo)) + if (!_decl.Uniforms.TryGetValue(cbuf.Index, out ShaderDeclInfo declInfo)) { throw new InvalidOperationException(); } - if (Cbuf.Offs != null) + if (cbuf.Offs != null) { - string Offset = "floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ")"; + string offset = "floatBitsToInt(" + GetSrcExpr(cbuf.Offs) + ")"; - string Index = "(" + Cbuf.Pos * 4 + " + " + Offset + ")"; + string index = "(" + cbuf.Pos * 4 + " + " + offset + ")"; - return $"{DeclInfo.Name}_data[{Index} / 16][({Index} / 4) % 4]"; + return $"{declInfo.Name}_data[{index} / 16][({index} / 4) % 4]"; } else { - return $"{DeclInfo.Name}_data[{Cbuf.Pos / 4}][{Cbuf.Pos % 4}]"; + return $"{declInfo.Name}_data[{cbuf.Pos / 4}][{cbuf.Pos % 4}]"; } } - private string GetOutAbufName(ShaderIrOperAbuf Abuf) + private string GetOutAbufName(ShaderIrOperAbuf abuf) { - if (Decl.ShaderType == GalShaderType.Geometry) + if (_decl.ShaderType == GalShaderType.Geometry) { - switch (Abuf.Offs) + switch (abuf.Offs) { case GlslDecl.LayerAttr: return "gl_Layer"; } } - return GetAttrTempName(Abuf); + return GetAttrTempName(abuf); } - private string GetName(ShaderIrOperAbuf Abuf) + private string GetName(ShaderIrOperAbuf abuf) { //Handle special scalar read-only attributes here. - if (Decl.ShaderType == GalShaderType.Vertex) + if (_decl.ShaderType == GalShaderType.Vertex) { - switch (Abuf.Offs) + switch (abuf.Offs) { case GlslDecl.VertexIdAttr: return "gl_VertexID"; case GlslDecl.InstanceIdAttr: return GlslDecl.InstanceUniformName; } } - else if (Decl.ShaderType == GalShaderType.TessEvaluation) + else if (_decl.ShaderType == GalShaderType.TessEvaluation) { - switch (Abuf.Offs) + switch (abuf.Offs) { case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x"; case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y"; case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z"; } } - else if (Decl.ShaderType == GalShaderType.Fragment) + else if (_decl.ShaderType == GalShaderType.Fragment) { - switch (Abuf.Offs) + switch (abuf.Offs) { case GlslDecl.PointCoordAttrX: return "gl_PointCoord.x"; case GlslDecl.PointCoordAttrY: return "gl_PointCoord.y"; @@ -912,65 +912,65 @@ namespace Ryujinx.Graphics.Gal.Shader } } - return GetAttrTempName(Abuf); + return GetAttrTempName(abuf); } - private string GetAttrTempName(ShaderIrOperAbuf Abuf) + private string GetAttrTempName(ShaderIrOperAbuf abuf) { - int Index = Abuf.Offs >> 4; - int Elem = (Abuf.Offs >> 2) & 3; + int index = abuf.Offs >> 4; + int elem = (abuf.Offs >> 2) & 3; - string Swizzle = "." + GetAttrSwizzle(Elem); + string swizzle = "." + GetAttrSwizzle(elem); - if (!Decl.Attributes.TryGetValue(Index, out ShaderDeclInfo DeclInfo)) + if (!_decl.Attributes.TryGetValue(index, out ShaderDeclInfo declInfo)) { //Handle special vec4 attributes here //(for example, index 7 is always gl_Position). - if (Index == GlslDecl.GlPositionVec4Index) + if (index == GlslDecl.GlPositionVec4Index) { - string Name = - Decl.ShaderType != GalShaderType.Vertex && - Decl.ShaderType != GalShaderType.Geometry ? GlslDecl.PositionOutAttrName : "gl_Position"; + string name = + _decl.ShaderType != GalShaderType.Vertex && + _decl.ShaderType != GalShaderType.Geometry ? GlslDecl.PositionOutAttrName : "gl_Position"; - return Name + Swizzle; + return name + swizzle; } - else if (Abuf.Offs == GlslDecl.PointSizeAttr) + else if (abuf.Offs == GlslDecl.PointSizeAttr) { return "gl_PointSize"; } } - if (DeclInfo.Index >= 32) + if (declInfo.Index >= 32) { - throw new InvalidOperationException($"Shader attribute offset {Abuf.Offs} is invalid."); + throw new InvalidOperationException($"Shader attribute offset {abuf.Offs} is invalid."); } - if (Decl.ShaderType == GalShaderType.Geometry) + if (_decl.ShaderType == GalShaderType.Geometry) { - string Vertex = "floatBitsToInt(" + GetSrcExpr(Abuf.Vertex) + ")"; + string vertex = "floatBitsToInt(" + GetSrcExpr(abuf.Vertex) + ")"; - return DeclInfo.Name + "[" + Vertex + "]" + Swizzle; + return declInfo.Name + "[" + vertex + "]" + swizzle; } else { - return DeclInfo.Name + Swizzle; + return declInfo.Name + swizzle; } } - private string GetName(ShaderIrOperGpr Gpr) + private string GetName(ShaderIrOperGpr gpr) { - if (Gpr.IsConst) + if (gpr.IsConst) { return "0"; } - if (Gpr.RegisterSize == ShaderRegisterSize.Single) + if (gpr.RegisterSize == ShaderRegisterSize.Single) { - return GetNameWithSwizzle(Decl.Gprs, Gpr.Index); + return GetNameWithSwizzle(_decl.Gprs, gpr.Index); } - else if (Gpr.RegisterSize == ShaderRegisterSize.Half) + else if (gpr.RegisterSize == ShaderRegisterSize.Half) { - return GetNameWithSwizzle(Decl.GprsHalf, (Gpr.Index << 1) | Gpr.HalfPart); + return GetNameWithSwizzle(_decl.GprsHalf, (gpr.Index << 1) | gpr.HalfPart); } else /* if (Gpr.RegisterSize == ShaderRegisterSize.Double) */ { @@ -978,163 +978,163 @@ namespace Ryujinx.Graphics.Gal.Shader } } - private string GetValue(ShaderIrOperImm Imm) + private string GetValue(ShaderIrOperImm imm) { //Only use hex is the value is too big and would likely be hard to read as int. - if (Imm.Value > 0xfff || - Imm.Value < -0xfff) + if (imm.Value > 0xfff || + imm.Value < -0xfff) { - return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture); + return "0x" + imm.Value.ToString("x8", CultureInfo.InvariantCulture); } else { - return GetIntConst(Imm.Value); + return GetIntConst(imm.Value); } } - private string GetValue(ShaderIrOperImmf Immf) + private string GetValue(ShaderIrOperImmf immf) { - return GetFloatConst(Immf.Value); + return GetFloatConst(immf.Value); } - private string GetName(ShaderIrOperPred Pred) + private string GetName(ShaderIrOperPred pred) { - return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index); + return pred.IsConst ? "true" : GetNameWithSwizzle(_decl.Preds, pred.Index); } - private string GetNameWithSwizzle(IReadOnlyDictionary Dict, int Index) + private string GetNameWithSwizzle(IReadOnlyDictionary dict, int index) { - int VecIndex = Index & ~3; + int vecIndex = index & ~3; - if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo)) + if (dict.TryGetValue(vecIndex, out ShaderDeclInfo declInfo)) { - if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size) + if (declInfo.Size > 1 && index < vecIndex + declInfo.Size) { - return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3); + return declInfo.Name + "." + GetAttrSwizzle(index & 3); } } - if (!Dict.TryGetValue(Index, out DeclInfo)) + if (!dict.TryGetValue(index, out declInfo)) { throw new InvalidOperationException(); } - return DeclInfo.Name; + return declInfo.Name; } - private string GetAttrSwizzle(int Elem) + private string GetAttrSwizzle(int elem) { - return "xyzw".Substring(Elem, 1); + return "xyzw".Substring(elem, 1); } - private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs"); + private string GetAbsExpr(ShaderIrOp op) => GetUnaryCall(op, "abs"); - private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+"); + private string GetAddExpr(ShaderIrOp op) => GetBinaryExpr(op, "+"); - private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&"); + private string GetAndExpr(ShaderIrOp op) => GetBinaryExpr(op, "&"); - private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>"); + private string GetAsrExpr(ShaderIrOp op) => GetBinaryExpr(op, ">>"); - private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&"); + private string GetBandExpr(ShaderIrOp op) => GetBinaryExpr(op, "&&"); - private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!"); + private string GetBnotExpr(ShaderIrOp op) => GetUnaryExpr(op, "!"); - private string GetBorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "||"); + private string GetBorExpr(ShaderIrOp op) => GetBinaryExpr(op, "||"); - private string GetBxorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^^"); + private string GetBxorExpr(ShaderIrOp op) => GetBinaryExpr(op, "^^"); - private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil"); + private string GetCeilExpr(ShaderIrOp op) => GetUnaryCall(op, "ceil"); - private string GetClampsExpr(ShaderIrOp Op) + private string GetClampsExpr(ShaderIrOp op) { - return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " + - GetOperExpr(Op, Op.OperandB) + ", " + - GetOperExpr(Op, Op.OperandC) + ")"; + return "clamp(" + GetOperExpr(op, op.OperandA) + ", " + + GetOperExpr(op, op.OperandB) + ", " + + GetOperExpr(op, op.OperandC) + ")"; } - private string GetClampuExpr(ShaderIrOp Op) + private string GetClampuExpr(ShaderIrOp op) { - return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " + - "uint(" + GetOperExpr(Op, Op.OperandB) + "), " + - "uint(" + GetOperExpr(Op, Op.OperandC) + ")))"; + return "int(clamp(uint(" + GetOperExpr(op, op.OperandA) + "), " + + "uint(" + GetOperExpr(op, op.OperandB) + "), " + + "uint(" + GetOperExpr(op, op.OperandC) + ")))"; } - private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "=="); + private string GetCeqExpr(ShaderIrOp op) => GetBinaryExpr(op, "=="); - private string GetCequExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "=="); + private string GetCequExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, "=="); - private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">="); + private string GetCgeExpr(ShaderIrOp op) => GetBinaryExpr(op, ">="); - private string GetCgeuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">="); + private string GetCgeuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, ">="); - private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">"); + private string GetCgtExpr(ShaderIrOp op) => GetBinaryExpr(op, ">"); - private string GetCgtuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">"); + private string GetCgtuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, ">"); - private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<="); + private string GetCleExpr(ShaderIrOp op) => GetBinaryExpr(op, "<="); - private string GetCleuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<="); + private string GetCleuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, "<="); - private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<"); + private string GetCltExpr(ShaderIrOp op) => GetBinaryExpr(op, "<"); - private string GetCltuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<"); + private string GetCltuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, "<"); - private string GetCnanExpr(ShaderIrOp Op) => GetUnaryCall(Op, "isnan"); + private string GetCnanExpr(ShaderIrOp op) => GetUnaryCall(op, "isnan"); - private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!="); + private string GetCneExpr(ShaderIrOp op) => GetBinaryExpr(op, "!="); - private string GetCutExpr(ShaderIrOp Op) => "EndPrimitive()"; + private string GetCutExpr(ShaderIrOp op) => "EndPrimitive()"; - private string GetCneuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "!="); + private string GetCneuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, "!="); - private string GetCnumExpr(ShaderIrOp Op) => GetUnaryCall(Op, "!isnan"); + private string GetCnumExpr(ShaderIrOp op) => GetUnaryCall(op, "!isnan"); - private string GetExitExpr(ShaderIrOp Op) => "return 0u"; + private string GetExitExpr(ShaderIrOp op) => "return 0u"; - private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos"); + private string GetFcosExpr(ShaderIrOp op) => GetUnaryCall(op, "cos"); - private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2"); + private string GetFex2Expr(ShaderIrOp op) => GetUnaryCall(op, "exp2"); - private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+"); + private string GetFfmaExpr(ShaderIrOp op) => GetTernaryExpr(op, "*", "+"); - private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp"); + private string GetFclampExpr(ShaderIrOp op) => GetTernaryCall(op, "clamp"); - private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2"); + private string GetFlg2Expr(ShaderIrOp op) => GetUnaryCall(op, "log2"); - private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor"); + private string GetFloorExpr(ShaderIrOp op) => GetUnaryCall(op, "floor"); - private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / "); + private string GetFrcpExpr(ShaderIrOp op) => GetUnaryExpr(op, "1 / "); - private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt"); + private string GetFrsqExpr(ShaderIrOp op) => GetUnaryCall(op, "inversesqrt"); - private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin"); + private string GetFsinExpr(ShaderIrOp op) => GetUnaryCall(op, "sin"); - private string GetFsqrtExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sqrt"); + private string GetFsqrtExpr(ShaderIrOp op) => GetUnaryCall(op, "sqrt"); - private string GetFtosExpr(ShaderIrOp Op) + private string GetFtosExpr(ShaderIrOp op) { - return "int(" + GetOperExpr(Op, Op.OperandA) + ")"; + return "int(" + GetOperExpr(op, op.OperandA) + ")"; } - private string GetFtouExpr(ShaderIrOp Op) + private string GetFtouExpr(ShaderIrOp op) { - return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))"; + return "int(uint(" + GetOperExpr(op, op.OperandA) + "))"; } - private string GetIpaExpr(ShaderIrOp Op) + private string GetIpaExpr(ShaderIrOp op) { - ShaderIrMetaIpa Meta = (ShaderIrMetaIpa)Op.MetaData; + ShaderIrMetaIpa meta = (ShaderIrMetaIpa)op.MetaData; - ShaderIrOperAbuf Abuf = (ShaderIrOperAbuf)Op.OperandA; + ShaderIrOperAbuf abuf = (ShaderIrOperAbuf)op.OperandA; - if (Meta.Mode == ShaderIpaMode.Pass) + if (meta.Mode == ShaderIpaMode.Pass) { - int Index = Abuf.Offs >> 4; - int Elem = (Abuf.Offs >> 2) & 3; + int index = abuf.Offs >> 4; + int elem = (abuf.Offs >> 2) & 3; - if (Decl.ShaderType == GalShaderType.Fragment && Index == GlslDecl.GlPositionVec4Index) + if (_decl.ShaderType == GalShaderType.Fragment && index == GlslDecl.GlPositionVec4Index) { - switch (Elem) + switch (elem) { case 0: return "gl_FragCoord.x"; case 1: return "gl_FragCoord.y"; @@ -1144,433 +1144,433 @@ namespace Ryujinx.Graphics.Gal.Shader } } - return GetSrcExpr(Op.OperandA); + return GetSrcExpr(op.OperandA); } - private string GetKilExpr(ShaderIrOp Op) => "discard"; + private string GetKilExpr(ShaderIrOp op) => "discard"; - private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<"); - private string GetLsrExpr(ShaderIrOp Op) + private string GetLslExpr(ShaderIrOp op) => GetBinaryExpr(op, "<<"); + private string GetLsrExpr(ShaderIrOp op) { - return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " + - GetOperExpr(Op, Op.OperandB) + ")"; + return "int(uint(" + GetOperExpr(op, op.OperandA) + ") >> " + + GetOperExpr(op, op.OperandB) + ")"; } - private string GetMaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max"); - private string GetMinExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min"); + private string GetMaxExpr(ShaderIrOp op) => GetBinaryCall(op, "max"); + private string GetMinExpr(ShaderIrOp op) => GetBinaryCall(op, "min"); - private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*"); + private string GetMulExpr(ShaderIrOp op) => GetBinaryExpr(op, "*"); - private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-"); + private string GetNegExpr(ShaderIrOp op) => GetUnaryExpr(op, "-"); - private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~"); + private string GetNotExpr(ShaderIrOp op) => GetUnaryExpr(op, "~"); - private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|"); + private string GetOrExpr(ShaderIrOp op) => GetBinaryExpr(op, "|"); - private string GetStofExpr(ShaderIrOp Op) + private string GetStofExpr(ShaderIrOp op) { - return "float(" + GetOperExpr(Op, Op.OperandA) + ")"; + return "float(" + GetOperExpr(op, op.OperandA) + ")"; } - private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-"); + private string GetSubExpr(ShaderIrOp op) => GetBinaryExpr(op, "-"); - private string GetTexbExpr(ShaderIrOp Op) + private string GetTexbExpr(ShaderIrOp op) { - ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData; + ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - if (!Decl.CbTextures.TryGetValue(Op, out ShaderDeclInfo DeclInfo)) + if (!_decl.CbTextures.TryGetValue(op, out ShaderDeclInfo declInfo)) { throw new InvalidOperationException(); } - string Coords = GetTexSamplerCoords(Op); + string coords = GetTexSamplerCoords(op); - string Ch = "rgba".Substring(Meta.Elem, 1); + string ch = "rgba".Substring(meta.Elem, 1); - return GetTextureOperation(Op, DeclInfo.Name, Coords, Ch); + return GetTextureOperation(op, declInfo.Name, coords, ch); } - private string GetTexqExpr(ShaderIrOp Op) + private string GetTexqExpr(ShaderIrOp op) { - ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData; + ShaderIrMetaTexq meta = (ShaderIrMetaTexq)op.MetaData; - string Ch = "xyzw".Substring(Meta.Elem, 1); + string ch = "xyzw".Substring(meta.Elem, 1); - if (Meta.Info == ShaderTexqInfo.Dimension) + if (meta.Info == ShaderTexqInfo.Dimension) { - string Sampler = GetTexSamplerName(Op); + string sampler = GetTexSamplerName(op); - string Lod = GetOperExpr(Op, Op.OperandA); //??? + string lod = GetOperExpr(op, op.OperandA); //??? - return "textureSize(" + Sampler + ", " + Lod + ")." + Ch; + return "textureSize(" + sampler + ", " + lod + ")." + ch; } else { - throw new NotImplementedException(Meta.Info.ToString()); + throw new NotImplementedException(meta.Info.ToString()); } } - private string GetTexsExpr(ShaderIrOp Op) + private string GetTexsExpr(ShaderIrOp op) { - ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData; + ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - string Sampler = GetTexSamplerName(Op); + string sampler = GetTexSamplerName(op); - string Coords = GetTexSamplerCoords(Op); + string coords = GetTexSamplerCoords(op); - string Ch = "rgba".Substring(Meta.Elem, 1); + string ch = "rgba".Substring(meta.Elem, 1); - return GetTextureOperation(Op, Sampler, Coords, Ch); + return GetTextureOperation(op, sampler, coords, ch); } - private string GetTld4Expr(ShaderIrOp Op) + private string GetTld4Expr(ShaderIrOp op) { - ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData; + ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - string Sampler = GetTexSamplerName(Op); + string sampler = GetTexSamplerName(op); - string Coords = GetTexSamplerCoords(Op); + string coords = GetTexSamplerCoords(op); - string Ch = "rgba".Substring(Meta.Elem, 1); + string ch = "rgba".Substring(meta.Elem, 1); - return GetTextureGatherOperation(Op, Sampler, Coords, Ch); + return GetTextureGatherOperation(op, sampler, coords, ch); } // TODO: support AOFFI on non nvidia drivers - private string GetTxlfExpr(ShaderIrOp Op) + private string GetTxlfExpr(ShaderIrOp op) { // TODO: Support all suffixes - ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData; + ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - TextureInstructionSuffix Suffix = Meta.TextureInstructionSuffix; + TextureInstructionSuffix suffix = meta.TextureInstructionSuffix; - string Sampler = GetTexSamplerName(Op); + string sampler = GetTexSamplerName(op); - string Coords = GetITexSamplerCoords(Op); + string coords = GetITexSamplerCoords(op); - string Ch = "rgba".Substring(Meta.Elem, 1); + string ch = "rgba".Substring(meta.Elem, 1); - string Lod = "0"; + string lod = "0"; - if (Meta.LevelOfDetail != null) + if (meta.LevelOfDetail != null) { - Lod = GetOperExpr(Op, Meta.LevelOfDetail); + lod = GetOperExpr(op, meta.LevelOfDetail); } - if ((Suffix & TextureInstructionSuffix.AOffI) != 0 && IsNvidiaDriver) + if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver) { - string Offset = GetTextureOffset(Meta, GetOperExpr(Op, Meta.Offset)); - return "texelFetchOffset(" + Sampler + ", " + Coords + ", " + Lod + ", " + Offset + ")." + Ch; + string offset = GetTextureOffset(meta, GetOperExpr(op, meta.Offset)); + return "texelFetchOffset(" + sampler + ", " + coords + ", " + lod + ", " + offset + ")." + ch; } - return "texelFetch(" + Sampler + ", " + Coords + ", " + Lod + ")." + Ch; + return "texelFetch(" + sampler + ", " + coords + ", " + lod + ")." + ch; } - private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc"); + private string GetTruncExpr(ShaderIrOp op) => GetUnaryCall(op, "trunc"); - private string GetUtofExpr(ShaderIrOp Op) + private string GetUtofExpr(ShaderIrOp op) { - return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))"; + return "float(uint(" + GetOperExpr(op, op.OperandA) + "))"; } - private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^"); + private string GetXorExpr(ShaderIrOp op) => GetBinaryExpr(op, "^"); - private string GetUnaryCall(ShaderIrOp Op, string FuncName) + private string GetUnaryCall(ShaderIrOp op, string funcName) { - return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")"; + return funcName + "(" + GetOperExpr(op, op.OperandA) + ")"; } - private string GetBinaryCall(ShaderIrOp Op, string FuncName) + private string GetBinaryCall(ShaderIrOp op, string funcName) { - return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " + - GetOperExpr(Op, Op.OperandB) + ")"; + return funcName + "(" + GetOperExpr(op, op.OperandA) + ", " + + GetOperExpr(op, op.OperandB) + ")"; } - private string GetTernaryCall(ShaderIrOp Op, string FuncName) + private string GetTernaryCall(ShaderIrOp op, string funcName) { - return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " + - GetOperExpr(Op, Op.OperandB) + ", " + - GetOperExpr(Op, Op.OperandC) + ")"; + return funcName + "(" + GetOperExpr(op, op.OperandA) + ", " + + GetOperExpr(op, op.OperandB) + ", " + + GetOperExpr(op, op.OperandC) + ")"; } - private string GetUnaryExpr(ShaderIrOp Op, string Opr) + private string GetUnaryExpr(ShaderIrOp op, string opr) { - return Opr + GetOperExpr(Op, Op.OperandA); + return opr + GetOperExpr(op, op.OperandA); } - private string GetBinaryExpr(ShaderIrOp Op, string Opr) + private string GetBinaryExpr(ShaderIrOp op, string opr) { - return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " + - GetOperExpr(Op, Op.OperandB); + return GetOperExpr(op, op.OperandA) + " " + opr + " " + + GetOperExpr(op, op.OperandB); } - private string GetBinaryExprWithNaN(ShaderIrOp Op, string Opr) + private string GetBinaryExprWithNaN(ShaderIrOp op, string opr) { - string A = GetOperExpr(Op, Op.OperandA); - string B = GetOperExpr(Op, Op.OperandB); + string a = GetOperExpr(op, op.OperandA); + string b = GetOperExpr(op, op.OperandB); - string NaNCheck = - " || isnan(" + A + ")" + - " || isnan(" + B + ")"; + string nanCheck = + " || isnan(" + a + ")" + + " || isnan(" + b + ")"; - return A + " " + Opr + " " + B + NaNCheck; + return a + " " + opr + " " + b + nanCheck; } - private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2) + private string GetTernaryExpr(ShaderIrOp op, string opr1, string opr2) { - return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " + - GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " + - GetOperExpr(Op, Op.OperandC); + return GetOperExpr(op, op.OperandA) + " " + opr1 + " " + + GetOperExpr(op, op.OperandB) + " " + opr2 + " " + + GetOperExpr(op, op.OperandC); } - private string GetTexSamplerName(ShaderIrOp Op) + private string GetTexSamplerName(ShaderIrOp op) { - ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC; + ShaderIrOperImm node = (ShaderIrOperImm)op.OperandC; - int Handle = ((ShaderIrOperImm)Op.OperandC).Value; + int handle = ((ShaderIrOperImm)op.OperandC).Value; - if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo)) + if (!_decl.Textures.TryGetValue(handle, out ShaderDeclInfo declInfo)) { throw new InvalidOperationException(); } - return DeclInfo.Name; + return declInfo.Name; } - private string GetTexSamplerCoords(ShaderIrOp Op) + private string GetTexSamplerCoords(ShaderIrOp op) { - ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData; + ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - bool HasDepth = (Meta.TextureInstructionSuffix & TextureInstructionSuffix.DC) != 0; + bool hasDepth = (meta.TextureInstructionSuffix & TextureInstructionSuffix.Dc) != 0; - int Coords = ImageUtils.GetCoordsCountTextureTarget(Meta.TextureTarget); + int coords = ImageUtils.GetCoordsCountTextureTarget(meta.TextureTarget); - bool IsArray = ImageUtils.IsArray(Meta.TextureTarget); + bool isArray = ImageUtils.IsArray(meta.TextureTarget); - string GetLastArgument(ShaderIrNode Node) + string GetLastArgument(ShaderIrNode node) { - string Result = GetOperExpr(Op, Node); + string result = GetOperExpr(op, node); // array index is actually an integer so we need to pass it correctly - if (IsArray) + if (isArray) { - Result = "float(floatBitsToInt(" + Result + "))"; + result = "float(floatBitsToInt(" + result + "))"; } - return Result; + return result; } - string LastArgument; - string DepthArgument = ""; + string lastArgument; + string depthArgument = ""; - int VecSize = Coords; - if (HasDepth && Op.Inst != ShaderIrInst.Tld4) + int vecSize = coords; + if (hasDepth && op.Inst != ShaderIrInst.Tld4) { - VecSize++; - DepthArgument = $", {GetOperExpr(Op, Meta.DepthCompare)}"; + vecSize++; + depthArgument = $", {GetOperExpr(op, meta.DepthCompare)}"; } - switch (Coords) + switch (coords) { case 1: - if (HasDepth) + if (hasDepth) { - return $"vec3({GetOperExpr(Op, Meta.Coordinates[0])}, 0.0{DepthArgument})"; + return $"vec3({GetOperExpr(op, meta.Coordinates[0])}, 0.0{depthArgument})"; } - return GetOperExpr(Op, Meta.Coordinates[0]); + return GetOperExpr(op, meta.Coordinates[0]); case 2: - LastArgument = GetLastArgument(Meta.Coordinates[1]); + lastArgument = GetLastArgument(meta.Coordinates[1]); - return $"vec{VecSize}({GetOperExpr(Op, Meta.Coordinates[0])}, {LastArgument}{DepthArgument})"; + return $"vec{vecSize}({GetOperExpr(op, meta.Coordinates[0])}, {lastArgument}{depthArgument})"; case 3: - LastArgument = GetLastArgument(Meta.Coordinates[2]); + lastArgument = GetLastArgument(meta.Coordinates[2]); - return $"vec{VecSize}({GetOperExpr(Op, Meta.Coordinates[0])}, {GetOperExpr(Op, Meta.Coordinates[1])}, {LastArgument}{DepthArgument})"; + return $"vec{vecSize}({GetOperExpr(op, meta.Coordinates[0])}, {GetOperExpr(op, meta.Coordinates[1])}, {lastArgument}{depthArgument})"; case 4: - LastArgument = GetLastArgument(Meta.Coordinates[3]); + lastArgument = GetLastArgument(meta.Coordinates[3]); - return $"vec4({GetOperExpr(Op, Meta.Coordinates[0])}, {GetOperExpr(Op, Meta.Coordinates[1])}, {GetOperExpr(Op, Meta.Coordinates[2])}, {LastArgument}){DepthArgument}"; + return $"vec4({GetOperExpr(op, meta.Coordinates[0])}, {GetOperExpr(op, meta.Coordinates[1])}, {GetOperExpr(op, meta.Coordinates[2])}, {lastArgument}){depthArgument}"; default: throw new InvalidOperationException(); } } - private string GetTextureOffset(ShaderIrMetaTex Meta, string Oper, int Shift = 4, int Mask = 0xF) + private string GetTextureOffset(ShaderIrMetaTex meta, string oper, int shift = 4, int mask = 0xF) { - string GetOffset(string Operation, int Index) + string GetOffset(string operation, int index) { - return $"({Operation} >> {Index * Shift}) & 0x{Mask:x}"; + return $"({operation} >> {index * shift}) & 0x{mask:x}"; } - int Coords = ImageUtils.GetCoordsCountTextureTarget(Meta.TextureTarget); + int coords = ImageUtils.GetCoordsCountTextureTarget(meta.TextureTarget); - if (ImageUtils.IsArray(Meta.TextureTarget)) - Coords -= 1; + if (ImageUtils.IsArray(meta.TextureTarget)) + coords -= 1; - switch (Coords) + switch (coords) { case 1: - return GetOffset(Oper, 0); + return GetOffset(oper, 0); case 2: - return "ivec2(" + GetOffset(Oper, 0) + ", " + GetOffset(Oper, 1) + ")"; + return "ivec2(" + GetOffset(oper, 0) + ", " + GetOffset(oper, 1) + ")"; case 3: - return "ivec3(" + GetOffset(Oper, 0) + ", " + GetOffset(Oper, 1) + ", " + GetOffset(Oper, 2) + ")"; + return "ivec3(" + GetOffset(oper, 0) + ", " + GetOffset(oper, 1) + ", " + GetOffset(oper, 2) + ")"; case 4: - return "ivec4(" + GetOffset(Oper, 0) + ", " + GetOffset(Oper, 1) + ", " + GetOffset(Oper, 2) + ", " + GetOffset(Oper, 3) + ")"; + return "ivec4(" + GetOffset(oper, 0) + ", " + GetOffset(oper, 1) + ", " + GetOffset(oper, 2) + ", " + GetOffset(oper, 3) + ")"; default: throw new InvalidOperationException(); } } // TODO: support AOFFI on non nvidia drivers - private string GetTextureGatherOperation(ShaderIrOp Op, string Sampler, string Coords, string Ch) + private string GetTextureGatherOperation(ShaderIrOp op, string sampler, string coords, string ch) { - ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData; + ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - TextureInstructionSuffix Suffix = Meta.TextureInstructionSuffix; + TextureInstructionSuffix suffix = meta.TextureInstructionSuffix; - string ChString = "." + Ch; + string chString = "." + ch; - string Comp = Meta.Component.ToString(); + string comp = meta.Component.ToString(); - if ((Suffix & TextureInstructionSuffix.DC) != 0) + if ((suffix & TextureInstructionSuffix.Dc) != 0) { - Comp = GetOperExpr(Op, Meta.DepthCompare); + comp = GetOperExpr(op, meta.DepthCompare); } - if ((Suffix & TextureInstructionSuffix.AOffI) != 0 && IsNvidiaDriver) + if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver) { - string Offset = GetTextureOffset(Meta, "floatBitsToInt((" + GetOperExpr(Op, Meta.Offset) + "))", 8, 0x3F); + string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))", 8, 0x3F); - if ((Suffix & TextureInstructionSuffix.DC) != 0) + if ((suffix & TextureInstructionSuffix.Dc) != 0) { - return "textureGatherOffset(" + Sampler + ", " + Coords + ", " + Comp + ", " + Offset + ")" + ChString; + return "textureGatherOffset(" + sampler + ", " + coords + ", " + comp + ", " + offset + ")" + chString; } - return "textureGatherOffset(" + Sampler + ", " + Coords + ", " + Offset + ", " + Comp + ")" + ChString; + return "textureGatherOffset(" + sampler + ", " + coords + ", " + offset + ", " + comp + ")" + chString; } // TODO: Support PTP - else if ((Suffix & TextureInstructionSuffix.PTP) != 0) + else if ((suffix & TextureInstructionSuffix.Ptp) != 0) { throw new NotImplementedException(); } - return "textureGather(" + Sampler + ", " + Coords + ", " + Comp + ")" + ChString; + return "textureGather(" + sampler + ", " + coords + ", " + comp + ")" + chString; } // TODO: support AOFFI on non nvidia drivers - private string GetTextureOperation(ShaderIrOp Op, string Sampler, string Coords, string Ch) + private string GetTextureOperation(ShaderIrOp op, string sampler, string coords, string ch) { - ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData; + ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - TextureInstructionSuffix Suffix = Meta.TextureInstructionSuffix; + TextureInstructionSuffix suffix = meta.TextureInstructionSuffix; - string ChString = "." + Ch; + string chString = "." + ch; - if ((Suffix & TextureInstructionSuffix.DC) != 0) + if ((suffix & TextureInstructionSuffix.Dc) != 0) { - ChString = ""; + chString = ""; } // TODO: Support LBA and LLA - if ((Suffix & TextureInstructionSuffix.LZ) != 0) + if ((suffix & TextureInstructionSuffix.Lz) != 0) { - if ((Suffix & TextureInstructionSuffix.AOffI) != 0 && IsNvidiaDriver) + if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver) { - string Offset = GetTextureOffset(Meta, "floatBitsToInt((" + GetOperExpr(Op, Meta.Offset) + "))"); + string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))"); - return "textureLodOffset(" + Sampler + ", " + Coords + ", 0.0, " + Offset + ")" + ChString; + return "textureLodOffset(" + sampler + ", " + coords + ", 0.0, " + offset + ")" + chString; } - return "textureLod(" + Sampler + ", " + Coords + ", 0.0)" + ChString; + return "textureLod(" + sampler + ", " + coords + ", 0.0)" + chString; } - else if ((Suffix & TextureInstructionSuffix.LB) != 0) + else if ((suffix & TextureInstructionSuffix.Lb) != 0) { - if ((Suffix & TextureInstructionSuffix.AOffI) != 0 && IsNvidiaDriver) + if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver) { - string Offset = GetTextureOffset(Meta, "floatBitsToInt((" + GetOperExpr(Op, Meta.Offset) + "))"); + string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))"); - return "textureOffset(" + Sampler + ", " + Coords + ", " + Offset + ", " + GetOperExpr(Op, Meta.LevelOfDetail) + ")" + ChString; + return "textureOffset(" + sampler + ", " + coords + ", " + offset + ", " + GetOperExpr(op, meta.LevelOfDetail) + ")" + chString; } - return "texture(" + Sampler + ", " + Coords + ", " + GetOperExpr(Op, Meta.LevelOfDetail) + ")" + ChString; + return "texture(" + sampler + ", " + coords + ", " + GetOperExpr(op, meta.LevelOfDetail) + ")" + chString; } - else if ((Suffix & TextureInstructionSuffix.LL) != 0) + else if ((suffix & TextureInstructionSuffix.Ll) != 0) { - if ((Suffix & TextureInstructionSuffix.AOffI) != 0 && IsNvidiaDriver) + if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver) { - string Offset = GetTextureOffset(Meta, "floatBitsToInt((" + GetOperExpr(Op, Meta.Offset) + "))"); + string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))"); - return "textureLodOffset(" + Sampler + ", " + Coords + ", " + GetOperExpr(Op, Meta.LevelOfDetail) + ", " + Offset + ")" + ChString; + return "textureLodOffset(" + sampler + ", " + coords + ", " + GetOperExpr(op, meta.LevelOfDetail) + ", " + offset + ")" + chString; } - return "textureLod(" + Sampler + ", " + Coords + ", " + GetOperExpr(Op, Meta.LevelOfDetail) + ")" + ChString; + return "textureLod(" + sampler + ", " + coords + ", " + GetOperExpr(op, meta.LevelOfDetail) + ")" + chString; } - else if ((Suffix & TextureInstructionSuffix.AOffI) != 0 && IsNvidiaDriver) + else if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver) { - string Offset = GetTextureOffset(Meta, "floatBitsToInt((" + GetOperExpr(Op, Meta.Offset) + "))"); + string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))"); - return "textureOffset(" + Sampler + ", " + Coords + ", " + Offset + ")" + ChString; + return "textureOffset(" + sampler + ", " + coords + ", " + offset + ")" + chString; } else { - return "texture(" + Sampler + ", " + Coords + ")" + ChString; + return "texture(" + sampler + ", " + coords + ")" + chString; } - throw new NotImplementedException($"Texture Suffix {Meta.TextureInstructionSuffix} is not implemented"); + throw new NotImplementedException($"Texture Suffix {meta.TextureInstructionSuffix} is not implemented"); } - private string GetITexSamplerCoords(ShaderIrOp Op) + private string GetITexSamplerCoords(ShaderIrOp op) { - ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData; + ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - switch (ImageUtils.GetCoordsCountTextureTarget(Meta.TextureTarget)) + switch (ImageUtils.GetCoordsCountTextureTarget(meta.TextureTarget)) { case 1: - return GetOperExpr(Op, Meta.Coordinates[0]); + return GetOperExpr(op, meta.Coordinates[0]); case 2: - return "ivec2(" + GetOperExpr(Op, Meta.Coordinates[0]) + ", " + GetOperExpr(Op, Meta.Coordinates[1]) + ")"; + return "ivec2(" + GetOperExpr(op, meta.Coordinates[0]) + ", " + GetOperExpr(op, meta.Coordinates[1]) + ")"; case 3: - return "ivec3(" + GetOperExpr(Op, Meta.Coordinates[0]) + ", " + GetOperExpr(Op, Meta.Coordinates[1]) + ", " + GetOperExpr(Op, Meta.Coordinates[2]) + ")"; + return "ivec3(" + GetOperExpr(op, meta.Coordinates[0]) + ", " + GetOperExpr(op, meta.Coordinates[1]) + ", " + GetOperExpr(op, meta.Coordinates[2]) + ")"; default: throw new InvalidOperationException(); } } - private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper) + private string GetOperExpr(ShaderIrOp op, ShaderIrNode oper) { - return GetExprWithCast(Op, Oper, GetSrcExpr(Oper)); + return GetExprWithCast(op, oper, GetSrcExpr(oper)); } - private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr) + private static string GetExprWithCast(ShaderIrNode dst, ShaderIrNode src, string expr) { //Note: The "DstType" (of the cast) is the type that the operation //uses on the source operands, while the "SrcType" is the destination //type of the operand result (if it is a operation) or just the type //of the variable for registers/uniforms/attributes. - OperType DstType = GetSrcNodeType(Dst); - OperType SrcType = GetDstNodeType(Src); + OperType dstType = GetSrcNodeType(dst); + OperType srcType = GetDstNodeType(src); - if (DstType != SrcType) + if (dstType != srcType) { //Check for invalid casts //(like bool to int/float and others). - if (SrcType != OperType.F32 && - SrcType != OperType.I32) + if (srcType != OperType.F32 && + srcType != OperType.I32) { throw new InvalidOperationException(); } - switch (Src) + switch (src) { - case ShaderIrOperGpr Gpr: + case ShaderIrOperGpr gpr: { //When the Gpr is ZR, just return the 0 value directly, //since the float encoding for 0 is 0. - if (Gpr.IsConst) + if (gpr.IsConst) { return "0"; } @@ -1578,37 +1578,37 @@ namespace Ryujinx.Graphics.Gal.Shader } } - switch (DstType) + switch (dstType) { - case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break; - case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break; + case OperType.F32: expr = "intBitsToFloat(" + expr + ")"; break; + case OperType.I32: expr = "floatBitsToInt(" + expr + ")"; break; } } - return Expr; + return expr; } - private static string GetIntConst(int Value) + private static string GetIntConst(int value) { - string Expr = Value.ToString(CultureInfo.InvariantCulture); + string expr = value.ToString(CultureInfo.InvariantCulture); - return Value < 0 ? "(" + Expr + ")" : Expr; + return value < 0 ? "(" + expr + ")" : expr; } - private static string GetFloatConst(float Value) + private static string GetFloatConst(float value) { - string Expr = Value.ToString(CultureInfo.InvariantCulture); + string expr = value.ToString(CultureInfo.InvariantCulture); - return Value < 0 ? "(" + Expr + ")" : Expr; + return value < 0 ? "(" + expr + ")" : expr; } - private static OperType GetDstNodeType(ShaderIrNode Node) + private static OperType GetDstNodeType(ShaderIrNode node) { //Special case instructions with the result type different //from the input types (like integer <-> float conversion) here. - if (Node is ShaderIrOp Op) + if (node is ShaderIrOp op) { - switch (Op.Inst) + switch (op.Inst) { case ShaderIrInst.Stof: case ShaderIrInst.Txlf: @@ -1621,54 +1621,54 @@ namespace Ryujinx.Graphics.Gal.Shader } } - return GetSrcNodeType(Node); + return GetSrcNodeType(node); } - private static OperType GetSrcNodeType(ShaderIrNode Node) + private static OperType GetSrcNodeType(ShaderIrNode node) { - switch (Node) + switch (node) { - case ShaderIrOperAbuf Abuf: - return Abuf.Offs == GlslDecl.LayerAttr || - Abuf.Offs == GlslDecl.InstanceIdAttr || - Abuf.Offs == GlslDecl.VertexIdAttr || - Abuf.Offs == GlslDecl.FaceAttr + case ShaderIrOperAbuf abuf: + return abuf.Offs == GlslDecl.LayerAttr || + abuf.Offs == GlslDecl.InstanceIdAttr || + abuf.Offs == GlslDecl.VertexIdAttr || + abuf.Offs == GlslDecl.FaceAttr ? OperType.I32 : OperType.F32; - case ShaderIrOperCbuf Cbuf: return OperType.F32; - case ShaderIrOperGpr Gpr: return OperType.F32; - case ShaderIrOperImm Imm: return OperType.I32; - case ShaderIrOperImmf Immf: return OperType.F32; - case ShaderIrOperPred Pred: return OperType.Bool; + case ShaderIrOperCbuf cbuf: return OperType.F32; + case ShaderIrOperGpr gpr: return OperType.F32; + case ShaderIrOperImm imm: return OperType.I32; + case ShaderIrOperImmf immf: return OperType.F32; + case ShaderIrOperPred pred: return OperType.Bool; - case ShaderIrOp Op: - if (Op.Inst > ShaderIrInst.B_Start && - Op.Inst < ShaderIrInst.B_End) + case ShaderIrOp op: + if (op.Inst > ShaderIrInst.B_Start && + op.Inst < ShaderIrInst.B_End) { return OperType.Bool; } - else if (Op.Inst > ShaderIrInst.F_Start && - Op.Inst < ShaderIrInst.F_End) + else if (op.Inst > ShaderIrInst.F_Start && + op.Inst < ShaderIrInst.F_End) { return OperType.F32; } - else if (Op.Inst > ShaderIrInst.I_Start && - Op.Inst < ShaderIrInst.I_End) + else if (op.Inst > ShaderIrInst.I_Start && + op.Inst < ShaderIrInst.I_End) { return OperType.I32; } break; } - throw new ArgumentException(nameof(Node)); + throw new ArgumentException(nameof(node)); } - private static string GetBlockPosition(ShaderIrBlock Block) + private static string GetBlockPosition(ShaderIrBlock block) { - if (Block != null) + if (block != null) { - return "0x" + Block.Position.ToString("x8") + "u"; + return "0x" + block.Position.ToString("x8") + "u"; } else { diff --git a/Ryujinx.Graphics/Gal/Shader/GlslProgram.cs b/Ryujinx.Graphics/Gal/Shader/GlslProgram.cs index a7af05ae..be8555d5 100644 --- a/Ryujinx.Graphics/Gal/Shader/GlslProgram.cs +++ b/Ryujinx.Graphics/Gal/Shader/GlslProgram.cs @@ -10,13 +10,13 @@ namespace Ryujinx.Graphics.Gal.Shader public IEnumerable Uniforms { get; private set; } public GlslProgram( - string Code, - IEnumerable Textures, - IEnumerable Uniforms) + string code, + IEnumerable textures, + IEnumerable uniforms) { - this.Code = Code; - this.Textures = Textures; - this.Uniforms = Uniforms; + Code = code; + Textures = textures; + Uniforms = uniforms; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeAlu.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeAlu.cs index 469092a2..f935be74 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeAlu.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeAlu.cs @@ -14,1138 +14,1138 @@ namespace Ryujinx.Graphics.Gal.Shader MergeH1 } - public static void Bfe_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Bfe_C(ShaderIrBlock block, long opCode, int position) { - EmitBfe(Block, OpCode, ShaderOper.CR); + EmitBfe(block, opCode, ShaderOper.Cr); } - public static void Bfe_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Bfe_I(ShaderIrBlock block, long opCode, int position) { - EmitBfe(Block, OpCode, ShaderOper.Imm); + EmitBfe(block, opCode, ShaderOper.Imm); } - public static void Bfe_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Bfe_R(ShaderIrBlock block, long opCode, int position) { - EmitBfe(Block, OpCode, ShaderOper.RR); + EmitBfe(block, opCode, ShaderOper.Rr); } - public static void Fadd_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Fadd_C(ShaderIrBlock block, long opCode, int position) { - EmitFadd(Block, OpCode, ShaderOper.CR); + EmitFadd(block, opCode, ShaderOper.Cr); } - public static void Fadd_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Fadd_I(ShaderIrBlock block, long opCode, int position) { - EmitFadd(Block, OpCode, ShaderOper.Immf); + EmitFadd(block, opCode, ShaderOper.Immf); } - public static void Fadd_I32(ShaderIrBlock Block, long OpCode, int Position) + public static void Fadd_I32(ShaderIrBlock block, long opCode, int position) { - ShaderIrNode OperA = OpCode.Gpr8(); - ShaderIrNode OperB = OpCode.Immf32_20(); + ShaderIrNode operA = opCode.Gpr8(); + ShaderIrNode operB = opCode.Immf32_20(); - bool NegB = OpCode.Read(53); - bool AbsA = OpCode.Read(54); - bool NegA = OpCode.Read(56); - bool AbsB = OpCode.Read(57); + bool negB = opCode.Read(53); + bool absA = opCode.Read(54); + bool negA = opCode.Read(56); + bool absB = opCode.Read(57); - OperA = GetAluFabsFneg(OperA, AbsA, NegA); - OperB = GetAluFabsFneg(OperB, AbsB, NegB); + operA = GetAluFabsFneg(operA, absA, negA); + operB = GetAluFabsFneg(operB, absB, negB); - ShaderIrOp Op = new ShaderIrOp(ShaderIrInst.Fadd, OperA, OperB); + ShaderIrOp op = new ShaderIrOp(ShaderIrInst.Fadd, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - public static void Fadd_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Fadd_R(ShaderIrBlock block, long opCode, int position) { - EmitFadd(Block, OpCode, ShaderOper.RR); + EmitFadd(block, opCode, ShaderOper.Rr); } - public static void Ffma_CR(ShaderIrBlock Block, long OpCode, int Position) + public static void Ffma_CR(ShaderIrBlock block, long opCode, int position) { - EmitFfma(Block, OpCode, ShaderOper.CR); + EmitFfma(block, opCode, ShaderOper.Cr); } - public static void Ffma_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Ffma_I(ShaderIrBlock block, long opCode, int position) { - EmitFfma(Block, OpCode, ShaderOper.Immf); + EmitFfma(block, opCode, ShaderOper.Immf); } - public static void Ffma_RC(ShaderIrBlock Block, long OpCode, int Position) + public static void Ffma_RC(ShaderIrBlock block, long opCode, int position) { - EmitFfma(Block, OpCode, ShaderOper.RC); + EmitFfma(block, opCode, ShaderOper.Rc); } - public static void Ffma_RR(ShaderIrBlock Block, long OpCode, int Position) + public static void Ffma_RR(ShaderIrBlock block, long opCode, int position) { - EmitFfma(Block, OpCode, ShaderOper.RR); + EmitFfma(block, opCode, ShaderOper.Rr); } - public static void Fmnmx_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Fmnmx_C(ShaderIrBlock block, long opCode, int position) { - EmitFmnmx(Block, OpCode, ShaderOper.CR); + EmitFmnmx(block, opCode, ShaderOper.Cr); } - public static void Fmnmx_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Fmnmx_I(ShaderIrBlock block, long opCode, int position) { - EmitFmnmx(Block, OpCode, ShaderOper.Immf); + EmitFmnmx(block, opCode, ShaderOper.Immf); } - public static void Fmnmx_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Fmnmx_R(ShaderIrBlock block, long opCode, int position) { - EmitFmnmx(Block, OpCode, ShaderOper.RR); + EmitFmnmx(block, opCode, ShaderOper.Rr); } - public static void Fmul_I32(ShaderIrBlock Block, long OpCode, int Position) + public static void Fmul_I32(ShaderIrBlock block, long opCode, int position) { - ShaderIrNode OperA = OpCode.Gpr8(); - ShaderIrNode OperB = OpCode.Immf32_20(); + ShaderIrNode operA = opCode.Gpr8(); + ShaderIrNode operB = opCode.Immf32_20(); - ShaderIrOp Op = new ShaderIrOp(ShaderIrInst.Fmul, OperA, OperB); + ShaderIrOp op = new ShaderIrOp(ShaderIrInst.Fmul, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - public static void Fmul_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Fmul_C(ShaderIrBlock block, long opCode, int position) { - EmitFmul(Block, OpCode, ShaderOper.CR); + EmitFmul(block, opCode, ShaderOper.Cr); } - public static void Fmul_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Fmul_I(ShaderIrBlock block, long opCode, int position) { - EmitFmul(Block, OpCode, ShaderOper.Immf); + EmitFmul(block, opCode, ShaderOper.Immf); } - public static void Fmul_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Fmul_R(ShaderIrBlock block, long opCode, int position) { - EmitFmul(Block, OpCode, ShaderOper.RR); + EmitFmul(block, opCode, ShaderOper.Rr); } - public static void Fset_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Fset_C(ShaderIrBlock block, long opCode, int position) { - EmitFset(Block, OpCode, ShaderOper.CR); + EmitFset(block, opCode, ShaderOper.Cr); } - public static void Fset_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Fset_I(ShaderIrBlock block, long opCode, int position) { - EmitFset(Block, OpCode, ShaderOper.Immf); + EmitFset(block, opCode, ShaderOper.Immf); } - public static void Fset_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Fset_R(ShaderIrBlock block, long opCode, int position) { - EmitFset(Block, OpCode, ShaderOper.RR); + EmitFset(block, opCode, ShaderOper.Rr); } - public static void Fsetp_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Fsetp_C(ShaderIrBlock block, long opCode, int position) { - EmitFsetp(Block, OpCode, ShaderOper.CR); + EmitFsetp(block, opCode, ShaderOper.Cr); } - public static void Fsetp_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Fsetp_I(ShaderIrBlock block, long opCode, int position) { - EmitFsetp(Block, OpCode, ShaderOper.Immf); + EmitFsetp(block, opCode, ShaderOper.Immf); } - public static void Fsetp_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Fsetp_R(ShaderIrBlock block, long opCode, int position) { - EmitFsetp(Block, OpCode, ShaderOper.RR); + EmitFsetp(block, opCode, ShaderOper.Rr); } - public static void Hadd2_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Hadd2_R(ShaderIrBlock block, long opCode, int position) { - EmitBinaryHalfOp(Block, OpCode, ShaderIrInst.Fadd); + EmitBinaryHalfOp(block, opCode, ShaderIrInst.Fadd); } - public static void Hmul2_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Hmul2_R(ShaderIrBlock block, long opCode, int position) { - EmitBinaryHalfOp(Block, OpCode, ShaderIrInst.Fmul); + EmitBinaryHalfOp(block, opCode, ShaderIrInst.Fmul); } - public static void Iadd_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Iadd_C(ShaderIrBlock block, long opCode, int position) { - EmitIadd(Block, OpCode, ShaderOper.CR); + EmitIadd(block, opCode, ShaderOper.Cr); } - public static void Iadd_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Iadd_I(ShaderIrBlock block, long opCode, int position) { - EmitIadd(Block, OpCode, ShaderOper.Imm); + EmitIadd(block, opCode, ShaderOper.Imm); } - public static void Iadd_I32(ShaderIrBlock Block, long OpCode, int Position) + public static void Iadd_I32(ShaderIrBlock block, long opCode, int position) { - ShaderIrNode OperA = OpCode.Gpr8(); - ShaderIrNode OperB = OpCode.Imm32_20(); + ShaderIrNode operA = opCode.Gpr8(); + ShaderIrNode operB = opCode.Imm32_20(); - bool NegA = OpCode.Read(56); + bool negA = opCode.Read(56); - OperA = GetAluIneg(OperA, NegA); + operA = GetAluIneg(operA, negA); - ShaderIrOp Op = new ShaderIrOp(ShaderIrInst.Add, OperA, OperB); + ShaderIrOp op = new ShaderIrOp(ShaderIrInst.Add, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - public static void Iadd_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Iadd_R(ShaderIrBlock block, long opCode, int position) { - EmitIadd(Block, OpCode, ShaderOper.RR); + EmitIadd(block, opCode, ShaderOper.Rr); } - public static void Iadd3_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Iadd3_C(ShaderIrBlock block, long opCode, int position) { - EmitIadd3(Block, OpCode, ShaderOper.CR); + EmitIadd3(block, opCode, ShaderOper.Cr); } - public static void Iadd3_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Iadd3_I(ShaderIrBlock block, long opCode, int position) { - EmitIadd3(Block, OpCode, ShaderOper.Imm); + EmitIadd3(block, opCode, ShaderOper.Imm); } - public static void Iadd3_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Iadd3_R(ShaderIrBlock block, long opCode, int position) { - EmitIadd3(Block, OpCode, ShaderOper.RR); + EmitIadd3(block, opCode, ShaderOper.Rr); } - public static void Imnmx_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Imnmx_C(ShaderIrBlock block, long opCode, int position) { - EmitImnmx(Block, OpCode, ShaderOper.CR); + EmitImnmx(block, opCode, ShaderOper.Cr); } - public static void Imnmx_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Imnmx_I(ShaderIrBlock block, long opCode, int position) { - EmitImnmx(Block, OpCode, ShaderOper.Imm); + EmitImnmx(block, opCode, ShaderOper.Imm); } - public static void Imnmx_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Imnmx_R(ShaderIrBlock block, long opCode, int position) { - EmitImnmx(Block, OpCode, ShaderOper.RR); + EmitImnmx(block, opCode, ShaderOper.Rr); } - public static void Ipa(ShaderIrBlock Block, long OpCode, int Position) + public static void Ipa(ShaderIrBlock block, long opCode, int position) { - ShaderIrNode OperA = OpCode.Abuf28(); - ShaderIrNode OperB = OpCode.Gpr20(); + ShaderIrNode operA = opCode.Abuf28(); + ShaderIrNode operB = opCode.Gpr20(); - ShaderIpaMode Mode = (ShaderIpaMode)(OpCode.Read(54, 3)); + ShaderIpaMode mode = (ShaderIpaMode)(opCode.Read(54, 3)); - ShaderIrMetaIpa Meta = new ShaderIrMetaIpa(Mode); + ShaderIrMetaIpa meta = new ShaderIrMetaIpa(mode); - ShaderIrOp Op = new ShaderIrOp(ShaderIrInst.Ipa, OperA, OperB, null, Meta); + ShaderIrOp op = new ShaderIrOp(ShaderIrInst.Ipa, operA, operB, null, meta); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - public static void Iscadd_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Iscadd_C(ShaderIrBlock block, long opCode, int position) { - EmitIscadd(Block, OpCode, ShaderOper.CR); + EmitIscadd(block, opCode, ShaderOper.Cr); } - public static void Iscadd_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Iscadd_I(ShaderIrBlock block, long opCode, int position) { - EmitIscadd(Block, OpCode, ShaderOper.Imm); + EmitIscadd(block, opCode, ShaderOper.Imm); } - public static void Iscadd_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Iscadd_R(ShaderIrBlock block, long opCode, int position) { - EmitIscadd(Block, OpCode, ShaderOper.RR); + EmitIscadd(block, opCode, ShaderOper.Rr); } - public static void Iset_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Iset_C(ShaderIrBlock block, long opCode, int position) { - EmitIset(Block, OpCode, ShaderOper.CR); + EmitIset(block, opCode, ShaderOper.Cr); } - public static void Iset_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Iset_I(ShaderIrBlock block, long opCode, int position) { - EmitIset(Block, OpCode, ShaderOper.Imm); + EmitIset(block, opCode, ShaderOper.Imm); } - public static void Iset_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Iset_R(ShaderIrBlock block, long opCode, int position) { - EmitIset(Block, OpCode, ShaderOper.RR); + EmitIset(block, opCode, ShaderOper.Rr); } - public static void Isetp_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Isetp_C(ShaderIrBlock block, long opCode, int position) { - EmitIsetp(Block, OpCode, ShaderOper.CR); + EmitIsetp(block, opCode, ShaderOper.Cr); } - public static void Isetp_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Isetp_I(ShaderIrBlock block, long opCode, int position) { - EmitIsetp(Block, OpCode, ShaderOper.Imm); + EmitIsetp(block, opCode, ShaderOper.Imm); } - public static void Isetp_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Isetp_R(ShaderIrBlock block, long opCode, int position) { - EmitIsetp(Block, OpCode, ShaderOper.RR); + EmitIsetp(block, opCode, ShaderOper.Rr); } - public static void Lop_I32(ShaderIrBlock Block, long OpCode, int Position) + public static void Lop_I32(ShaderIrBlock block, long opCode, int position) { - int SubOp = OpCode.Read(53, 3); + int subOp = opCode.Read(53, 3); - bool InvA = OpCode.Read(55); - bool InvB = OpCode.Read(56); + bool invA = opCode.Read(55); + bool invB = opCode.Read(56); - ShaderIrInst Inst = 0; + ShaderIrInst inst = 0; - switch (SubOp) + switch (subOp) { - case 0: Inst = ShaderIrInst.And; break; - case 1: Inst = ShaderIrInst.Or; break; - case 2: Inst = ShaderIrInst.Xor; break; + case 0: inst = ShaderIrInst.And; break; + case 1: inst = ShaderIrInst.Or; break; + case 2: inst = ShaderIrInst.Xor; break; } - ShaderIrNode OperB = GetAluNot(OpCode.Imm32_20(), InvB); + ShaderIrNode operB = GetAluNot(opCode.Imm32_20(), invB); //SubOp == 3 is pass, used by the not instruction //which just moves the inverted register value. - if (SubOp < 3) + if (subOp < 3) { - ShaderIrNode OperA = GetAluNot(OpCode.Gpr8(), InvA); + ShaderIrNode operA = GetAluNot(opCode.Gpr8(), invA); - ShaderIrOp Op = new ShaderIrOp(Inst, OperA, OperB); + ShaderIrOp op = new ShaderIrOp(inst, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } else { - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), OperB))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), operB))); } } - public static void Lop_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Lop_C(ShaderIrBlock block, long opCode, int position) { - EmitLop(Block, OpCode, ShaderOper.CR); + EmitLop(block, opCode, ShaderOper.Cr); } - public static void Lop_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Lop_I(ShaderIrBlock block, long opCode, int position) { - EmitLop(Block, OpCode, ShaderOper.Imm); + EmitLop(block, opCode, ShaderOper.Imm); } - public static void Lop_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Lop_R(ShaderIrBlock block, long opCode, int position) { - EmitLop(Block, OpCode, ShaderOper.RR); + EmitLop(block, opCode, ShaderOper.Rr); } - public static void Mufu(ShaderIrBlock Block, long OpCode, int Position) + public static void Mufu(ShaderIrBlock block, long opCode, int position) { - int SubOp = OpCode.Read(20, 0xf); + int subOp = opCode.Read(20, 0xf); - bool AbsA = OpCode.Read(46); - bool NegA = OpCode.Read(48); + bool absA = opCode.Read(46); + bool negA = opCode.Read(48); - ShaderIrInst Inst = 0; + ShaderIrInst inst = 0; - switch (SubOp) + switch (subOp) { - case 0: Inst = ShaderIrInst.Fcos; break; - case 1: Inst = ShaderIrInst.Fsin; break; - case 2: Inst = ShaderIrInst.Fex2; break; - case 3: Inst = ShaderIrInst.Flg2; break; - case 4: Inst = ShaderIrInst.Frcp; break; - case 5: Inst = ShaderIrInst.Frsq; break; - case 8: Inst = ShaderIrInst.Fsqrt; break; + case 0: inst = ShaderIrInst.Fcos; break; + case 1: inst = ShaderIrInst.Fsin; break; + case 2: inst = ShaderIrInst.Fex2; break; + case 3: inst = ShaderIrInst.Flg2; break; + case 4: inst = ShaderIrInst.Frcp; break; + case 5: inst = ShaderIrInst.Frsq; break; + case 8: inst = ShaderIrInst.Fsqrt; break; - default: throw new NotImplementedException(SubOp.ToString()); + default: throw new NotImplementedException(subOp.ToString()); } - ShaderIrNode OperA = OpCode.Gpr8(); + ShaderIrNode operA = opCode.Gpr8(); - ShaderIrOp Op = new ShaderIrOp(Inst, GetAluFabsFneg(OperA, AbsA, NegA)); + ShaderIrOp op = new ShaderIrOp(inst, GetAluFabsFneg(operA, absA, negA)); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - public static void Psetp(ShaderIrBlock Block, long OpCode, int Position) + public static void Psetp(ShaderIrBlock block, long opCode, int position) { - bool NegA = OpCode.Read(15); - bool NegB = OpCode.Read(32); - bool NegP = OpCode.Read(42); + bool negA = opCode.Read(15); + bool negB = opCode.Read(32); + bool negP = opCode.Read(42); - ShaderIrInst LopInst = OpCode.BLop24(); + ShaderIrInst lopInst = opCode.BLop24(); - ShaderIrNode OperA = OpCode.Pred12(); - ShaderIrNode OperB = OpCode.Pred29(); + ShaderIrNode operA = opCode.Pred12(); + ShaderIrNode operB = opCode.Pred29(); - if (NegA) + if (negA) { - OperA = new ShaderIrOp(ShaderIrInst.Bnot, OperA); + operA = new ShaderIrOp(ShaderIrInst.Bnot, operA); } - if (NegB) + if (negB) { - OperB = new ShaderIrOp(ShaderIrInst.Bnot, OperB); + operB = new ShaderIrOp(ShaderIrInst.Bnot, operB); } - ShaderIrOp Op = new ShaderIrOp(LopInst, OperA, OperB); + ShaderIrOp op = new ShaderIrOp(lopInst, operA, operB); - ShaderIrOperPred P0Node = OpCode.Pred3(); - ShaderIrOperPred P1Node = OpCode.Pred0(); - ShaderIrOperPred P2Node = OpCode.Pred39(); + ShaderIrOperPred p0Node = opCode.Pred3(); + ShaderIrOperPred p1Node = opCode.Pred0(); + ShaderIrOperPred p2Node = opCode.Pred39(); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(P0Node, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(p0Node, op))); - LopInst = OpCode.BLop45(); + lopInst = opCode.BLop45(); - if (LopInst == ShaderIrInst.Band && P1Node.IsConst && P2Node.IsConst) + if (lopInst == ShaderIrInst.Band && p1Node.IsConst && p2Node.IsConst) { return; } - ShaderIrNode P2NNode = P2Node; + ShaderIrNode p2NNode = p2Node; - if (NegP) + if (negP) { - P2NNode = new ShaderIrOp(ShaderIrInst.Bnot, P2NNode); + p2NNode = new ShaderIrOp(ShaderIrInst.Bnot, p2NNode); } - Op = new ShaderIrOp(ShaderIrInst.Bnot, P0Node); + op = new ShaderIrOp(ShaderIrInst.Bnot, p0Node); - Op = new ShaderIrOp(LopInst, Op, P2NNode); + op = new ShaderIrOp(lopInst, op, p2NNode); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(P1Node, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(p1Node, op))); - Op = new ShaderIrOp(LopInst, P0Node, P2NNode); + op = new ShaderIrOp(lopInst, p0Node, p2NNode); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(P0Node, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(p0Node, op))); } - public static void Rro_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Rro_C(ShaderIrBlock block, long opCode, int position) { - EmitRro(Block, OpCode, ShaderOper.CR); + EmitRro(block, opCode, ShaderOper.Cr); } - public static void Rro_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Rro_I(ShaderIrBlock block, long opCode, int position) { - EmitRro(Block, OpCode, ShaderOper.Immf); + EmitRro(block, opCode, ShaderOper.Immf); } - public static void Rro_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Rro_R(ShaderIrBlock block, long opCode, int position) { - EmitRro(Block, OpCode, ShaderOper.RR); + EmitRro(block, opCode, ShaderOper.Rr); } - public static void Shl_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Shl_C(ShaderIrBlock block, long opCode, int position) { - EmitAluBinary(Block, OpCode, ShaderOper.CR, ShaderIrInst.Lsl); + EmitAluBinary(block, opCode, ShaderOper.Cr, ShaderIrInst.Lsl); } - public static void Shl_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Shl_I(ShaderIrBlock block, long opCode, int position) { - EmitAluBinary(Block, OpCode, ShaderOper.Imm, ShaderIrInst.Lsl); + EmitAluBinary(block, opCode, ShaderOper.Imm, ShaderIrInst.Lsl); } - public static void Shl_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Shl_R(ShaderIrBlock block, long opCode, int position) { - EmitAluBinary(Block, OpCode, ShaderOper.RR, ShaderIrInst.Lsl); + EmitAluBinary(block, opCode, ShaderOper.Rr, ShaderIrInst.Lsl); } - public static void Shr_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Shr_C(ShaderIrBlock block, long opCode, int position) { - EmitAluBinary(Block, OpCode, ShaderOper.CR, GetShrInst(OpCode)); + EmitAluBinary(block, opCode, ShaderOper.Cr, GetShrInst(opCode)); } - public static void Shr_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Shr_I(ShaderIrBlock block, long opCode, int position) { - EmitAluBinary(Block, OpCode, ShaderOper.Imm, GetShrInst(OpCode)); + EmitAluBinary(block, opCode, ShaderOper.Imm, GetShrInst(opCode)); } - public static void Shr_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Shr_R(ShaderIrBlock block, long opCode, int position) { - EmitAluBinary(Block, OpCode, ShaderOper.RR, GetShrInst(OpCode)); + EmitAluBinary(block, opCode, ShaderOper.Rr, GetShrInst(opCode)); } - private static ShaderIrInst GetShrInst(long OpCode) + private static ShaderIrInst GetShrInst(long opCode) { - bool Signed = OpCode.Read(48); + bool signed = opCode.Read(48); - return Signed ? ShaderIrInst.Asr : ShaderIrInst.Lsr; + return signed ? ShaderIrInst.Asr : ShaderIrInst.Lsr; } - public static void Vmad(ShaderIrBlock Block, long OpCode, int Position) + public static void Vmad(ShaderIrBlock block, long opCode, int position) { - ShaderIrNode OperA = OpCode.Gpr8(); + ShaderIrNode operA = opCode.Gpr8(); - ShaderIrNode OperB; + ShaderIrNode operB; - if (OpCode.Read(50)) + if (opCode.Read(50)) { - OperB = OpCode.Gpr20(); + operB = opCode.Gpr20(); } else { - OperB = OpCode.Imm19_20(); + operB = opCode.Imm19_20(); } - ShaderIrOperGpr OperC = OpCode.Gpr39(); + ShaderIrOperGpr operC = opCode.Gpr39(); - ShaderIrNode Tmp = new ShaderIrOp(ShaderIrInst.Mul, OperA, OperB); + ShaderIrNode tmp = new ShaderIrOp(ShaderIrInst.Mul, operA, operB); - ShaderIrNode Final = new ShaderIrOp(ShaderIrInst.Add, Tmp, OperC); + ShaderIrNode final = new ShaderIrOp(ShaderIrInst.Add, tmp, operC); - int Shr = OpCode.Read(51, 3); + int shr = opCode.Read(51, 3); - if (Shr != 0) + if (shr != 0) { - int Shift = (Shr == 2) ? 15 : 7; + int shift = (shr == 2) ? 15 : 7; - Final = new ShaderIrOp(ShaderIrInst.Lsr, Final, new ShaderIrOperImm(Shift)); + final = new ShaderIrOp(ShaderIrInst.Lsr, final, new ShaderIrOperImm(shift)); } - Block.AddNode(new ShaderIrCmnt("Stubbed. Instruction is reduced to a * b + c")); + block.AddNode(new ShaderIrCmnt("Stubbed. Instruction is reduced to a * b + c")); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Final))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), final))); } - public static void Xmad_CR(ShaderIrBlock Block, long OpCode, int Position) + public static void Xmad_CR(ShaderIrBlock block, long opCode, int position) { - EmitXmad(Block, OpCode, ShaderOper.CR); + EmitXmad(block, opCode, ShaderOper.Cr); } - public static void Xmad_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Xmad_I(ShaderIrBlock block, long opCode, int position) { - EmitXmad(Block, OpCode, ShaderOper.Imm); + EmitXmad(block, opCode, ShaderOper.Imm); } - public static void Xmad_RC(ShaderIrBlock Block, long OpCode, int Position) + public static void Xmad_RC(ShaderIrBlock block, long opCode, int position) { - EmitXmad(Block, OpCode, ShaderOper.RC); + EmitXmad(block, opCode, ShaderOper.Rc); } - public static void Xmad_RR(ShaderIrBlock Block, long OpCode, int Position) + public static void Xmad_RR(ShaderIrBlock block, long opCode, int position) { - EmitXmad(Block, OpCode, ShaderOper.RR); + EmitXmad(block, opCode, ShaderOper.Rr); } private static void EmitAluBinary( - ShaderIrBlock Block, - long OpCode, - ShaderOper Oper, - ShaderIrInst Inst) + ShaderIrBlock block, + long opCode, + ShaderOper oper, + ShaderIrInst inst) { - ShaderIrNode OperA = OpCode.Gpr8(), OperB; + ShaderIrNode operA = opCode.Gpr8(), operB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - ShaderIrNode Op = new ShaderIrOp(Inst, OperA, OperB); + ShaderIrNode op = new ShaderIrOp(inst, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - private static void EmitBfe(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitBfe(ShaderIrBlock block, long opCode, ShaderOper oper) { //TODO: Handle the case where position + length //is greater than the word size, in this case the sign bit //needs to be replicated to fill the remaining space. - bool NegB = OpCode.Read(48); - bool NegA = OpCode.Read(49); + bool negB = opCode.Read(48); + bool negA = opCode.Read(49); - ShaderIrNode OperA = OpCode.Gpr8(), OperB; + ShaderIrNode operA = opCode.Gpr8(), operB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - ShaderIrNode Op; + ShaderIrNode op; - bool Signed = OpCode.Read(48); //? + bool signed = opCode.Read(48); //? - if (OperB is ShaderIrOperImm PosLen) + if (operB is ShaderIrOperImm posLen) { - int Position = (PosLen.Value >> 0) & 0xff; - int Length = (PosLen.Value >> 8) & 0xff; + int position = (posLen.Value >> 0) & 0xff; + int length = (posLen.Value >> 8) & 0xff; - int LSh = 32 - (Position + Length); + int lSh = 32 - (position + length); - ShaderIrInst RightShift = Signed + ShaderIrInst rightShift = signed ? ShaderIrInst.Asr : ShaderIrInst.Lsr; - Op = new ShaderIrOp(ShaderIrInst.Lsl, OperA, new ShaderIrOperImm(LSh)); - Op = new ShaderIrOp(RightShift, Op, new ShaderIrOperImm(LSh + Position)); + op = new ShaderIrOp(ShaderIrInst.Lsl, operA, new ShaderIrOperImm(lSh)); + op = new ShaderIrOp(rightShift, op, new ShaderIrOperImm(lSh + position)); } else { - ShaderIrOperImm Shift = new ShaderIrOperImm(8); - ShaderIrOperImm Mask = new ShaderIrOperImm(0xff); + ShaderIrOperImm shift = new ShaderIrOperImm(8); + ShaderIrOperImm mask = new ShaderIrOperImm(0xff); - ShaderIrNode OpPos, OpLen; + ShaderIrNode opPos, opLen; - OpPos = new ShaderIrOp(ShaderIrInst.And, OperB, Mask); - OpLen = new ShaderIrOp(ShaderIrInst.Lsr, OperB, Shift); - OpLen = new ShaderIrOp(ShaderIrInst.And, OpLen, Mask); + opPos = new ShaderIrOp(ShaderIrInst.And, operB, mask); + opLen = new ShaderIrOp(ShaderIrInst.Lsr, operB, shift); + opLen = new ShaderIrOp(ShaderIrInst.And, opLen, mask); - Op = new ShaderIrOp(ShaderIrInst.Lsr, OperA, OpPos); + op = new ShaderIrOp(ShaderIrInst.Lsr, operA, opPos); - Op = ExtendTo32(Op, Signed, OpLen); + op = ExtendTo32(op, signed, opLen); } - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - private static void EmitFadd(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitFadd(ShaderIrBlock block, long opCode, ShaderOper oper) { - bool NegB = OpCode.Read(45); - bool AbsA = OpCode.Read(46); - bool NegA = OpCode.Read(48); - bool AbsB = OpCode.Read(49); - bool Sat = OpCode.Read(50); + bool negB = opCode.Read(45); + bool absA = opCode.Read(46); + bool negA = opCode.Read(48); + bool absB = opCode.Read(49); + bool sat = opCode.Read(50); - ShaderIrNode OperA = OpCode.Gpr8(), OperB; + ShaderIrNode operA = opCode.Gpr8(), operB; - OperA = GetAluFabsFneg(OperA, AbsA, NegA); + operA = GetAluFabsFneg(operA, absA, negA); - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Immf: OperB = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Immf: operB = opCode.Immf19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperB = GetAluFabsFneg(OperB, AbsB, NegB); + operB = GetAluFabsFneg(operB, absB, negB); - ShaderIrNode Op = new ShaderIrOp(ShaderIrInst.Fadd, OperA, OperB); + ShaderIrNode op = new ShaderIrOp(ShaderIrInst.Fadd, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), GetAluFsat(Op, Sat)))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), GetAluFsat(op, sat)))); } - private static void EmitFmul(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitFmul(ShaderIrBlock block, long opCode, ShaderOper oper) { - bool NegB = OpCode.Read(48); - bool Sat = OpCode.Read(50); + bool negB = opCode.Read(48); + bool sat = opCode.Read(50); - ShaderIrNode OperA = OpCode.Gpr8(), OperB; + ShaderIrNode operA = opCode.Gpr8(), operB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Immf: OperB = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Immf: operB = opCode.Immf19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperB = GetAluFneg(OperB, NegB); + operB = GetAluFneg(operB, negB); - ShaderIrNode Op = new ShaderIrOp(ShaderIrInst.Fmul, OperA, OperB); + ShaderIrNode op = new ShaderIrOp(ShaderIrInst.Fmul, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), GetAluFsat(Op, Sat)))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), GetAluFsat(op, sat)))); } - private static void EmitFfma(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitFfma(ShaderIrBlock block, long opCode, ShaderOper oper) { - bool NegB = OpCode.Read(48); - bool NegC = OpCode.Read(49); - bool Sat = OpCode.Read(50); + bool negB = opCode.Read(48); + bool negC = opCode.Read(49); + bool sat = opCode.Read(50); - ShaderIrNode OperA = OpCode.Gpr8(), OperB, OperC; + ShaderIrNode operA = opCode.Gpr8(), operB, operC; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Immf: OperB = OpCode.Immf19_20(); break; - case ShaderOper.RC: OperB = OpCode.Gpr39(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Immf: operB = opCode.Immf19_20(); break; + case ShaderOper.Rc: operB = opCode.Gpr39(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperB = GetAluFneg(OperB, NegB); + operB = GetAluFneg(operB, negB); - if (Oper == ShaderOper.RC) + if (oper == ShaderOper.Rc) { - OperC = GetAluFneg(OpCode.Cbuf34(), NegC); + operC = GetAluFneg(opCode.Cbuf34(), negC); } else { - OperC = GetAluFneg(OpCode.Gpr39(), NegC); + operC = GetAluFneg(opCode.Gpr39(), negC); } - ShaderIrOp Op = new ShaderIrOp(ShaderIrInst.Ffma, OperA, OperB, OperC); + ShaderIrOp op = new ShaderIrOp(ShaderIrInst.Ffma, operA, operB, operC); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), GetAluFsat(Op, Sat)))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), GetAluFsat(op, sat)))); } - private static void EmitIadd(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitIadd(ShaderIrBlock block, long opCode, ShaderOper oper) { - ShaderIrNode OperA = OpCode.Gpr8(); - ShaderIrNode OperB; + ShaderIrNode operA = opCode.Gpr8(); + ShaderIrNode operB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - bool NegA = OpCode.Read(49); - bool NegB = OpCode.Read(48); + bool negA = opCode.Read(49); + bool negB = opCode.Read(48); - OperA = GetAluIneg(OperA, NegA); - OperB = GetAluIneg(OperB, NegB); + operA = GetAluIneg(operA, negA); + operB = GetAluIneg(operB, negB); - ShaderIrOp Op = new ShaderIrOp(ShaderIrInst.Add, OperA, OperB); + ShaderIrOp op = new ShaderIrOp(ShaderIrInst.Add, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - private static void EmitIadd3(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitIadd3(ShaderIrBlock block, long opCode, ShaderOper oper) { - int Mode = OpCode.Read(37, 3); + int mode = opCode.Read(37, 3); - bool Neg1 = OpCode.Read(51); - bool Neg2 = OpCode.Read(50); - bool Neg3 = OpCode.Read(49); + bool neg1 = opCode.Read(51); + bool neg2 = opCode.Read(50); + bool neg3 = opCode.Read(49); - int Height1 = OpCode.Read(35, 3); - int Height2 = OpCode.Read(33, 3); - int Height3 = OpCode.Read(31, 3); + int height1 = opCode.Read(35, 3); + int height2 = opCode.Read(33, 3); + int height3 = opCode.Read(31, 3); - ShaderIrNode OperB; + ShaderIrNode operB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - ShaderIrNode ApplyHeight(ShaderIrNode Src, int Height) + ShaderIrNode ApplyHeight(ShaderIrNode src, int height) { - if (Oper != ShaderOper.RR) + if (oper != ShaderOper.Rr) { - return Src; + return src; } - switch (Height) + switch (height) { - case 0: return Src; - case 1: return new ShaderIrOp(ShaderIrInst.And, Src, new ShaderIrOperImm(0xffff)); - case 2: return new ShaderIrOp(ShaderIrInst.Lsr, Src, new ShaderIrOperImm(16)); + case 0: return src; + case 1: return new ShaderIrOp(ShaderIrInst.And, src, new ShaderIrOperImm(0xffff)); + case 2: return new ShaderIrOp(ShaderIrInst.Lsr, src, new ShaderIrOperImm(16)); default: throw new InvalidOperationException(); } } - ShaderIrNode Src1 = GetAluIneg(ApplyHeight(OpCode.Gpr8(), Height1), Neg1); - ShaderIrNode Src2 = GetAluIneg(ApplyHeight(OperB, Height2), Neg2); - ShaderIrNode Src3 = GetAluIneg(ApplyHeight(OpCode.Gpr39(), Height3), Neg3); + ShaderIrNode src1 = GetAluIneg(ApplyHeight(opCode.Gpr8(), height1), neg1); + ShaderIrNode src2 = GetAluIneg(ApplyHeight(operB, height2), neg2); + ShaderIrNode src3 = GetAluIneg(ApplyHeight(opCode.Gpr39(), height3), neg3); - ShaderIrOp Sum = new ShaderIrOp(ShaderIrInst.Add, Src1, Src2); + ShaderIrOp sum = new ShaderIrOp(ShaderIrInst.Add, src1, src2); - if (Oper == ShaderOper.RR) + if (oper == ShaderOper.Rr) { - switch (Mode) + switch (mode) { - case 1: Sum = new ShaderIrOp(ShaderIrInst.Lsr, Sum, new ShaderIrOperImm(16)); break; - case 2: Sum = new ShaderIrOp(ShaderIrInst.Lsl, Sum, new ShaderIrOperImm(16)); break; + case 1: sum = new ShaderIrOp(ShaderIrInst.Lsr, sum, new ShaderIrOperImm(16)); break; + case 2: sum = new ShaderIrOp(ShaderIrInst.Lsl, sum, new ShaderIrOperImm(16)); break; } } //Note: Here there should be a "+ 1" when carry flag is set //but since carry is mostly ignored by other instructions, it's excluded for now - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), new ShaderIrOp(ShaderIrInst.Add, Sum, Src3)))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), new ShaderIrOp(ShaderIrInst.Add, sum, src3)))); } - private static void EmitIscadd(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitIscadd(ShaderIrBlock block, long opCode, ShaderOper oper) { - bool NegB = OpCode.Read(48); - bool NegA = OpCode.Read(49); + bool negB = opCode.Read(48); + bool negA = opCode.Read(49); - ShaderIrNode OperA = OpCode.Gpr8(), OperB; + ShaderIrNode operA = opCode.Gpr8(), operB; - ShaderIrOperImm Scale = OpCode.Imm5_39(); + ShaderIrOperImm scale = opCode.Imm5_39(); - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperA = GetAluIneg(OperA, NegA); - OperB = GetAluIneg(OperB, NegB); + operA = GetAluIneg(operA, negA); + operB = GetAluIneg(operB, negB); - ShaderIrOp ScaleOp = new ShaderIrOp(ShaderIrInst.Lsl, OperA, Scale); - ShaderIrOp AddOp = new ShaderIrOp(ShaderIrInst.Add, OperB, ScaleOp); + ShaderIrOp scaleOp = new ShaderIrOp(ShaderIrInst.Lsl, operA, scale); + ShaderIrOp addOp = new ShaderIrOp(ShaderIrInst.Add, operB, scaleOp); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), AddOp))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), addOp))); } - private static void EmitFmnmx(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitFmnmx(ShaderIrBlock block, long opCode, ShaderOper oper) { - EmitMnmx(Block, OpCode, true, Oper); + EmitMnmx(block, opCode, true, oper); } - private static void EmitImnmx(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitImnmx(ShaderIrBlock block, long opCode, ShaderOper oper) { - EmitMnmx(Block, OpCode, false, Oper); + EmitMnmx(block, opCode, false, oper); } - private static void EmitMnmx(ShaderIrBlock Block, long OpCode, bool IsFloat, ShaderOper Oper) + private static void EmitMnmx(ShaderIrBlock block, long opCode, bool isFloat, ShaderOper oper) { - bool NegB = OpCode.Read(45); - bool AbsA = OpCode.Read(46); - bool NegA = OpCode.Read(48); - bool AbsB = OpCode.Read(49); + bool negB = opCode.Read(45); + bool absA = opCode.Read(46); + bool negA = opCode.Read(48); + bool absB = opCode.Read(49); - ShaderIrNode OperA = OpCode.Gpr8(), OperB; + ShaderIrNode operA = opCode.Gpr8(), operB; - if (IsFloat) + if (isFloat) { - OperA = GetAluFabsFneg(OperA, AbsA, NegA); + operA = GetAluFabsFneg(operA, absA, negA); } else { - OperA = GetAluIabsIneg(OperA, AbsA, NegA); + operA = GetAluIabsIneg(operA, absA, negA); } - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.Immf: OperB = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Immf: operB = opCode.Immf19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - if (IsFloat) + if (isFloat) { - OperB = GetAluFabsFneg(OperB, AbsB, NegB); + operB = GetAluFabsFneg(operB, absB, negB); } else { - OperB = GetAluIabsIneg(OperB, AbsB, NegB); + operB = GetAluIabsIneg(operB, absB, negB); } - ShaderIrOperPred Pred = OpCode.Pred39(); + ShaderIrOperPred pred = opCode.Pred39(); - ShaderIrOp Op; + ShaderIrOp op; - ShaderIrInst MaxInst = IsFloat ? ShaderIrInst.Fmax : ShaderIrInst.Max; - ShaderIrInst MinInst = IsFloat ? ShaderIrInst.Fmin : ShaderIrInst.Min; + ShaderIrInst maxInst = isFloat ? ShaderIrInst.Fmax : ShaderIrInst.Max; + ShaderIrInst minInst = isFloat ? ShaderIrInst.Fmin : ShaderIrInst.Min; - if (Pred.IsConst) + if (pred.IsConst) { - bool IsMax = OpCode.Read(42); + bool isMax = opCode.Read(42); - Op = new ShaderIrOp(IsMax - ? MaxInst - : MinInst, OperA, OperB); + op = new ShaderIrOp(isMax + ? maxInst + : minInst, operA, operB); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } else { - ShaderIrNode PredN = OpCode.Pred39N(); + ShaderIrNode predN = opCode.Pred39N(); - ShaderIrOp OpMax = new ShaderIrOp(MaxInst, OperA, OperB); - ShaderIrOp OpMin = new ShaderIrOp(MinInst, OperA, OperB); + ShaderIrOp opMax = new ShaderIrOp(maxInst, operA, operB); + ShaderIrOp opMin = new ShaderIrOp(minInst, operA, operB); - ShaderIrAsg AsgMax = new ShaderIrAsg(OpCode.Gpr0(), OpMax); - ShaderIrAsg AsgMin = new ShaderIrAsg(OpCode.Gpr0(), OpMin); + ShaderIrAsg asgMax = new ShaderIrAsg(opCode.Gpr0(), opMax); + ShaderIrAsg asgMin = new ShaderIrAsg(opCode.Gpr0(), opMin); - Block.AddNode(OpCode.PredNode(new ShaderIrCond(PredN, AsgMax, Not: true))); - Block.AddNode(OpCode.PredNode(new ShaderIrCond(PredN, AsgMin, Not: false))); + block.AddNode(opCode.PredNode(new ShaderIrCond(predN, asgMax, not: true))); + block.AddNode(opCode.PredNode(new ShaderIrCond(predN, asgMin, not: false))); } } - private static void EmitRro(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitRro(ShaderIrBlock block, long opCode, ShaderOper oper) { //Note: this is a range reduction instruction and is supposed to //be used with Mufu, here it just moves the value and ignores the operation. - bool NegA = OpCode.Read(45); - bool AbsA = OpCode.Read(49); + bool negA = opCode.Read(45); + bool absA = opCode.Read(49); - ShaderIrNode OperA; + ShaderIrNode operA; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperA = OpCode.Cbuf34(); break; - case ShaderOper.Immf: OperA = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperA = OpCode.Gpr20(); break; + case ShaderOper.Cr: operA = opCode.Cbuf34(); break; + case ShaderOper.Immf: operA = opCode.Immf19_20(); break; + case ShaderOper.Rr: operA = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperA = GetAluFabsFneg(OperA, AbsA, NegA); + operA = GetAluFabsFneg(operA, absA, negA); - Block.AddNode(new ShaderIrCmnt("Stubbed.")); + block.AddNode(new ShaderIrCmnt("Stubbed.")); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), OperA))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), operA))); } - private static void EmitFset(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitFset(ShaderIrBlock block, long opCode, ShaderOper oper) { - EmitSet(Block, OpCode, true, Oper); + EmitSet(block, opCode, true, oper); } - private static void EmitIset(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitIset(ShaderIrBlock block, long opCode, ShaderOper oper) { - EmitSet(Block, OpCode, false, Oper); + EmitSet(block, opCode, false, oper); } - private static void EmitSet(ShaderIrBlock Block, long OpCode, bool IsFloat, ShaderOper Oper) + private static void EmitSet(ShaderIrBlock block, long opCode, bool isFloat, ShaderOper oper) { - bool NegA = OpCode.Read(43); - bool AbsB = OpCode.Read(44); - bool NegB = OpCode.Read(53); - bool AbsA = OpCode.Read(54); + bool negA = opCode.Read(43); + bool absB = opCode.Read(44); + bool negB = opCode.Read(53); + bool absA = opCode.Read(54); - bool BoolFloat = OpCode.Read(IsFloat ? 52 : 44); + bool boolFloat = opCode.Read(isFloat ? 52 : 44); - ShaderIrNode OperA = OpCode.Gpr8(), OperB; + ShaderIrNode operA = opCode.Gpr8(), operB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.Immf: OperB = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Immf: operB = opCode.Immf19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - ShaderIrInst CmpInst; + ShaderIrInst cmpInst; - if (IsFloat) + if (isFloat) { - OperA = GetAluFabsFneg(OperA, AbsA, NegA); - OperB = GetAluFabsFneg(OperB, AbsB, NegB); + operA = GetAluFabsFneg(operA, absA, negA); + operB = GetAluFabsFneg(operB, absB, negB); - CmpInst = OpCode.CmpF(); + cmpInst = opCode.CmpF(); } else { - CmpInst = OpCode.Cmp(); + cmpInst = opCode.Cmp(); } - ShaderIrOp Op = new ShaderIrOp(CmpInst, OperA, OperB); + ShaderIrOp op = new ShaderIrOp(cmpInst, operA, operB); - ShaderIrInst LopInst = OpCode.BLop45(); + ShaderIrInst lopInst = opCode.BLop45(); - ShaderIrOperPred PNode = OpCode.Pred39(); + ShaderIrOperPred pNode = opCode.Pred39(); - ShaderIrNode Imm0, Imm1; + ShaderIrNode imm0, imm1; - if (BoolFloat) + if (boolFloat) { - Imm0 = new ShaderIrOperImmf(0); - Imm1 = new ShaderIrOperImmf(1); + imm0 = new ShaderIrOperImmf(0); + imm1 = new ShaderIrOperImmf(1); } else { - Imm0 = new ShaderIrOperImm(0); - Imm1 = new ShaderIrOperImm(-1); + imm0 = new ShaderIrOperImm(0); + imm1 = new ShaderIrOperImm(-1); } - ShaderIrNode Asg0 = new ShaderIrAsg(OpCode.Gpr0(), Imm0); - ShaderIrNode Asg1 = new ShaderIrAsg(OpCode.Gpr0(), Imm1); + ShaderIrNode asg0 = new ShaderIrAsg(opCode.Gpr0(), imm0); + ShaderIrNode asg1 = new ShaderIrAsg(opCode.Gpr0(), imm1); - if (LopInst != ShaderIrInst.Band || !PNode.IsConst) + if (lopInst != ShaderIrInst.Band || !pNode.IsConst) { - ShaderIrOp Op2 = new ShaderIrOp(LopInst, Op, PNode); + ShaderIrOp op2 = new ShaderIrOp(lopInst, op, pNode); - Asg0 = new ShaderIrCond(Op2, Asg0, Not: true); - Asg1 = new ShaderIrCond(Op2, Asg1, Not: false); + asg0 = new ShaderIrCond(op2, asg0, not: true); + asg1 = new ShaderIrCond(op2, asg1, not: false); } else { - Asg0 = new ShaderIrCond(Op, Asg0, Not: true); - Asg1 = new ShaderIrCond(Op, Asg1, Not: false); + asg0 = new ShaderIrCond(op, asg0, not: true); + asg1 = new ShaderIrCond(op, asg1, not: false); } - Block.AddNode(OpCode.PredNode(Asg0)); - Block.AddNode(OpCode.PredNode(Asg1)); + block.AddNode(opCode.PredNode(asg0)); + block.AddNode(opCode.PredNode(asg1)); } - private static void EmitFsetp(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitFsetp(ShaderIrBlock block, long opCode, ShaderOper oper) { - EmitSetp(Block, OpCode, true, Oper); + EmitSetp(block, opCode, true, oper); } - private static void EmitIsetp(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitIsetp(ShaderIrBlock block, long opCode, ShaderOper oper) { - EmitSetp(Block, OpCode, false, Oper); + EmitSetp(block, opCode, false, oper); } - private static void EmitSetp(ShaderIrBlock Block, long OpCode, bool IsFloat, ShaderOper Oper) + private static void EmitSetp(ShaderIrBlock block, long opCode, bool isFloat, ShaderOper oper) { - bool AbsA = OpCode.Read(7); - bool NegP = OpCode.Read(42); - bool NegA = OpCode.Read(43); - bool AbsB = OpCode.Read(44); + bool absA = opCode.Read(7); + bool negP = opCode.Read(42); + bool negA = opCode.Read(43); + bool absB = opCode.Read(44); - ShaderIrNode OperA = OpCode.Gpr8(), OperB; + ShaderIrNode operA = opCode.Gpr8(), operB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.Immf: OperB = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Immf: operB = opCode.Immf19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - ShaderIrInst CmpInst; + ShaderIrInst cmpInst; - if (IsFloat) + if (isFloat) { - OperA = GetAluFabsFneg(OperA, AbsA, NegA); - OperB = GetAluFabs (OperB, AbsB); + operA = GetAluFabsFneg(operA, absA, negA); + operB = GetAluFabs (operB, absB); - CmpInst = OpCode.CmpF(); + cmpInst = opCode.CmpF(); } else { - CmpInst = OpCode.Cmp(); + cmpInst = opCode.Cmp(); } - ShaderIrOp Op = new ShaderIrOp(CmpInst, OperA, OperB); + ShaderIrOp op = new ShaderIrOp(cmpInst, operA, operB); - ShaderIrOperPred P0Node = OpCode.Pred3(); - ShaderIrOperPred P1Node = OpCode.Pred0(); - ShaderIrOperPred P2Node = OpCode.Pred39(); + ShaderIrOperPred p0Node = opCode.Pred3(); + ShaderIrOperPred p1Node = opCode.Pred0(); + ShaderIrOperPred p2Node = opCode.Pred39(); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(P0Node, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(p0Node, op))); - ShaderIrInst LopInst = OpCode.BLop45(); + ShaderIrInst lopInst = opCode.BLop45(); - if (LopInst == ShaderIrInst.Band && P1Node.IsConst && P2Node.IsConst) + if (lopInst == ShaderIrInst.Band && p1Node.IsConst && p2Node.IsConst) { return; } - ShaderIrNode P2NNode = P2Node; + ShaderIrNode p2NNode = p2Node; - if (NegP) + if (negP) { - P2NNode = new ShaderIrOp(ShaderIrInst.Bnot, P2NNode); + p2NNode = new ShaderIrOp(ShaderIrInst.Bnot, p2NNode); } - Op = new ShaderIrOp(ShaderIrInst.Bnot, P0Node); + op = new ShaderIrOp(ShaderIrInst.Bnot, p0Node); - Op = new ShaderIrOp(LopInst, Op, P2NNode); + op = new ShaderIrOp(lopInst, op, p2NNode); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(P1Node, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(p1Node, op))); - Op = new ShaderIrOp(LopInst, P0Node, P2NNode); + op = new ShaderIrOp(lopInst, p0Node, p2NNode); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(P0Node, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(p0Node, op))); } - private static void EmitBinaryHalfOp(ShaderIrBlock Block, long OpCode, ShaderIrInst Inst) + private static void EmitBinaryHalfOp(ShaderIrBlock block, long opCode, ShaderIrInst inst) { - bool AbsB = OpCode.Read(30); - bool NegB = OpCode.Read(31); - bool Sat = OpCode.Read(32); - bool AbsA = OpCode.Read(44); + bool absB = opCode.Read(30); + bool negB = opCode.Read(31); + bool sat = opCode.Read(32); + bool absA = opCode.Read(44); - ShaderIrOperGpr[] VecA = OpCode.GprHalfVec8(); - ShaderIrOperGpr[] VecB = OpCode.GprHalfVec20(); + ShaderIrOperGpr[] vecA = opCode.GprHalfVec8(); + ShaderIrOperGpr[] vecB = opCode.GprHalfVec20(); - HalfOutputType OutputType = (HalfOutputType)OpCode.Read(49, 3); + HalfOutputType outputType = (HalfOutputType)opCode.Read(49, 3); - int Elems = OutputType == HalfOutputType.PackedFp16 ? 2 : 1; - int First = OutputType == HalfOutputType.MergeH1 ? 1 : 0; + int elems = outputType == HalfOutputType.PackedFp16 ? 2 : 1; + int first = outputType == HalfOutputType.MergeH1 ? 1 : 0; - for (int Index = First; Index < Elems; Index++) + for (int index = first; index < elems; index++) { - ShaderIrNode OperA = GetAluFabs (VecA[Index], AbsA); - ShaderIrNode OperB = GetAluFabsFneg(VecB[Index], AbsB, NegB); + ShaderIrNode operA = GetAluFabs (vecA[index], absA); + ShaderIrNode operB = GetAluFabsFneg(vecB[index], absB, negB); - ShaderIrNode Op = new ShaderIrOp(Inst, OperA, OperB); + ShaderIrNode op = new ShaderIrOp(inst, operA, operB); - ShaderIrOperGpr Dst = GetHalfDst(OpCode, OutputType, Index); + ShaderIrOperGpr dst = GetHalfDst(opCode, outputType, index); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(Dst, GetAluFsat(Op, Sat)))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(dst, GetAluFsat(op, sat)))); } } - private static ShaderIrOperGpr GetHalfDst(long OpCode, HalfOutputType OutputType, int Index) + private static ShaderIrOperGpr GetHalfDst(long opCode, HalfOutputType outputType, int index) { - switch (OutputType) + switch (outputType) { - case HalfOutputType.PackedFp16: return OpCode.GprHalf0(Index); - case HalfOutputType.Fp32: return OpCode.Gpr0(); - case HalfOutputType.MergeH0: return OpCode.GprHalf0(0); - case HalfOutputType.MergeH1: return OpCode.GprHalf0(1); + case HalfOutputType.PackedFp16: return opCode.GprHalf0(index); + case HalfOutputType.Fp32: return opCode.Gpr0(); + case HalfOutputType.MergeH0: return opCode.GprHalf0(0); + case HalfOutputType.MergeH1: return opCode.GprHalf0(1); } - throw new ArgumentException(nameof(OutputType)); + throw new ArgumentException(nameof(outputType)); } - private static void EmitLop(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitLop(ShaderIrBlock block, long opCode, ShaderOper oper) { - int SubOp = OpCode.Read(41, 3); + int subOp = opCode.Read(41, 3); - bool InvA = OpCode.Read(39); - bool InvB = OpCode.Read(40); + bool invA = opCode.Read(39); + bool invB = opCode.Read(40); - ShaderIrInst Inst = 0; + ShaderIrInst inst = 0; - switch (SubOp) + switch (subOp) { - case 0: Inst = ShaderIrInst.And; break; - case 1: Inst = ShaderIrInst.Or; break; - case 2: Inst = ShaderIrInst.Xor; break; + case 0: inst = ShaderIrInst.And; break; + case 1: inst = ShaderIrInst.Or; break; + case 2: inst = ShaderIrInst.Xor; break; } - ShaderIrNode OperA = GetAluNot(OpCode.Gpr8(), InvA); - ShaderIrNode OperB; + ShaderIrNode operA = GetAluNot(opCode.Gpr8(), invA); + ShaderIrNode operB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.Imm19_20(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.Imm19_20(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperB = GetAluNot(OperB, InvB); + operB = GetAluNot(operB, invB); - ShaderIrNode Op; + ShaderIrNode op; - if (SubOp < 3) + if (subOp < 3) { - Op = new ShaderIrOp(Inst, OperA, OperB); + op = new ShaderIrOp(inst, operA, operB); } else { - Op = OperB; + op = operB; } - ShaderIrNode Compare = new ShaderIrOp(ShaderIrInst.Cne, Op, new ShaderIrOperImm(0)); + ShaderIrNode compare = new ShaderIrOp(ShaderIrInst.Cne, op, new ShaderIrOperImm(0)); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Pred48(), Compare))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Pred48(), compare))); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } private enum XmadMode @@ -1157,143 +1157,143 @@ namespace Ryujinx.Graphics.Gal.Shader Cbcc = 4 } - private static void EmitXmad(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitXmad(ShaderIrBlock block, long opCode, ShaderOper oper) { - bool SignedA = OpCode.Read(48); - bool SignedB = OpCode.Read(49); - bool HighB = OpCode.Read(52); - bool HighA = OpCode.Read(53); + bool signedA = opCode.Read(48); + bool signedB = opCode.Read(49); + bool highB = opCode.Read(52); + bool highA = opCode.Read(53); - int Mode = OpCode.Read(50, 7); + int mode = opCode.Read(50, 7); - ShaderIrNode OperA = OpCode.Gpr8(), OperB, OperC; + ShaderIrNode operA = opCode.Gpr8(), operB, operC; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperB = OpCode.ImmU16_20(); break; - case ShaderOper.RC: OperB = OpCode.Gpr39(); break; - case ShaderOper.RR: OperB = OpCode.Gpr20(); break; + case ShaderOper.Cr: operB = opCode.Cbuf34(); break; + case ShaderOper.Imm: operB = opCode.ImmU16_20(); break; + case ShaderOper.Rc: operB = opCode.Gpr39(); break; + case ShaderOper.Rr: operB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - ShaderIrNode OperB2 = OperB; + ShaderIrNode operB2 = operB; - if (Oper == ShaderOper.Imm) + if (oper == ShaderOper.Imm) { - int Imm = ((ShaderIrOperImm)OperB2).Value; + int imm = ((ShaderIrOperImm)operB2).Value; - if (!HighB) + if (!highB) { - Imm <<= 16; + imm <<= 16; } - if (SignedB) + if (signedB) { - Imm >>= 16; + imm >>= 16; } else { - Imm = (int)((uint)Imm >> 16); + imm = (int)((uint)imm >> 16); } - OperB2 = new ShaderIrOperImm(Imm); + operB2 = new ShaderIrOperImm(imm); } - ShaderIrOperImm Imm16 = new ShaderIrOperImm(16); + ShaderIrOperImm imm16 = new ShaderIrOperImm(16); //If we are working with the lower 16-bits of the A/B operands, //we need to shift the lower 16-bits to the top 16-bits. Later, //they will be right shifted. For U16 types, this will be a logical //right shift, and for S16 types, a arithmetic right shift. - if (!HighA) + if (!highA) { - OperA = new ShaderIrOp(ShaderIrInst.Lsl, OperA, Imm16); + operA = new ShaderIrOp(ShaderIrInst.Lsl, operA, imm16); } - if (!HighB && Oper != ShaderOper.Imm) + if (!highB && oper != ShaderOper.Imm) { - OperB2 = new ShaderIrOp(ShaderIrInst.Lsl, OperB2, Imm16); + operB2 = new ShaderIrOp(ShaderIrInst.Lsl, operB2, imm16); } - ShaderIrInst ShiftA = SignedA ? ShaderIrInst.Asr : ShaderIrInst.Lsr; - ShaderIrInst ShiftB = SignedB ? ShaderIrInst.Asr : ShaderIrInst.Lsr; + ShaderIrInst shiftA = signedA ? ShaderIrInst.Asr : ShaderIrInst.Lsr; + ShaderIrInst shiftB = signedB ? ShaderIrInst.Asr : ShaderIrInst.Lsr; - OperA = new ShaderIrOp(ShiftA, OperA, Imm16); + operA = new ShaderIrOp(shiftA, operA, imm16); - if (Oper != ShaderOper.Imm) + if (oper != ShaderOper.Imm) { - OperB2 = new ShaderIrOp(ShiftB, OperB2, Imm16); + operB2 = new ShaderIrOp(shiftB, operB2, imm16); } - bool ProductShiftLeft = false; - bool Merge = false; + bool productShiftLeft = false; + bool merge = false; - if (Oper == ShaderOper.RC) + if (oper == ShaderOper.Rc) { - OperC = OpCode.Cbuf34(); + operC = opCode.Cbuf34(); } else { - OperC = OpCode.Gpr39(); + operC = opCode.Gpr39(); - ProductShiftLeft = OpCode.Read(36); - Merge = OpCode.Read(37); + productShiftLeft = opCode.Read(36); + merge = opCode.Read(37); } - ShaderIrOp MulOp = new ShaderIrOp(ShaderIrInst.Mul, OperA, OperB2); + ShaderIrOp mulOp = new ShaderIrOp(ShaderIrInst.Mul, operA, operB2); - if (ProductShiftLeft) + if (productShiftLeft) { - MulOp = new ShaderIrOp(ShaderIrInst.Lsl, MulOp, Imm16); + mulOp = new ShaderIrOp(ShaderIrInst.Lsl, mulOp, imm16); } - switch ((XmadMode)Mode) + switch ((XmadMode)mode) { - case XmadMode.Clo: OperC = ExtendTo32(OperC, Signed: false, Size: 16); break; + case XmadMode.Clo: operC = ExtendTo32(operC, signed: false, size: 16); break; - case XmadMode.Chi: OperC = new ShaderIrOp(ShaderIrInst.Lsr, OperC, Imm16); break; + case XmadMode.Chi: operC = new ShaderIrOp(ShaderIrInst.Lsr, operC, imm16); break; case XmadMode.Cbcc: { - ShaderIrOp OperBLsh16 = new ShaderIrOp(ShaderIrInst.Lsl, OperB, Imm16); + ShaderIrOp operBLsh16 = new ShaderIrOp(ShaderIrInst.Lsl, operB, imm16); - OperC = new ShaderIrOp(ShaderIrInst.Add, OperC, OperBLsh16); + operC = new ShaderIrOp(ShaderIrInst.Add, operC, operBLsh16); break; } case XmadMode.Csfu: { - ShaderIrOperImm Imm31 = new ShaderIrOperImm(31); + ShaderIrOperImm imm31 = new ShaderIrOperImm(31); - ShaderIrOp SignAdjustA = new ShaderIrOp(ShaderIrInst.Lsr, OperA, Imm31); - ShaderIrOp SignAdjustB = new ShaderIrOp(ShaderIrInst.Lsr, OperB2, Imm31); + ShaderIrOp signAdjustA = new ShaderIrOp(ShaderIrInst.Lsr, operA, imm31); + ShaderIrOp signAdjustB = new ShaderIrOp(ShaderIrInst.Lsr, operB2, imm31); - SignAdjustA = new ShaderIrOp(ShaderIrInst.Lsl, SignAdjustA, Imm16); - SignAdjustB = new ShaderIrOp(ShaderIrInst.Lsl, SignAdjustB, Imm16); + signAdjustA = new ShaderIrOp(ShaderIrInst.Lsl, signAdjustA, imm16); + signAdjustB = new ShaderIrOp(ShaderIrInst.Lsl, signAdjustB, imm16); - ShaderIrOp SignAdjust = new ShaderIrOp(ShaderIrInst.Add, SignAdjustA, SignAdjustB); + ShaderIrOp signAdjust = new ShaderIrOp(ShaderIrInst.Add, signAdjustA, signAdjustB); - OperC = new ShaderIrOp(ShaderIrInst.Sub, OperC, SignAdjust); + operC = new ShaderIrOp(ShaderIrInst.Sub, operC, signAdjust); break; } } - ShaderIrOp AddOp = new ShaderIrOp(ShaderIrInst.Add, MulOp, OperC); + ShaderIrOp addOp = new ShaderIrOp(ShaderIrInst.Add, mulOp, operC); - if (Merge) + if (merge) { - ShaderIrOperImm Imm16Mask = new ShaderIrOperImm(0xffff); + ShaderIrOperImm imm16Mask = new ShaderIrOperImm(0xffff); - AddOp = new ShaderIrOp(ShaderIrInst.And, AddOp, Imm16Mask); - OperB = new ShaderIrOp(ShaderIrInst.Lsl, OperB, Imm16); - AddOp = new ShaderIrOp(ShaderIrInst.Or, AddOp, OperB); + addOp = new ShaderIrOp(ShaderIrInst.And, addOp, imm16Mask); + operB = new ShaderIrOp(ShaderIrInst.Lsl, operB, imm16); + addOp = new ShaderIrOp(ShaderIrInst.Or, addOp, operB); } - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), AddOp))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), addOp))); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFlow.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFlow.cs index bc2539bd..fc992693 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFlow.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFlow.cs @@ -4,54 +4,54 @@ namespace Ryujinx.Graphics.Gal.Shader { static partial class ShaderDecode { - public static void Bra(ShaderIrBlock Block, long OpCode, int Position) + public static void Bra(ShaderIrBlock block, long opCode, int position) { - if ((OpCode & 0x20) != 0) + if ((opCode & 0x20) != 0) { //This reads the target offset from the constant buffer. //Almost impossible to support with GLSL. throw new NotImplementedException(); } - ShaderIrOperImm Imm = new ShaderIrOperImm(Position + OpCode.Branch()); + ShaderIrOperImm imm = new ShaderIrOperImm(position + opCode.Branch()); - Block.AddNode(OpCode.PredNode(new ShaderIrOp(ShaderIrInst.Bra, Imm))); + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Bra, imm))); } - public static void Exit(ShaderIrBlock Block, long OpCode, int Position) + public static void Exit(ShaderIrBlock block, long opCode, int position) { - int CCode = (int)OpCode & 0x1f; + int cCode = (int)opCode & 0x1f; //TODO: Figure out what the other condition codes mean... - if (CCode == 0xf) + if (cCode == 0xf) { - Block.AddNode(OpCode.PredNode(new ShaderIrOp(ShaderIrInst.Exit))); + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Exit))); } } - public static void Kil(ShaderIrBlock Block, long OpCode, int Position) + public static void Kil(ShaderIrBlock block, long opCode, int position) { - Block.AddNode(OpCode.PredNode(new ShaderIrOp(ShaderIrInst.Kil))); + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Kil))); } - public static void Ssy(ShaderIrBlock Block, long OpCode, int Position) + public static void Ssy(ShaderIrBlock block, long opCode, int position) { - if ((OpCode & 0x20) != 0) + if ((opCode & 0x20) != 0) { //This reads the target offset from the constant buffer. //Almost impossible to support with GLSL. throw new NotImplementedException(); } - ShaderIrOperImm Imm = new ShaderIrOperImm(Position + OpCode.Branch()); + ShaderIrOperImm imm = new ShaderIrOperImm(position + opCode.Branch()); - Block.AddNode(new ShaderIrOp(ShaderIrInst.Ssy, Imm)); + block.AddNode(new ShaderIrOp(ShaderIrInst.Ssy, imm)); } - public static void Sync(ShaderIrBlock Block, long OpCode, int Position) + public static void Sync(ShaderIrBlock block, long opCode, int position) { //TODO: Implement Sync condition codes - Block.AddNode(OpCode.PredNode(new ShaderIrOp(ShaderIrInst.Sync))); + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Sync))); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFunc.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFunc.cs index 73248aa0..cc385aa4 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFunc.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFunc.cs @@ -1,4 +1,4 @@ namespace Ryujinx.Graphics.Gal.Shader { - delegate void ShaderDecodeFunc(ShaderIrBlock Block, long OpCode, int Position); + delegate void ShaderDecodeFunc(ShaderIrBlock block, long opCode, int position); } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeHelper.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeHelper.cs index d07bcd91..9a84e612 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeHelper.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeHelper.cs @@ -5,74 +5,74 @@ namespace Ryujinx.Graphics.Gal.Shader private static readonly ShaderIrOperImmf ImmfZero = new ShaderIrOperImmf(0); private static readonly ShaderIrOperImmf ImmfOne = new ShaderIrOperImmf(1); - public static ShaderIrNode GetAluFabsFneg(ShaderIrNode Node, bool Abs, bool Neg) + public static ShaderIrNode GetAluFabsFneg(ShaderIrNode node, bool abs, bool neg) { - return GetAluFneg(GetAluFabs(Node, Abs), Neg); + return GetAluFneg(GetAluFabs(node, abs), neg); } - public static ShaderIrNode GetAluFabs(ShaderIrNode Node, bool Abs) + public static ShaderIrNode GetAluFabs(ShaderIrNode node, bool abs) { - return Abs ? new ShaderIrOp(ShaderIrInst.Fabs, Node) : Node; + return abs ? new ShaderIrOp(ShaderIrInst.Fabs, node) : node; } - public static ShaderIrNode GetAluFneg(ShaderIrNode Node, bool Neg) + public static ShaderIrNode GetAluFneg(ShaderIrNode node, bool neg) { - return Neg ? new ShaderIrOp(ShaderIrInst.Fneg, Node) : Node; + return neg ? new ShaderIrOp(ShaderIrInst.Fneg, node) : node; } - public static ShaderIrNode GetAluFsat(ShaderIrNode Node, bool Sat) + public static ShaderIrNode GetAluFsat(ShaderIrNode node, bool sat) { - return Sat ? new ShaderIrOp(ShaderIrInst.Fclamp, Node, ImmfZero, ImmfOne) : Node; + return sat ? new ShaderIrOp(ShaderIrInst.Fclamp, node, ImmfZero, ImmfOne) : node; } - public static ShaderIrNode GetAluIabsIneg(ShaderIrNode Node, bool Abs, bool Neg) + public static ShaderIrNode GetAluIabsIneg(ShaderIrNode node, bool abs, bool neg) { - return GetAluIneg(GetAluIabs(Node, Abs), Neg); + return GetAluIneg(GetAluIabs(node, abs), neg); } - public static ShaderIrNode GetAluIabs(ShaderIrNode Node, bool Abs) + public static ShaderIrNode GetAluIabs(ShaderIrNode node, bool abs) { - return Abs ? new ShaderIrOp(ShaderIrInst.Abs, Node) : Node; + return abs ? new ShaderIrOp(ShaderIrInst.Abs, node) : node; } - public static ShaderIrNode GetAluIneg(ShaderIrNode Node, bool Neg) + public static ShaderIrNode GetAluIneg(ShaderIrNode node, bool neg) { - return Neg ? new ShaderIrOp(ShaderIrInst.Neg, Node) : Node; + return neg ? new ShaderIrOp(ShaderIrInst.Neg, node) : node; } - public static ShaderIrNode GetAluNot(ShaderIrNode Node, bool Not) + public static ShaderIrNode GetAluNot(ShaderIrNode node, bool not) { - return Not ? new ShaderIrOp(ShaderIrInst.Not, Node) : Node; + return not ? new ShaderIrOp(ShaderIrInst.Not, node) : node; } - public static ShaderIrNode ExtendTo32(ShaderIrNode Node, bool Signed, int Size) + public static ShaderIrNode ExtendTo32(ShaderIrNode node, bool signed, int size) { - int Shift = 32 - Size; + int shift = 32 - size; - ShaderIrInst RightShift = Signed + ShaderIrInst rightShift = signed ? ShaderIrInst.Asr : ShaderIrInst.Lsr; - Node = new ShaderIrOp(ShaderIrInst.Lsl, Node, new ShaderIrOperImm(Shift)); - Node = new ShaderIrOp(RightShift, Node, new ShaderIrOperImm(Shift)); + node = new ShaderIrOp(ShaderIrInst.Lsl, node, new ShaderIrOperImm(shift)); + node = new ShaderIrOp(rightShift, node, new ShaderIrOperImm(shift)); - return Node; + return node; } - public static ShaderIrNode ExtendTo32(ShaderIrNode Node, bool Signed, ShaderIrNode Size) + public static ShaderIrNode ExtendTo32(ShaderIrNode node, bool signed, ShaderIrNode size) { - ShaderIrOperImm WordSize = new ShaderIrOperImm(32); + ShaderIrOperImm wordSize = new ShaderIrOperImm(32); - ShaderIrOp Shift = new ShaderIrOp(ShaderIrInst.Sub, WordSize, Size); + ShaderIrOp shift = new ShaderIrOp(ShaderIrInst.Sub, wordSize, size); - ShaderIrInst RightShift = Signed + ShaderIrInst rightShift = signed ? ShaderIrInst.Asr : ShaderIrInst.Lsr; - Node = new ShaderIrOp(ShaderIrInst.Lsl, Node, Shift); - Node = new ShaderIrOp(RightShift, Node, Shift); + node = new ShaderIrOp(ShaderIrInst.Lsl, node, shift); + node = new ShaderIrOp(rightShift, node, shift); - return Node; + return node; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMem.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMem.cs index 8b4eacdf..7ce126b0 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMem.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMem.cs @@ -7,6 +7,7 @@ namespace Ryujinx.Graphics.Gal.Shader { static partial class ShaderDecode { + // ReSharper disable InconsistentNaming private const int ____ = 0x0; private const int R___ = 0x1; private const int _G__ = 0x2; @@ -21,8 +22,9 @@ namespace Ryujinx.Graphics.Gal.Shader private const int R_BA = 0xd; private const int _GBA = 0xe; private const int RGBA = 0xf; + // ReSharper restore InconsistentNaming - private static int[,] MaskLut = new int[,] + private static int[,] _maskLut = new int[,] { { ____, ____, ____, ____, ____, ____, ____, ____ }, { R___, _G__, __B_, ___A, RG__, R__A, _G_A, __BA }, @@ -30,28 +32,28 @@ namespace Ryujinx.Graphics.Gal.Shader { RGB_, RG_A, R_BA, _GBA, RGBA, ____, ____, ____ } }; - private static GalTextureTarget TexToTextureTarget(int TexType, bool IsArray) + private static GalTextureTarget TexToTextureTarget(int texType, bool isArray) { - switch (TexType) + switch (texType) { case 0: - return IsArray ? GalTextureTarget.OneDArray : GalTextureTarget.OneD; + return isArray ? GalTextureTarget.OneDArray : GalTextureTarget.OneD; case 2: - return IsArray ? GalTextureTarget.TwoDArray : GalTextureTarget.TwoD; + return isArray ? GalTextureTarget.TwoDArray : GalTextureTarget.TwoD; case 4: - if (IsArray) - throw new InvalidOperationException($"ARRAY bit set on a TEX with 3D texture!"); + if (isArray) + throw new InvalidOperationException("ARRAY bit set on a TEX with 3D texture!"); return GalTextureTarget.ThreeD; case 6: - return IsArray ? GalTextureTarget.CubeArray : GalTextureTarget.CubeMap; + return isArray ? GalTextureTarget.CubeArray : GalTextureTarget.CubeMap; default: throw new InvalidOperationException(); } } - private static GalTextureTarget TexsToTextureTarget(int TexType) + private static GalTextureTarget TexsToTextureTarget(int texType) { - switch (TexType) + switch (texType) { case 0: return GalTextureTarget.OneD; @@ -77,9 +79,9 @@ namespace Ryujinx.Graphics.Gal.Shader } } - public static GalTextureTarget TldsToTextureTarget(int TexType) + public static GalTextureTarget TldsToTextureTarget(int texType) { - switch (TexType) + switch (texType) { case 0: case 2: @@ -99,566 +101,566 @@ namespace Ryujinx.Graphics.Gal.Shader } } - public static void Ld_A(ShaderIrBlock Block, long OpCode, int Position) + public static void Ld_A(ShaderIrBlock block, long opCode, int position) { - ShaderIrNode[] Opers = OpCode.Abuf20(); + ShaderIrNode[] opers = opCode.Abuf20(); //Used by GS - ShaderIrOperGpr Vertex = OpCode.Gpr39(); + ShaderIrOperGpr vertex = opCode.Gpr39(); - int Index = 0; + int index = 0; - foreach (ShaderIrNode OperA in Opers) + foreach (ShaderIrNode operA in opers) { - ShaderIrOperGpr OperD = OpCode.Gpr0(); + ShaderIrOperGpr operD = opCode.Gpr0(); - OperD.Index += Index++; + operD.Index += index++; - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OperD, OperA))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(operD, operA))); } } - public static void Ld_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Ld_C(ShaderIrBlock block, long opCode, int position) { - int CbufPos = OpCode.Read(22, 0x3fff); - int CbufIndex = OpCode.Read(36, 0x1f); - int Type = OpCode.Read(48, 7); + int cbufPos = opCode.Read(22, 0x3fff); + int cbufIndex = opCode.Read(36, 0x1f); + int type = opCode.Read(48, 7); - if (Type > 5) + if (type > 5) { throw new InvalidOperationException(); } - ShaderIrOperGpr Temp = ShaderIrOperGpr.MakeTemporary(); + ShaderIrOperGpr temp = ShaderIrOperGpr.MakeTemporary(); - Block.AddNode(new ShaderIrAsg(Temp, OpCode.Gpr8())); + block.AddNode(new ShaderIrAsg(temp, opCode.Gpr8())); - int Count = Type == 5 ? 2 : 1; + int count = type == 5 ? 2 : 1; - for (int Index = 0; Index < Count; Index++) + for (int index = 0; index < count; index++) { - ShaderIrOperCbuf OperA = new ShaderIrOperCbuf(CbufIndex, CbufPos, Temp); + ShaderIrOperCbuf operA = new ShaderIrOperCbuf(cbufIndex, cbufPos, temp); - ShaderIrOperGpr OperD = OpCode.Gpr0(); + ShaderIrOperGpr operD = opCode.Gpr0(); - OperA.Pos += Index; - OperD.Index += Index; + operA.Pos += index; + operD.Index += index; - if (!OperD.IsValidRegister) + if (!operD.IsValidRegister) { break; } - ShaderIrNode Node = OperA; + ShaderIrNode node = operA; - if (Type < 4) + if (type < 4) { //This is a 8 or 16 bits type. - bool Signed = (Type & 1) != 0; + bool signed = (type & 1) != 0; - int Size = 8 << (Type >> 1); + int size = 8 << (type >> 1); - Node = ExtendTo32(Node, Signed, Size); + node = ExtendTo32(node, signed, size); } - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OperD, Node))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(operD, node))); } } - public static void St_A(ShaderIrBlock Block, long OpCode, int Position) + public static void St_A(ShaderIrBlock block, long opCode, int position) { - ShaderIrNode[] Opers = OpCode.Abuf20(); + ShaderIrNode[] opers = opCode.Abuf20(); - int Index = 0; + int index = 0; - foreach (ShaderIrNode OperA in Opers) + foreach (ShaderIrNode operA in opers) { - ShaderIrOperGpr OperD = OpCode.Gpr0(); + ShaderIrOperGpr operD = opCode.Gpr0(); - OperD.Index += Index++; + operD.Index += index++; - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OperA, OperD))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(operA, operD))); } } - public static void Texq(ShaderIrBlock Block, long OpCode, int Position) + public static void Texq(ShaderIrBlock block, long opCode, int position) { - ShaderIrNode OperD = OpCode.Gpr0(); - ShaderIrNode OperA = OpCode.Gpr8(); + ShaderIrNode operD = opCode.Gpr0(); + ShaderIrNode operA = opCode.Gpr8(); - ShaderTexqInfo Info = (ShaderTexqInfo)(OpCode.Read(22, 0x1f)); + ShaderTexqInfo info = (ShaderTexqInfo)(opCode.Read(22, 0x1f)); - ShaderIrMetaTexq Meta0 = new ShaderIrMetaTexq(Info, 0); - ShaderIrMetaTexq Meta1 = new ShaderIrMetaTexq(Info, 1); + ShaderIrMetaTexq meta0 = new ShaderIrMetaTexq(info, 0); + ShaderIrMetaTexq meta1 = new ShaderIrMetaTexq(info, 1); - ShaderIrNode OperC = OpCode.Imm13_36(); + ShaderIrNode operC = opCode.Imm13_36(); - ShaderIrOp Op0 = new ShaderIrOp(ShaderIrInst.Texq, OperA, null, OperC, Meta0); - ShaderIrOp Op1 = new ShaderIrOp(ShaderIrInst.Texq, OperA, null, OperC, Meta1); + ShaderIrOp op0 = new ShaderIrOp(ShaderIrInst.Texq, operA, null, operC, meta0); + ShaderIrOp op1 = new ShaderIrOp(ShaderIrInst.Texq, operA, null, operC, meta1); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OperD, Op0))); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OperA, Op1))); //Is this right? + block.AddNode(opCode.PredNode(new ShaderIrAsg(operD, op0))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(operA, op1))); //Is this right? } - public static void Tex(ShaderIrBlock Block, long OpCode, int Position) + public static void Tex(ShaderIrBlock block, long opCode, int position) { - TextureInstructionSuffix Suffix; + TextureInstructionSuffix suffix; - int RawSuffix = OpCode.Read(0x34, 0x38); + int rawSuffix = opCode.Read(0x34, 0x38); - switch (RawSuffix) + switch (rawSuffix) { case 0: - Suffix = TextureInstructionSuffix.None; + suffix = TextureInstructionSuffix.None; break; case 0x8: - Suffix = TextureInstructionSuffix.LZ; + suffix = TextureInstructionSuffix.Lz; break; case 0x10: - Suffix = TextureInstructionSuffix.LB; + suffix = TextureInstructionSuffix.Lb; break; case 0x18: - Suffix = TextureInstructionSuffix.LL; + suffix = TextureInstructionSuffix.Ll; break; case 0x30: - Suffix = TextureInstructionSuffix.LBA; + suffix = TextureInstructionSuffix.Lba; break; case 0x38: - Suffix = TextureInstructionSuffix.LLA; + suffix = TextureInstructionSuffix.Lla; break; default: - throw new InvalidOperationException($"Invalid Suffix for TEX instruction {RawSuffix}"); + throw new InvalidOperationException($"Invalid Suffix for TEX instruction {rawSuffix}"); } - bool IsOffset = OpCode.Read(0x36); + bool isOffset = opCode.Read(0x36); - if (IsOffset) - Suffix |= TextureInstructionSuffix.AOffI; + if (isOffset) + suffix |= TextureInstructionSuffix.AOffI; - EmitTex(Block, OpCode, Suffix, GprHandle: false); + EmitTex(block, opCode, suffix, gprHandle: false); } - public static void Tex_B(ShaderIrBlock Block, long OpCode, int Position) + public static void Tex_B(ShaderIrBlock block, long opCode, int position) { - TextureInstructionSuffix Suffix; + TextureInstructionSuffix suffix; - int RawSuffix = OpCode.Read(0x24, 0xe); + int rawSuffix = opCode.Read(0x24, 0xe); - switch (RawSuffix) + switch (rawSuffix) { case 0: - Suffix = TextureInstructionSuffix.None; + suffix = TextureInstructionSuffix.None; break; case 0x2: - Suffix = TextureInstructionSuffix.LZ; + suffix = TextureInstructionSuffix.Lz; break; case 0x4: - Suffix = TextureInstructionSuffix.LB; + suffix = TextureInstructionSuffix.Lb; break; case 0x6: - Suffix = TextureInstructionSuffix.LL; + suffix = TextureInstructionSuffix.Ll; break; case 0xc: - Suffix = TextureInstructionSuffix.LBA; + suffix = TextureInstructionSuffix.Lba; break; case 0xe: - Suffix = TextureInstructionSuffix.LLA; + suffix = TextureInstructionSuffix.Lla; break; default: - throw new InvalidOperationException($"Invalid Suffix for TEX.B instruction {RawSuffix}"); + throw new InvalidOperationException($"Invalid Suffix for TEX.B instruction {rawSuffix}"); } - bool IsOffset = OpCode.Read(0x23); + bool isOffset = opCode.Read(0x23); - if (IsOffset) - Suffix |= TextureInstructionSuffix.AOffI; + if (isOffset) + suffix |= TextureInstructionSuffix.AOffI; - EmitTex(Block, OpCode, Suffix, GprHandle: true); + EmitTex(block, opCode, suffix, gprHandle: true); } - private static void EmitTex(ShaderIrBlock Block, long OpCode, TextureInstructionSuffix TextureInstructionSuffix, bool GprHandle) + private static void EmitTex(ShaderIrBlock block, long opCode, TextureInstructionSuffix textureInstructionSuffix, bool gprHandle) { - bool IsArray = OpCode.HasArray(); + bool isArray = opCode.HasArray(); - GalTextureTarget TextureTarget = TexToTextureTarget(OpCode.Read(28, 6), IsArray); + GalTextureTarget textureTarget = TexToTextureTarget(opCode.Read(28, 6), isArray); - bool HasDepthCompare = OpCode.Read(0x32); + bool hasDepthCompare = opCode.Read(0x32); - if (HasDepthCompare) + if (hasDepthCompare) { - TextureInstructionSuffix |= TextureInstructionSuffix.DC; + textureInstructionSuffix |= TextureInstructionSuffix.Dc; } - ShaderIrOperGpr[] Coords = new ShaderIrOperGpr[ImageUtils.GetCoordsCountTextureTarget(TextureTarget)]; + ShaderIrOperGpr[] coords = new ShaderIrOperGpr[ImageUtils.GetCoordsCountTextureTarget(textureTarget)]; - int IndexExtraCoord = 0; + int indexExtraCoord = 0; - if (IsArray) + if (isArray) { - IndexExtraCoord++; + indexExtraCoord++; - Coords[Coords.Length - 1] = OpCode.Gpr8(); + coords[coords.Length - 1] = opCode.Gpr8(); } - for (int Index = 0; Index < Coords.Length - IndexExtraCoord; Index++) + for (int index = 0; index < coords.Length - indexExtraCoord; index++) { - ShaderIrOperGpr CoordReg = OpCode.Gpr8(); + ShaderIrOperGpr coordReg = opCode.Gpr8(); - CoordReg.Index += Index; + coordReg.Index += index; - CoordReg.Index += IndexExtraCoord; + coordReg.Index += indexExtraCoord; - if (!CoordReg.IsValidRegister) + if (!coordReg.IsValidRegister) { - CoordReg.Index = ShaderIrOperGpr.ZRIndex; + coordReg.Index = ShaderIrOperGpr.ZrIndex; } - Coords[Index] = CoordReg; + coords[index] = coordReg; } - int ChMask = OpCode.Read(31, 0xf); + int chMask = opCode.Read(31, 0xf); - ShaderIrOperGpr LevelOfDetail = null; - ShaderIrOperGpr Offset = null; - ShaderIrOperGpr DepthCompare = null; + ShaderIrOperGpr levelOfDetail = null; + ShaderIrOperGpr offset = null; + ShaderIrOperGpr depthCompare = null; // TODO: determine first argument when TEX.B is used - int OperBIndex = GprHandle ? 1 : 0; + int operBIndex = gprHandle ? 1 : 0; - if ((TextureInstructionSuffix & TextureInstructionSuffix.LL) != 0 || - (TextureInstructionSuffix & TextureInstructionSuffix.LB) != 0 || - (TextureInstructionSuffix & TextureInstructionSuffix.LBA) != 0 || - (TextureInstructionSuffix & TextureInstructionSuffix.LLA) != 0) + if ((textureInstructionSuffix & TextureInstructionSuffix.Ll) != 0 || + (textureInstructionSuffix & TextureInstructionSuffix.Lb) != 0 || + (textureInstructionSuffix & TextureInstructionSuffix.Lba) != 0 || + (textureInstructionSuffix & TextureInstructionSuffix.Lla) != 0) { - LevelOfDetail = OpCode.Gpr20(); - LevelOfDetail.Index += OperBIndex; + levelOfDetail = opCode.Gpr20(); + levelOfDetail.Index += operBIndex; - OperBIndex++; + operBIndex++; } - if ((TextureInstructionSuffix & TextureInstructionSuffix.AOffI) != 0) + if ((textureInstructionSuffix & TextureInstructionSuffix.AOffI) != 0) { - Offset = OpCode.Gpr20(); - Offset.Index += OperBIndex; + offset = opCode.Gpr20(); + offset.Index += operBIndex; - OperBIndex++; + operBIndex++; } - if ((TextureInstructionSuffix & TextureInstructionSuffix.DC) != 0) + if ((textureInstructionSuffix & TextureInstructionSuffix.Dc) != 0) { - DepthCompare = OpCode.Gpr20(); - DepthCompare.Index += OperBIndex; + depthCompare = opCode.Gpr20(); + depthCompare.Index += operBIndex; - OperBIndex++; + operBIndex++; } // ??? - ShaderIrNode OperC = GprHandle - ? (ShaderIrNode)OpCode.Gpr20() - : (ShaderIrNode)OpCode.Imm13_36(); + ShaderIrNode operC = gprHandle + ? (ShaderIrNode)opCode.Gpr20() + : (ShaderIrNode)opCode.Imm13_36(); - ShaderIrInst Inst = GprHandle ? ShaderIrInst.Texb : ShaderIrInst.Texs; + ShaderIrInst inst = gprHandle ? ShaderIrInst.Texb : ShaderIrInst.Texs; - Coords = CoordsRegistersToTempRegisters(Block, Coords); + coords = CoordsRegistersToTempRegisters(block, coords); - int RegInc = 0; + int regInc = 0; - for (int Ch = 0; Ch < 4; Ch++) + for (int ch = 0; ch < 4; ch++) { - if (!IsChannelUsed(ChMask, Ch)) + if (!IsChannelUsed(chMask, ch)) { continue; } - ShaderIrOperGpr Dst = OpCode.Gpr0(); + ShaderIrOperGpr dst = opCode.Gpr0(); - Dst.Index += RegInc++; + dst.Index += regInc++; - if (!Dst.IsValidRegister || Dst.IsConst) + if (!dst.IsValidRegister || dst.IsConst) { continue; } - ShaderIrMetaTex Meta = new ShaderIrMetaTex(Ch, TextureTarget, TextureInstructionSuffix, Coords) + ShaderIrMetaTex meta = new ShaderIrMetaTex(ch, textureTarget, textureInstructionSuffix, coords) { - LevelOfDetail = LevelOfDetail, - Offset = Offset, - DepthCompare = DepthCompare + LevelOfDetail = levelOfDetail, + Offset = offset, + DepthCompare = depthCompare }; - ShaderIrOp Op = new ShaderIrOp(Inst, Coords[0], Coords.Length > 1 ? Coords[1] : null, OperC, Meta); + ShaderIrOp op = new ShaderIrOp(inst, coords[0], coords.Length > 1 ? coords[1] : null, operC, meta); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(Dst, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(dst, op))); } } - public static void Texs(ShaderIrBlock Block, long OpCode, int Position) + public static void Texs(ShaderIrBlock block, long opCode, int position) { - TextureInstructionSuffix Suffix; + TextureInstructionSuffix suffix; - int RawSuffix = OpCode.Read(0x34, 0x1e); + int rawSuffix = opCode.Read(0x34, 0x1e); - switch (RawSuffix) + switch (rawSuffix) { case 0: case 0x4: case 0x10: case 0x16: - Suffix = TextureInstructionSuffix.LZ; + suffix = TextureInstructionSuffix.Lz; break; case 0x6: case 0x1a: - Suffix = TextureInstructionSuffix.LL; + suffix = TextureInstructionSuffix.Ll; break; case 0x8: - Suffix = TextureInstructionSuffix.DC; + suffix = TextureInstructionSuffix.Dc; break; case 0x2: case 0xe: case 0x14: case 0x18: - Suffix = TextureInstructionSuffix.None; + suffix = TextureInstructionSuffix.None; break; case 0xa: - Suffix = TextureInstructionSuffix.LL | TextureInstructionSuffix.DC; + suffix = TextureInstructionSuffix.Ll | TextureInstructionSuffix.Dc; break; case 0xc: case 0x12: - Suffix = TextureInstructionSuffix.LZ | TextureInstructionSuffix.DC; + suffix = TextureInstructionSuffix.Lz | TextureInstructionSuffix.Dc; break; default: - throw new InvalidOperationException($"Invalid Suffix for TEXS instruction {RawSuffix}"); + throw new InvalidOperationException($"Invalid Suffix for TEXS instruction {rawSuffix}"); } - GalTextureTarget TextureTarget = TexsToTextureTarget(OpCode.Read(52, 0x1e)); + GalTextureTarget textureTarget = TexsToTextureTarget(opCode.Read(52, 0x1e)); - EmitTexs(Block, OpCode, ShaderIrInst.Texs, TextureTarget, Suffix); + EmitTexs(block, opCode, ShaderIrInst.Texs, textureTarget, suffix); } - public static void Tlds(ShaderIrBlock Block, long OpCode, int Position) + public static void Tlds(ShaderIrBlock block, long opCode, int position) { - TextureInstructionSuffix Suffix; + TextureInstructionSuffix suffix; - int RawSuffix = OpCode.Read(0x34, 0x1e); + int rawSuffix = opCode.Read(0x34, 0x1e); - switch (RawSuffix) + switch (rawSuffix) { case 0: case 0x4: case 0x8: - Suffix = TextureInstructionSuffix.LZ | TextureInstructionSuffix.AOffI; + suffix = TextureInstructionSuffix.Lz | TextureInstructionSuffix.AOffI; break; case 0xc: - Suffix = TextureInstructionSuffix.LZ | TextureInstructionSuffix.MZ; + suffix = TextureInstructionSuffix.Lz | TextureInstructionSuffix.Mz; break; case 0xe: case 0x10: - Suffix = TextureInstructionSuffix.LZ; + suffix = TextureInstructionSuffix.Lz; break; case 0x2: case 0xa: - Suffix = TextureInstructionSuffix.LL; + suffix = TextureInstructionSuffix.Ll; break; case 0x18: - Suffix = TextureInstructionSuffix.LL | TextureInstructionSuffix.AOffI; + suffix = TextureInstructionSuffix.Ll | TextureInstructionSuffix.AOffI; break; default: - throw new InvalidOperationException($"Invalid Suffix for TLDS instruction {RawSuffix}"); + throw new InvalidOperationException($"Invalid Suffix for TLDS instruction {rawSuffix}"); } - GalTextureTarget TextureTarget = TldsToTextureTarget(OpCode.Read(52, 0x1e)); + GalTextureTarget textureTarget = TldsToTextureTarget(opCode.Read(52, 0x1e)); - EmitTexs(Block, OpCode, ShaderIrInst.Txlf, TextureTarget, Suffix); + EmitTexs(block, opCode, ShaderIrInst.Txlf, textureTarget, suffix); } - public static void Tld4(ShaderIrBlock Block, long OpCode, int Position) + public static void Tld4(ShaderIrBlock block, long opCode, int position) { - TextureInstructionSuffix Suffix; + TextureInstructionSuffix suffix; - int RawSuffix = OpCode.Read(0x34, 0xc); + int rawSuffix = opCode.Read(0x34, 0xc); - switch (RawSuffix) + switch (rawSuffix) { case 0: - Suffix = TextureInstructionSuffix.None; + suffix = TextureInstructionSuffix.None; break; case 0x4: - Suffix = TextureInstructionSuffix.AOffI; + suffix = TextureInstructionSuffix.AOffI; break; case 0x8: - Suffix = TextureInstructionSuffix.PTP; + suffix = TextureInstructionSuffix.Ptp; break; default: - throw new InvalidOperationException($"Invalid Suffix for TLD4 instruction {RawSuffix}"); + throw new InvalidOperationException($"Invalid Suffix for TLD4 instruction {rawSuffix}"); } - bool IsShadow = OpCode.Read(0x32); + bool isShadow = opCode.Read(0x32); - bool IsArray = OpCode.HasArray(); - int ChMask = OpCode.Read(31, 0xf); + bool isArray = opCode.HasArray(); + int chMask = opCode.Read(31, 0xf); - GalTextureTarget TextureTarget = TexToTextureTarget(OpCode.Read(28, 6), IsArray); + GalTextureTarget textureTarget = TexToTextureTarget(opCode.Read(28, 6), isArray); - if (IsShadow) + if (isShadow) { - Suffix |= TextureInstructionSuffix.DC; + suffix |= TextureInstructionSuffix.Dc; } - EmitTld4(Block, OpCode, TextureTarget, Suffix, ChMask, OpCode.Read(0x38, 0x3), false); + EmitTld4(block, opCode, textureTarget, suffix, chMask, opCode.Read(0x38, 0x3), false); } - public static void Tld4s(ShaderIrBlock Block, long OpCode, int Position) + public static void Tld4S(ShaderIrBlock block, long opCode, int position) { - TextureInstructionSuffix Suffix = TextureInstructionSuffix.None; + TextureInstructionSuffix suffix = TextureInstructionSuffix.None; - bool IsOffset = OpCode.Read(0x33); - bool IsShadow = OpCode.Read(0x32); + bool isOffset = opCode.Read(0x33); + bool isShadow = opCode.Read(0x32); - if (IsOffset) + if (isOffset) { - Suffix |= TextureInstructionSuffix.AOffI; + suffix |= TextureInstructionSuffix.AOffI; } - if (IsShadow) + if (isShadow) { - Suffix |= TextureInstructionSuffix.DC; + suffix |= TextureInstructionSuffix.Dc; } // TLD4S seems to only support 2D textures with RGBA mask? - EmitTld4(Block, OpCode, GalTextureTarget.TwoD, Suffix, RGBA, OpCode.Read(0x34, 0x3), true); + EmitTld4(block, opCode, GalTextureTarget.TwoD, suffix, RGBA, opCode.Read(0x34, 0x3), true); } - private static void EmitTexs(ShaderIrBlock Block, - long OpCode, - ShaderIrInst Inst, - GalTextureTarget TextureTarget, - TextureInstructionSuffix TextureInstructionSuffix) + private static void EmitTexs(ShaderIrBlock block, + long opCode, + ShaderIrInst inst, + GalTextureTarget textureTarget, + TextureInstructionSuffix textureInstructionSuffix) { - if (Inst == ShaderIrInst.Txlf && TextureTarget == GalTextureTarget.CubeArray) + if (inst == ShaderIrInst.Txlf && textureTarget == GalTextureTarget.CubeArray) { throw new InvalidOperationException("TLDS instructions cannot use CUBE modifier!"); } - bool IsArray = ImageUtils.IsArray(TextureTarget); + bool isArray = ImageUtils.IsArray(textureTarget); - ShaderIrOperGpr[] Coords = new ShaderIrOperGpr[ImageUtils.GetCoordsCountTextureTarget(TextureTarget)]; + ShaderIrOperGpr[] coords = new ShaderIrOperGpr[ImageUtils.GetCoordsCountTextureTarget(textureTarget)]; - ShaderIrOperGpr OperA = OpCode.Gpr8(); - ShaderIrOperGpr OperB = OpCode.Gpr20(); + ShaderIrOperGpr operA = opCode.Gpr8(); + ShaderIrOperGpr operB = opCode.Gpr20(); - ShaderIrOperGpr SuffixExtra = OpCode.Gpr20(); - SuffixExtra.Index += 1; + ShaderIrOperGpr suffixExtra = opCode.Gpr20(); + suffixExtra.Index += 1; - int CoordStartIndex = 0; + int coordStartIndex = 0; - if (IsArray) + if (isArray) { - CoordStartIndex++; - Coords[Coords.Length - 1] = OpCode.Gpr8(); + coordStartIndex++; + coords[coords.Length - 1] = opCode.Gpr8(); } - switch (Coords.Length - CoordStartIndex) + switch (coords.Length - coordStartIndex) { case 1: - Coords[0] = OpCode.Gpr8(); + coords[0] = opCode.Gpr8(); break; case 2: - Coords[0] = OpCode.Gpr8(); - Coords[0].Index += CoordStartIndex; + coords[0] = opCode.Gpr8(); + coords[0].Index += coordStartIndex; break; case 3: - Coords[0] = OpCode.Gpr8(); - Coords[0].Index += CoordStartIndex; + coords[0] = opCode.Gpr8(); + coords[0].Index += coordStartIndex; - Coords[1] = OpCode.Gpr8(); - Coords[1].Index += 1 + CoordStartIndex; + coords[1] = opCode.Gpr8(); + coords[1].Index += 1 + coordStartIndex; break; default: - throw new NotSupportedException($"{Coords.Length - CoordStartIndex} coords textures aren't supported in TEXS"); + throw new NotSupportedException($"{coords.Length - coordStartIndex} coords textures aren't supported in TEXS"); } - int OperBIndex = 0; + int operBIndex = 0; - ShaderIrOperGpr LevelOfDetail = null; - ShaderIrOperGpr Offset = null; - ShaderIrOperGpr DepthCompare = null; + ShaderIrOperGpr levelOfDetail = null; + ShaderIrOperGpr offset = null; + ShaderIrOperGpr depthCompare = null; // OperB is always the last value // Not applicable to 1d textures - if (Coords.Length - CoordStartIndex != 1) + if (coords.Length - coordStartIndex != 1) { - Coords[Coords.Length - CoordStartIndex - 1] = OperB; - OperBIndex++; + coords[coords.Length - coordStartIndex - 1] = operB; + operBIndex++; } // Encoding of TEXS/TLDS is a bit special and change for 2d textures // NOTE: OperA seems to hold at best two args. // On 2D textures, if no suffix need an additional values, Y is stored in OperB, otherwise coords are in OperA and the additional values is in OperB. - if (TextureInstructionSuffix != TextureInstructionSuffix.None && TextureInstructionSuffix != TextureInstructionSuffix.LZ && TextureTarget == GalTextureTarget.TwoD) + if (textureInstructionSuffix != TextureInstructionSuffix.None && textureInstructionSuffix != TextureInstructionSuffix.Lz && textureTarget == GalTextureTarget.TwoD) { - Coords[Coords.Length - CoordStartIndex - 1] = OpCode.Gpr8(); - Coords[Coords.Length - CoordStartIndex - 1].Index += Coords.Length - CoordStartIndex - 1; - OperBIndex--; + coords[coords.Length - coordStartIndex - 1] = opCode.Gpr8(); + coords[coords.Length - coordStartIndex - 1].Index += coords.Length - coordStartIndex - 1; + operBIndex--; } // TODO: Find what MZ does and what changes about the encoding (Maybe Multisample?) - if ((TextureInstructionSuffix & TextureInstructionSuffix.LL) != 0) + if ((textureInstructionSuffix & TextureInstructionSuffix.Ll) != 0) { - LevelOfDetail = OpCode.Gpr20(); - LevelOfDetail.Index += OperBIndex; - OperBIndex++; + levelOfDetail = opCode.Gpr20(); + levelOfDetail.Index += operBIndex; + operBIndex++; } - if ((TextureInstructionSuffix & TextureInstructionSuffix.AOffI) != 0) + if ((textureInstructionSuffix & TextureInstructionSuffix.AOffI) != 0) { - Offset = OpCode.Gpr20(); - Offset.Index += OperBIndex; - OperBIndex++; + offset = opCode.Gpr20(); + offset.Index += operBIndex; + operBIndex++; } - if ((TextureInstructionSuffix & TextureInstructionSuffix.DC) != 0) + if ((textureInstructionSuffix & TextureInstructionSuffix.Dc) != 0) { - DepthCompare = OpCode.Gpr20(); - DepthCompare.Index += OperBIndex; - OperBIndex++; + depthCompare = opCode.Gpr20(); + depthCompare.Index += operBIndex; + operBIndex++; } - int LutIndex; + int lutIndex; - LutIndex = !OpCode.Gpr0().IsConst ? 1 : 0; - LutIndex |= !OpCode.Gpr28().IsConst ? 2 : 0; + lutIndex = !opCode.Gpr0().IsConst ? 1 : 0; + lutIndex |= !opCode.Gpr28().IsConst ? 2 : 0; - if (LutIndex == 0) + if (lutIndex == 0) { //Both destination registers are RZ, do nothing. return; } - bool Fp16 = !OpCode.Read(59); + bool fp16 = !opCode.Read(59); - int DstIncrement = 0; + int dstIncrement = 0; ShaderIrOperGpr GetDst() { - ShaderIrOperGpr Dst; + ShaderIrOperGpr dst; - if (Fp16) + if (fp16) { //FP16 mode, two components are packed on the two //halfs of a 32-bits register, as two half-float values. - int HalfPart = DstIncrement & 1; + int halfPart = dstIncrement & 1; - switch (LutIndex) + switch (lutIndex) { - case 1: Dst = OpCode.GprHalf0(HalfPart); break; - case 2: Dst = OpCode.GprHalf28(HalfPart); break; - case 3: Dst = (DstIncrement >> 1) != 0 - ? OpCode.GprHalf28(HalfPart) - : OpCode.GprHalf0(HalfPart); break; + case 1: dst = opCode.GprHalf0(halfPart); break; + case 2: dst = opCode.GprHalf28(halfPart); break; + case 3: dst = (dstIncrement >> 1) != 0 + ? opCode.GprHalf28(halfPart) + : opCode.GprHalf0(halfPart); break; default: throw new InvalidOperationException(); } @@ -667,210 +669,210 @@ namespace Ryujinx.Graphics.Gal.Shader { //32-bits mode, each component uses one register. //Two components uses two consecutive registers. - switch (LutIndex) + switch (lutIndex) { - case 1: Dst = OpCode.Gpr0(); break; - case 2: Dst = OpCode.Gpr28(); break; - case 3: Dst = (DstIncrement >> 1) != 0 - ? OpCode.Gpr28() - : OpCode.Gpr0(); break; + case 1: dst = opCode.Gpr0(); break; + case 2: dst = opCode.Gpr28(); break; + case 3: dst = (dstIncrement >> 1) != 0 + ? opCode.Gpr28() + : opCode.Gpr0(); break; default: throw new InvalidOperationException(); } - Dst.Index += DstIncrement & 1; + dst.Index += dstIncrement & 1; } - DstIncrement++; + dstIncrement++; - return Dst; + return dst; } - int ChMask = MaskLut[LutIndex, OpCode.Read(50, 7)]; + int chMask = _maskLut[lutIndex, opCode.Read(50, 7)]; - if (ChMask == 0) + if (chMask == 0) { //All channels are disabled, do nothing. return; } - ShaderIrNode OperC = OpCode.Imm13_36(); - Coords = CoordsRegistersToTempRegisters(Block, Coords); + ShaderIrNode operC = opCode.Imm13_36(); + coords = CoordsRegistersToTempRegisters(block, coords); - for (int Ch = 0; Ch < 4; Ch++) + for (int ch = 0; ch < 4; ch++) { - if (!IsChannelUsed(ChMask, Ch)) + if (!IsChannelUsed(chMask, ch)) { continue; } - ShaderIrMetaTex Meta = new ShaderIrMetaTex(Ch, TextureTarget, TextureInstructionSuffix, Coords) + ShaderIrMetaTex meta = new ShaderIrMetaTex(ch, textureTarget, textureInstructionSuffix, coords) { - LevelOfDetail = LevelOfDetail, - Offset = Offset, - DepthCompare = DepthCompare + LevelOfDetail = levelOfDetail, + Offset = offset, + DepthCompare = depthCompare }; - ShaderIrOp Op = new ShaderIrOp(Inst, OperA, OperB, OperC, Meta); + ShaderIrOp op = new ShaderIrOp(inst, operA, operB, operC, meta); - ShaderIrOperGpr Dst = GetDst(); + ShaderIrOperGpr dst = GetDst(); - if (Dst.IsValidRegister && !Dst.IsConst) + if (dst.IsValidRegister && !dst.IsConst) { - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(Dst, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(dst, op))); } } } - private static void EmitTld4(ShaderIrBlock Block, long OpCode, GalTextureTarget TextureType, TextureInstructionSuffix TextureInstructionSuffix, int ChMask, int Component, bool Scalar) + private static void EmitTld4(ShaderIrBlock block, long opCode, GalTextureTarget textureType, TextureInstructionSuffix textureInstructionSuffix, int chMask, int component, bool scalar) { - ShaderIrOperGpr OperA = OpCode.Gpr8(); - ShaderIrOperGpr OperB = OpCode.Gpr20(); - ShaderIrOperImm OperC = OpCode.Imm13_36(); + ShaderIrOperGpr operA = opCode.Gpr8(); + ShaderIrOperGpr operB = opCode.Gpr20(); + ShaderIrOperImm operC = opCode.Imm13_36(); - ShaderIrOperGpr[] Coords = new ShaderIrOperGpr[ImageUtils.GetCoordsCountTextureTarget(TextureType)]; + ShaderIrOperGpr[] coords = new ShaderIrOperGpr[ImageUtils.GetCoordsCountTextureTarget(textureType)]; - ShaderIrOperGpr Offset = null; - ShaderIrOperGpr DepthCompare = null; + ShaderIrOperGpr offset = null; + ShaderIrOperGpr depthCompare = null; - bool IsArray = ImageUtils.IsArray(TextureType); + bool isArray = ImageUtils.IsArray(textureType); - int OperBIndex = 0; + int operBIndex = 0; - if (Scalar) + if (scalar) { - int CoordStartIndex = 0; + int coordStartIndex = 0; - if (IsArray) + if (isArray) { - CoordStartIndex++; - Coords[Coords.Length - 1] = OperB; + coordStartIndex++; + coords[coords.Length - 1] = operB; } - switch (Coords.Length - CoordStartIndex) + switch (coords.Length - coordStartIndex) { case 1: - Coords[0] = OpCode.Gpr8(); + coords[0] = opCode.Gpr8(); break; case 2: - Coords[0] = OpCode.Gpr8(); - Coords[0].Index += CoordStartIndex; + coords[0] = opCode.Gpr8(); + coords[0].Index += coordStartIndex; break; case 3: - Coords[0] = OpCode.Gpr8(); - Coords[0].Index += CoordStartIndex; + coords[0] = opCode.Gpr8(); + coords[0].Index += coordStartIndex; - Coords[1] = OpCode.Gpr8(); - Coords[1].Index += 1 + CoordStartIndex; + coords[1] = opCode.Gpr8(); + coords[1].Index += 1 + coordStartIndex; break; default: - throw new NotSupportedException($"{Coords.Length - CoordStartIndex} coords textures aren't supported in TLD4S"); + throw new NotSupportedException($"{coords.Length - coordStartIndex} coords textures aren't supported in TLD4S"); } - if (Coords.Length - CoordStartIndex != 1) + if (coords.Length - coordStartIndex != 1) { - Coords[Coords.Length - CoordStartIndex - 1] = OperB; - OperBIndex++; + coords[coords.Length - coordStartIndex - 1] = operB; + operBIndex++; } - if (TextureInstructionSuffix != TextureInstructionSuffix.None && TextureType == GalTextureTarget.TwoD) + if (textureInstructionSuffix != TextureInstructionSuffix.None && textureType == GalTextureTarget.TwoD) { - Coords[Coords.Length - CoordStartIndex - 1] = OpCode.Gpr8(); - Coords[Coords.Length - CoordStartIndex - 1].Index += Coords.Length - CoordStartIndex - 1; - OperBIndex--; + coords[coords.Length - coordStartIndex - 1] = opCode.Gpr8(); + coords[coords.Length - coordStartIndex - 1].Index += coords.Length - coordStartIndex - 1; + operBIndex--; } } else { - int IndexExtraCoord = 0; + int indexExtraCoord = 0; - if (IsArray) + if (isArray) { - IndexExtraCoord++; + indexExtraCoord++; - Coords[Coords.Length - 1] = OpCode.Gpr8(); + coords[coords.Length - 1] = opCode.Gpr8(); } - for (int Index = 0; Index < Coords.Length - IndexExtraCoord; Index++) + for (int index = 0; index < coords.Length - indexExtraCoord; index++) { - Coords[Index] = OpCode.Gpr8(); + coords[index] = opCode.Gpr8(); - Coords[Index].Index += Index; + coords[index].Index += index; - Coords[Index].Index += IndexExtraCoord; + coords[index].Index += indexExtraCoord; - if (Coords[Index].Index > ShaderIrOperGpr.ZRIndex) + if (coords[index].Index > ShaderIrOperGpr.ZrIndex) { - Coords[Index].Index = ShaderIrOperGpr.ZRIndex; + coords[index].Index = ShaderIrOperGpr.ZrIndex; } } } - if ((TextureInstructionSuffix & TextureInstructionSuffix.AOffI) != 0) + if ((textureInstructionSuffix & TextureInstructionSuffix.AOffI) != 0) { - Offset = OpCode.Gpr20(); - Offset.Index += OperBIndex; - OperBIndex++; + offset = opCode.Gpr20(); + offset.Index += operBIndex; + operBIndex++; } - if ((TextureInstructionSuffix & TextureInstructionSuffix.DC) != 0) + if ((textureInstructionSuffix & TextureInstructionSuffix.Dc) != 0) { - DepthCompare = OpCode.Gpr20(); - DepthCompare.Index += OperBIndex; - OperBIndex++; + depthCompare = opCode.Gpr20(); + depthCompare.Index += operBIndex; + operBIndex++; } - Coords = CoordsRegistersToTempRegisters(Block, Coords); + coords = CoordsRegistersToTempRegisters(block, coords); - int RegInc = 0; + int regInc = 0; - for (int Ch = 0; Ch < 4; Ch++) + for (int ch = 0; ch < 4; ch++) { - if (!IsChannelUsed(ChMask, Ch)) + if (!IsChannelUsed(chMask, ch)) { continue; } - ShaderIrOperGpr Dst = OpCode.Gpr0(); + ShaderIrOperGpr dst = opCode.Gpr0(); - Dst.Index += RegInc++; + dst.Index += regInc++; - if (!Dst.IsValidRegister || Dst.IsConst) + if (!dst.IsValidRegister || dst.IsConst) { continue; } - ShaderIrMetaTex Meta = new ShaderIrMetaTex(Ch, TextureType, TextureInstructionSuffix, Coords) + ShaderIrMetaTex meta = new ShaderIrMetaTex(ch, textureType, textureInstructionSuffix, coords) { - Component = Component, - Offset = Offset, - DepthCompare = DepthCompare + Component = component, + Offset = offset, + DepthCompare = depthCompare }; - ShaderIrOp Op = new ShaderIrOp(ShaderIrInst.Tld4, OperA, OperB, OperC, Meta); + ShaderIrOp op = new ShaderIrOp(ShaderIrInst.Tld4, operA, operB, operC, meta); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(Dst, Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(dst, op))); } } - private static bool IsChannelUsed(int ChMask, int Ch) + private static bool IsChannelUsed(int chMask, int ch) { - return (ChMask & (1 << Ch)) != 0; + return (chMask & (1 << ch)) != 0; } - private static ShaderIrOperGpr[] CoordsRegistersToTempRegisters(ShaderIrBlock Block, params ShaderIrOperGpr[] Registers) + private static ShaderIrOperGpr[] CoordsRegistersToTempRegisters(ShaderIrBlock block, params ShaderIrOperGpr[] registers) { - ShaderIrOperGpr[] Res = new ShaderIrOperGpr[Registers.Length]; + ShaderIrOperGpr[] res = new ShaderIrOperGpr[registers.Length]; - for (int Index = 0; Index < Res.Length; Index++) + for (int index = 0; index < res.Length; index++) { - Res[Index] = ShaderIrOperGpr.MakeTemporary(Index); - Block.AddNode(new ShaderIrAsg(Res[Index], Registers[Index])); + res[index] = ShaderIrOperGpr.MakeTemporary(index); + block.AddNode(new ShaderIrAsg(res[index], registers[index])); } - return Res; + return res; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMove.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMove.cs index cd602db7..0a2b4232 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMove.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMove.cs @@ -25,400 +25,400 @@ namespace Ryujinx.Graphics.Gal.Shader F64 = 3 } - public static void F2f_C(ShaderIrBlock Block, long OpCode, int Position) + public static void F2f_C(ShaderIrBlock block, long opCode, int position) { - EmitF2f(Block, OpCode, ShaderOper.CR); + EmitF2F(block, opCode, ShaderOper.Cr); } - public static void F2f_I(ShaderIrBlock Block, long OpCode, int Position) + public static void F2f_I(ShaderIrBlock block, long opCode, int position) { - EmitF2f(Block, OpCode, ShaderOper.Immf); + EmitF2F(block, opCode, ShaderOper.Immf); } - public static void F2f_R(ShaderIrBlock Block, long OpCode, int Position) + public static void F2f_R(ShaderIrBlock block, long opCode, int position) { - EmitF2f(Block, OpCode, ShaderOper.RR); + EmitF2F(block, opCode, ShaderOper.Rr); } - public static void F2i_C(ShaderIrBlock Block, long OpCode, int Position) + public static void F2i_C(ShaderIrBlock block, long opCode, int position) { - EmitF2i(Block, OpCode, ShaderOper.CR); + EmitF2I(block, opCode, ShaderOper.Cr); } - public static void F2i_I(ShaderIrBlock Block, long OpCode, int Position) + public static void F2i_I(ShaderIrBlock block, long opCode, int position) { - EmitF2i(Block, OpCode, ShaderOper.Immf); + EmitF2I(block, opCode, ShaderOper.Immf); } - public static void F2i_R(ShaderIrBlock Block, long OpCode, int Position) + public static void F2i_R(ShaderIrBlock block, long opCode, int position) { - EmitF2i(Block, OpCode, ShaderOper.RR); + EmitF2I(block, opCode, ShaderOper.Rr); } - public static void I2f_C(ShaderIrBlock Block, long OpCode, int Position) + public static void I2f_C(ShaderIrBlock block, long opCode, int position) { - EmitI2f(Block, OpCode, ShaderOper.CR); + EmitI2F(block, opCode, ShaderOper.Cr); } - public static void I2f_I(ShaderIrBlock Block, long OpCode, int Position) + public static void I2f_I(ShaderIrBlock block, long opCode, int position) { - EmitI2f(Block, OpCode, ShaderOper.Imm); + EmitI2F(block, opCode, ShaderOper.Imm); } - public static void I2f_R(ShaderIrBlock Block, long OpCode, int Position) + public static void I2f_R(ShaderIrBlock block, long opCode, int position) { - EmitI2f(Block, OpCode, ShaderOper.RR); + EmitI2F(block, opCode, ShaderOper.Rr); } - public static void I2i_C(ShaderIrBlock Block, long OpCode, int Position) + public static void I2i_C(ShaderIrBlock block, long opCode, int position) { - EmitI2i(Block, OpCode, ShaderOper.CR); + EmitI2I(block, opCode, ShaderOper.Cr); } - public static void I2i_I(ShaderIrBlock Block, long OpCode, int Position) + public static void I2i_I(ShaderIrBlock block, long opCode, int position) { - EmitI2i(Block, OpCode, ShaderOper.Imm); + EmitI2I(block, opCode, ShaderOper.Imm); } - public static void I2i_R(ShaderIrBlock Block, long OpCode, int Position) + public static void I2i_R(ShaderIrBlock block, long opCode, int position) { - EmitI2i(Block, OpCode, ShaderOper.RR); + EmitI2I(block, opCode, ShaderOper.Rr); } - public static void Isberd(ShaderIrBlock Block, long OpCode, int Position) + public static void Isberd(ShaderIrBlock block, long opCode, int position) { //This instruction seems to be used to translate from an address to a vertex index in a GS //Stub it as such - Block.AddNode(new ShaderIrCmnt("Stubbed.")); + block.AddNode(new ShaderIrCmnt("Stubbed.")); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), OpCode.Gpr8()))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), opCode.Gpr8()))); } - public static void Mov_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Mov_C(ShaderIrBlock block, long opCode, int position) { - ShaderIrOperCbuf Cbuf = OpCode.Cbuf34(); + ShaderIrOperCbuf cbuf = opCode.Cbuf34(); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Cbuf))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), cbuf))); } - public static void Mov_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Mov_I(ShaderIrBlock block, long opCode, int position) { - ShaderIrOperImm Imm = OpCode.Imm19_20(); + ShaderIrOperImm imm = opCode.Imm19_20(); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Imm))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), imm))); } - public static void Mov_I32(ShaderIrBlock Block, long OpCode, int Position) + public static void Mov_I32(ShaderIrBlock block, long opCode, int position) { - ShaderIrOperImm Imm = OpCode.Imm32_20(); + ShaderIrOperImm imm = opCode.Imm32_20(); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Imm))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), imm))); } - public static void Mov_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Mov_R(ShaderIrBlock block, long opCode, int position) { - ShaderIrOperGpr Gpr = OpCode.Gpr20(); + ShaderIrOperGpr gpr = opCode.Gpr20(); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Gpr))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), gpr))); } - public static void Sel_C(ShaderIrBlock Block, long OpCode, int Position) + public static void Sel_C(ShaderIrBlock block, long opCode, int position) { - EmitSel(Block, OpCode, ShaderOper.CR); + EmitSel(block, opCode, ShaderOper.Cr); } - public static void Sel_I(ShaderIrBlock Block, long OpCode, int Position) + public static void Sel_I(ShaderIrBlock block, long opCode, int position) { - EmitSel(Block, OpCode, ShaderOper.Imm); + EmitSel(block, opCode, ShaderOper.Imm); } - public static void Sel_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Sel_R(ShaderIrBlock block, long opCode, int position) { - EmitSel(Block, OpCode, ShaderOper.RR); + EmitSel(block, opCode, ShaderOper.Rr); } - public static void Mov_S(ShaderIrBlock Block, long OpCode, int Position) + public static void Mov_S(ShaderIrBlock block, long opCode, int position) { - Block.AddNode(new ShaderIrCmnt("Stubbed.")); + block.AddNode(new ShaderIrCmnt("Stubbed.")); //Zero is used as a special number to get a valid "0 * 0 + VertexIndex" in a GS - ShaderIrNode Source = new ShaderIrOperImm(0); + ShaderIrNode source = new ShaderIrOperImm(0); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Source))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), source))); } - private static void EmitF2f(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitF2F(ShaderIrBlock block, long opCode, ShaderOper oper) { - bool NegA = OpCode.Read(45); - bool AbsA = OpCode.Read(49); + bool negA = opCode.Read(45); + bool absA = opCode.Read(49); - ShaderIrNode OperA; + ShaderIrNode operA; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperA = OpCode.Cbuf34(); break; - case ShaderOper.Immf: OperA = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperA = OpCode.Gpr20(); break; + case ShaderOper.Cr: operA = opCode.Cbuf34(); break; + case ShaderOper.Immf: operA = opCode.Immf19_20(); break; + case ShaderOper.Rr: operA = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperA = GetAluFabsFneg(OperA, AbsA, NegA); + operA = GetAluFabsFneg(operA, absA, negA); - ShaderIrInst RoundInst = GetRoundInst(OpCode); + ShaderIrInst roundInst = GetRoundInst(opCode); - if (RoundInst != ShaderIrInst.Invalid) + if (roundInst != ShaderIrInst.Invalid) { - OperA = new ShaderIrOp(RoundInst, OperA); + operA = new ShaderIrOp(roundInst, operA); } - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), OperA))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), operA))); } - private static void EmitF2i(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitF2I(ShaderIrBlock block, long opCode, ShaderOper oper) { - IntType Type = GetIntType(OpCode); + IntType type = GetIntType(opCode); - if (Type == IntType.U64 || - Type == IntType.S64) + if (type == IntType.U64 || + type == IntType.S64) { //TODO: 64-bits support. //Note: GLSL doesn't support 64-bits integers. throw new NotImplementedException(); } - bool NegA = OpCode.Read(45); - bool AbsA = OpCode.Read(49); + bool negA = opCode.Read(45); + bool absA = opCode.Read(49); - ShaderIrNode OperA; + ShaderIrNode operA; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperA = OpCode.Cbuf34(); break; - case ShaderOper.Immf: OperA = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperA = OpCode.Gpr20(); break; + case ShaderOper.Cr: operA = opCode.Cbuf34(); break; + case ShaderOper.Immf: operA = opCode.Immf19_20(); break; + case ShaderOper.Rr: operA = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperA = GetAluFabsFneg(OperA, AbsA, NegA); + operA = GetAluFabsFneg(operA, absA, negA); - ShaderIrInst RoundInst = GetRoundInst(OpCode); + ShaderIrInst roundInst = GetRoundInst(opCode); - if (RoundInst != ShaderIrInst.Invalid) + if (roundInst != ShaderIrInst.Invalid) { - OperA = new ShaderIrOp(RoundInst, OperA); + operA = new ShaderIrOp(roundInst, operA); } - bool Signed = Type >= IntType.S8; + bool signed = type >= IntType.S8; - int Size = 8 << ((int)Type & 3); + int size = 8 << ((int)type & 3); - if (Size < 32) + if (size < 32) { - uint Mask = uint.MaxValue >> (32 - Size); + uint mask = uint.MaxValue >> (32 - size); - float CMin = 0; - float CMax = Mask; + float cMin = 0; + float cMax = mask; - if (Signed) + if (signed) { - uint HalfMask = Mask >> 1; + uint halfMask = mask >> 1; - CMin -= HalfMask + 1; - CMax = HalfMask; + cMin -= halfMask + 1; + cMax = halfMask; } - ShaderIrOperImmf IMin = new ShaderIrOperImmf(CMin); - ShaderIrOperImmf IMax = new ShaderIrOperImmf(CMax); + ShaderIrOperImmf min = new ShaderIrOperImmf(cMin); + ShaderIrOperImmf max = new ShaderIrOperImmf(cMax); - OperA = new ShaderIrOp(ShaderIrInst.Fclamp, OperA, IMin, IMax); + operA = new ShaderIrOp(ShaderIrInst.Fclamp, operA, min, max); } - ShaderIrInst Inst = Signed + ShaderIrInst inst = signed ? ShaderIrInst.Ftos : ShaderIrInst.Ftou; - ShaderIrNode Op = new ShaderIrOp(Inst, OperA); + ShaderIrNode op = new ShaderIrOp(inst, operA); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - private static void EmitI2f(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitI2F(ShaderIrBlock block, long opCode, ShaderOper oper) { - IntType Type = GetIntType(OpCode); + IntType type = GetIntType(opCode); - if (Type == IntType.U64 || - Type == IntType.S64) + if (type == IntType.U64 || + type == IntType.S64) { //TODO: 64-bits support. //Note: GLSL doesn't support 64-bits integers. throw new NotImplementedException(); } - int Sel = OpCode.Read(41, 3); + int sel = opCode.Read(41, 3); - bool NegA = OpCode.Read(45); - bool AbsA = OpCode.Read(49); + bool negA = opCode.Read(45); + bool absA = opCode.Read(49); - ShaderIrNode OperA; + ShaderIrNode operA; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperA = OpCode.Cbuf34(); break; - case ShaderOper.Imm: OperA = OpCode.Imm19_20(); break; - case ShaderOper.RR: OperA = OpCode.Gpr20(); break; + case ShaderOper.Cr: operA = opCode.Cbuf34(); break; + case ShaderOper.Imm: operA = opCode.Imm19_20(); break; + case ShaderOper.Rr: operA = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperA = GetAluIabsIneg(OperA, AbsA, NegA); + operA = GetAluIabsIneg(operA, absA, negA); - bool Signed = Type >= IntType.S8; + bool signed = type >= IntType.S8; - int Shift = Sel * 8; + int shift = sel * 8; - int Size = 8 << ((int)Type & 3); + int size = 8 << ((int)type & 3); - if (Shift != 0) + if (shift != 0) { - OperA = new ShaderIrOp(ShaderIrInst.Asr, OperA, new ShaderIrOperImm(Shift)); + operA = new ShaderIrOp(ShaderIrInst.Asr, operA, new ShaderIrOperImm(shift)); } - if (Size < 32) + if (size < 32) { - OperA = ExtendTo32(OperA, Signed, Size); + operA = ExtendTo32(operA, signed, size); } - ShaderIrInst Inst = Signed + ShaderIrInst inst = signed ? ShaderIrInst.Stof : ShaderIrInst.Utof; - ShaderIrNode Op = new ShaderIrOp(Inst, OperA); + ShaderIrNode op = new ShaderIrOp(inst, operA); - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), Op))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } - private static void EmitI2i(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitI2I(ShaderIrBlock block, long opCode, ShaderOper oper) { - IntType Type = GetIntType(OpCode); + IntType type = GetIntType(opCode); - if (Type == IntType.U64 || - Type == IntType.S64) + if (type == IntType.U64 || + type == IntType.S64) { //TODO: 64-bits support. //Note: GLSL doesn't support 64-bits integers. throw new NotImplementedException(); } - int Sel = OpCode.Read(41, 3); + int sel = opCode.Read(41, 3); - bool NegA = OpCode.Read(45); - bool AbsA = OpCode.Read(49); - bool SatA = OpCode.Read(50); + bool negA = opCode.Read(45); + bool absA = opCode.Read(49); + bool satA = opCode.Read(50); - ShaderIrNode OperA; + ShaderIrNode operA; - switch (Oper) + switch (oper) { - case ShaderOper.CR: OperA = OpCode.Cbuf34(); break; - case ShaderOper.Immf: OperA = OpCode.Immf19_20(); break; - case ShaderOper.RR: OperA = OpCode.Gpr20(); break; + case ShaderOper.Cr: operA = opCode.Cbuf34(); break; + case ShaderOper.Immf: operA = opCode.Immf19_20(); break; + case ShaderOper.Rr: operA = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - OperA = GetAluIabsIneg(OperA, AbsA, NegA); + operA = GetAluIabsIneg(operA, absA, negA); - bool Signed = Type >= IntType.S8; + bool signed = type >= IntType.S8; - int Shift = Sel * 8; + int shift = sel * 8; - int Size = 8 << ((int)Type & 3); + int size = 8 << ((int)type & 3); - if (Shift != 0) + if (shift != 0) { - OperA = new ShaderIrOp(ShaderIrInst.Asr, OperA, new ShaderIrOperImm(Shift)); + operA = new ShaderIrOp(ShaderIrInst.Asr, operA, new ShaderIrOperImm(shift)); } - if (Size < 32) + if (size < 32) { - uint Mask = uint.MaxValue >> (32 - Size); + uint mask = uint.MaxValue >> (32 - size); - if (SatA) + if (satA) { - uint CMin = 0; - uint CMax = Mask; + uint cMin = 0; + uint cMax = mask; - if (Signed) + if (signed) { - uint HalfMask = Mask >> 1; + uint halfMask = mask >> 1; - CMin -= HalfMask + 1; - CMax = HalfMask; + cMin -= halfMask + 1; + cMax = halfMask; } - ShaderIrOperImm IMin = new ShaderIrOperImm((int)CMin); - ShaderIrOperImm IMax = new ShaderIrOperImm((int)CMax); + ShaderIrOperImm min = new ShaderIrOperImm((int)cMin); + ShaderIrOperImm max = new ShaderIrOperImm((int)cMax); - OperA = new ShaderIrOp(Signed + operA = new ShaderIrOp(signed ? ShaderIrInst.Clamps - : ShaderIrInst.Clampu, OperA, IMin, IMax); + : ShaderIrInst.Clampu, operA, min, max); } else { - OperA = ExtendTo32(OperA, Signed, Size); + operA = ExtendTo32(operA, signed, size); } } - Block.AddNode(OpCode.PredNode(new ShaderIrAsg(OpCode.Gpr0(), OperA))); + block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), operA))); } - private static void EmitSel(ShaderIrBlock Block, long OpCode, ShaderOper Oper) + private static void EmitSel(ShaderIrBlock block, long opCode, ShaderOper oper) { - ShaderIrOperGpr Dst = OpCode.Gpr0(); - ShaderIrNode Pred = OpCode.Pred39N(); + ShaderIrOperGpr dst = opCode.Gpr0(); + ShaderIrNode pred = opCode.Pred39N(); - ShaderIrNode ResultA = OpCode.Gpr8(); - ShaderIrNode ResultB; + ShaderIrNode resultA = opCode.Gpr8(); + ShaderIrNode resultB; - switch (Oper) + switch (oper) { - case ShaderOper.CR: ResultB = OpCode.Cbuf34(); break; - case ShaderOper.Imm: ResultB = OpCode.Imm19_20(); break; - case ShaderOper.RR: ResultB = OpCode.Gpr20(); break; + case ShaderOper.Cr: resultB = opCode.Cbuf34(); break; + case ShaderOper.Imm: resultB = opCode.Imm19_20(); break; + case ShaderOper.Rr: resultB = opCode.Gpr20(); break; - default: throw new ArgumentException(nameof(Oper)); + default: throw new ArgumentException(nameof(oper)); } - Block.AddNode(OpCode.PredNode(new ShaderIrCond(Pred, new ShaderIrAsg(Dst, ResultA), false))); + block.AddNode(opCode.PredNode(new ShaderIrCond(pred, new ShaderIrAsg(dst, resultA), false))); - Block.AddNode(OpCode.PredNode(new ShaderIrCond(Pred, new ShaderIrAsg(Dst, ResultB), true))); + block.AddNode(opCode.PredNode(new ShaderIrCond(pred, new ShaderIrAsg(dst, resultB), true))); } - private static IntType GetIntType(long OpCode) + private static IntType GetIntType(long opCode) { - bool Signed = OpCode.Read(13); + bool signed = opCode.Read(13); - IntType Type = (IntType)(OpCode.Read(10, 3)); + IntType type = (IntType)(opCode.Read(10, 3)); - if (Signed) + if (signed) { - Type += (int)IntType.S8; + type += (int)IntType.S8; } - return Type; + return type; } - private static FloatType GetFloatType(long OpCode) + private static FloatType GetFloatType(long opCode) { - return (FloatType)(OpCode.Read(8, 3)); + return (FloatType)(opCode.Read(8, 3)); } - private static ShaderIrInst GetRoundInst(long OpCode) + private static ShaderIrInst GetRoundInst(long opCode) { - switch (OpCode.Read(39, 3)) + switch (opCode.Read(39, 3)) { case 1: return ShaderIrInst.Floor; case 2: return ShaderIrInst.Ceil; diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeOpCode.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeOpCode.cs index e241e1ca..4b1e4046 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeOpCode.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeOpCode.cs @@ -4,227 +4,227 @@ namespace Ryujinx.Graphics.Gal.Shader { static partial class ShaderDecode { - private static int Read(this long OpCode, int Position, int Mask) + private static int Read(this long opCode, int position, int mask) { - return (int)(OpCode >> Position) & Mask; + return (int)(opCode >> position) & mask; } - private static bool Read(this long OpCode, int Position) + private static bool Read(this long opCode, int position) { - return ((OpCode >> Position) & 1) != 0; + return ((opCode >> position) & 1) != 0; } - private static int Branch(this long OpCode) + private static int Branch(this long opCode) { - return ((int)(OpCode >> 20) << 8) >> 8; + return ((int)(opCode >> 20) << 8) >> 8; } - private static bool HasArray(this long OpCode) + private static bool HasArray(this long opCode) { - return OpCode.Read(0x1c); + return opCode.Read(0x1c); } - private static ShaderIrOperAbuf[] Abuf20(this long OpCode) + private static ShaderIrOperAbuf[] Abuf20(this long opCode) { - int Abuf = OpCode.Read(20, 0x3ff); - int Size = OpCode.Read(47, 3); + int abuf = opCode.Read(20, 0x3ff); + int size = opCode.Read(47, 3); - ShaderIrOperGpr Vertex = OpCode.Gpr39(); + ShaderIrOperGpr vertex = opCode.Gpr39(); - ShaderIrOperAbuf[] Opers = new ShaderIrOperAbuf[Size + 1]; + ShaderIrOperAbuf[] opers = new ShaderIrOperAbuf[size + 1]; - for (int Index = 0; Index <= Size; Index++) + for (int index = 0; index <= size; index++) { - Opers[Index] = new ShaderIrOperAbuf(Abuf + Index * 4, Vertex); + opers[index] = new ShaderIrOperAbuf(abuf + index * 4, vertex); } - return Opers; + return opers; } - private static ShaderIrOperAbuf Abuf28(this long OpCode) + private static ShaderIrOperAbuf Abuf28(this long opCode) { - int Abuf = OpCode.Read(28, 0x3ff); + int abuf = opCode.Read(28, 0x3ff); - return new ShaderIrOperAbuf(Abuf, OpCode.Gpr39()); + return new ShaderIrOperAbuf(abuf, opCode.Gpr39()); } - private static ShaderIrOperCbuf Cbuf34(this long OpCode) + private static ShaderIrOperCbuf Cbuf34(this long opCode) { return new ShaderIrOperCbuf( - OpCode.Read(34, 0x1f), - OpCode.Read(20, 0x3fff)); + opCode.Read(34, 0x1f), + opCode.Read(20, 0x3fff)); } - private static ShaderIrOperGpr Gpr8(this long OpCode) + private static ShaderIrOperGpr Gpr8(this long opCode) { - return new ShaderIrOperGpr(OpCode.Read(8, 0xff)); + return new ShaderIrOperGpr(opCode.Read(8, 0xff)); } - private static ShaderIrOperGpr Gpr20(this long OpCode) + private static ShaderIrOperGpr Gpr20(this long opCode) { - return new ShaderIrOperGpr(OpCode.Read(20, 0xff)); + return new ShaderIrOperGpr(opCode.Read(20, 0xff)); } - private static ShaderIrOperGpr Gpr39(this long OpCode) + private static ShaderIrOperGpr Gpr39(this long opCode) { - return new ShaderIrOperGpr(OpCode.Read(39, 0xff)); + return new ShaderIrOperGpr(opCode.Read(39, 0xff)); } - private static ShaderIrOperGpr Gpr0(this long OpCode) + private static ShaderIrOperGpr Gpr0(this long opCode) { - return new ShaderIrOperGpr(OpCode.Read(0, 0xff)); + return new ShaderIrOperGpr(opCode.Read(0, 0xff)); } - private static ShaderIrOperGpr Gpr28(this long OpCode) + private static ShaderIrOperGpr Gpr28(this long opCode) { - return new ShaderIrOperGpr(OpCode.Read(28, 0xff)); + return new ShaderIrOperGpr(opCode.Read(28, 0xff)); } - private static ShaderIrOperGpr[] GprHalfVec8(this long OpCode) + private static ShaderIrOperGpr[] GprHalfVec8(this long opCode) { - return GetGprHalfVec2(OpCode.Read(8, 0xff), OpCode.Read(47, 3)); + return GetGprHalfVec2(opCode.Read(8, 0xff), opCode.Read(47, 3)); } - private static ShaderIrOperGpr[] GprHalfVec20(this long OpCode) + private static ShaderIrOperGpr[] GprHalfVec20(this long opCode) { - return GetGprHalfVec2(OpCode.Read(20, 0xff), OpCode.Read(28, 3)); + return GetGprHalfVec2(opCode.Read(20, 0xff), opCode.Read(28, 3)); } - private static ShaderIrOperGpr[] GetGprHalfVec2(int Gpr, int Mask) + private static ShaderIrOperGpr[] GetGprHalfVec2(int gpr, int mask) { - if (Mask == 1) + if (mask == 1) { //This value is used for FP32, the whole 32-bits register //is used as each element on the vector. return new ShaderIrOperGpr[] { - new ShaderIrOperGpr(Gpr), - new ShaderIrOperGpr(Gpr) + new ShaderIrOperGpr(gpr), + new ShaderIrOperGpr(gpr) }; } - ShaderIrOperGpr Low = new ShaderIrOperGpr(Gpr, 0); - ShaderIrOperGpr High = new ShaderIrOperGpr(Gpr, 1); + ShaderIrOperGpr low = new ShaderIrOperGpr(gpr, 0); + ShaderIrOperGpr high = new ShaderIrOperGpr(gpr, 1); return new ShaderIrOperGpr[] { - (Mask & 1) != 0 ? High : Low, - (Mask & 2) != 0 ? High : Low + (mask & 1) != 0 ? high : low, + (mask & 2) != 0 ? high : low }; } - private static ShaderIrOperGpr GprHalf0(this long OpCode, int HalfPart) + private static ShaderIrOperGpr GprHalf0(this long opCode, int halfPart) { - return new ShaderIrOperGpr(OpCode.Read(0, 0xff), HalfPart); + return new ShaderIrOperGpr(opCode.Read(0, 0xff), halfPart); } - private static ShaderIrOperGpr GprHalf28(this long OpCode, int HalfPart) + private static ShaderIrOperGpr GprHalf28(this long opCode, int halfPart) { - return new ShaderIrOperGpr(OpCode.Read(28, 0xff), HalfPart); + return new ShaderIrOperGpr(opCode.Read(28, 0xff), halfPart); } - private static ShaderIrOperImm Imm5_39(this long OpCode) + private static ShaderIrOperImm Imm5_39(this long opCode) { - return new ShaderIrOperImm(OpCode.Read(39, 0x1f)); + return new ShaderIrOperImm(opCode.Read(39, 0x1f)); } - private static ShaderIrOperImm Imm13_36(this long OpCode) + private static ShaderIrOperImm Imm13_36(this long opCode) { - return new ShaderIrOperImm(OpCode.Read(36, 0x1fff)); + return new ShaderIrOperImm(opCode.Read(36, 0x1fff)); } - private static ShaderIrOperImm Imm32_20(this long OpCode) + private static ShaderIrOperImm Imm32_20(this long opCode) { - return new ShaderIrOperImm((int)(OpCode >> 20)); + return new ShaderIrOperImm((int)(opCode >> 20)); } - private static ShaderIrOperImmf Immf32_20(this long OpCode) + private static ShaderIrOperImmf Immf32_20(this long opCode) { - return new ShaderIrOperImmf(BitConverter.Int32BitsToSingle((int)(OpCode >> 20))); + return new ShaderIrOperImmf(BitConverter.Int32BitsToSingle((int)(opCode >> 20))); } - private static ShaderIrOperImm ImmU16_20(this long OpCode) + private static ShaderIrOperImm ImmU16_20(this long opCode) { - return new ShaderIrOperImm(OpCode.Read(20, 0xffff)); + return new ShaderIrOperImm(opCode.Read(20, 0xffff)); } - private static ShaderIrOperImm Imm19_20(this long OpCode) + private static ShaderIrOperImm Imm19_20(this long opCode) { - int Value = OpCode.Read(20, 0x7ffff); + int value = opCode.Read(20, 0x7ffff); - bool Neg = OpCode.Read(56); + bool neg = opCode.Read(56); - if (Neg) + if (neg) { - Value = -Value; + value = -value; } - return new ShaderIrOperImm(Value); + return new ShaderIrOperImm(value); } - private static ShaderIrOperImmf Immf19_20(this long OpCode) + private static ShaderIrOperImmf Immf19_20(this long opCode) { - uint Imm = (uint)(OpCode >> 20) & 0x7ffff; + uint imm = (uint)(opCode >> 20) & 0x7ffff; - bool Neg = OpCode.Read(56); + bool neg = opCode.Read(56); - Imm <<= 12; + imm <<= 12; - if (Neg) + if (neg) { - Imm |= 0x80000000; + imm |= 0x80000000; } - float Value = BitConverter.Int32BitsToSingle((int)Imm); + float value = BitConverter.Int32BitsToSingle((int)imm); - return new ShaderIrOperImmf(Value); + return new ShaderIrOperImmf(value); } - private static ShaderIrOperPred Pred0(this long OpCode) + private static ShaderIrOperPred Pred0(this long opCode) { - return new ShaderIrOperPred(OpCode.Read(0, 7)); + return new ShaderIrOperPred(opCode.Read(0, 7)); } - private static ShaderIrOperPred Pred3(this long OpCode) + private static ShaderIrOperPred Pred3(this long opCode) { - return new ShaderIrOperPred(OpCode.Read(3, 7)); + return new ShaderIrOperPred(opCode.Read(3, 7)); } - private static ShaderIrOperPred Pred12(this long OpCode) + private static ShaderIrOperPred Pred12(this long opCode) { - return new ShaderIrOperPred(OpCode.Read(12, 7)); + return new ShaderIrOperPred(opCode.Read(12, 7)); } - private static ShaderIrOperPred Pred29(this long OpCode) + private static ShaderIrOperPred Pred29(this long opCode) { - return new ShaderIrOperPred(OpCode.Read(29, 7)); + return new ShaderIrOperPred(opCode.Read(29, 7)); } - private static ShaderIrNode Pred39N(this long OpCode) + private static ShaderIrNode Pred39N(this long opCode) { - ShaderIrNode Node = OpCode.Pred39(); + ShaderIrNode node = opCode.Pred39(); - if (OpCode.Read(42)) + if (opCode.Read(42)) { - Node = new ShaderIrOp(ShaderIrInst.Bnot, Node); + node = new ShaderIrOp(ShaderIrInst.Bnot, node); } - return Node; + return node; } - private static ShaderIrOperPred Pred39(this long OpCode) + private static ShaderIrOperPred Pred39(this long opCode) { - return new ShaderIrOperPred(OpCode.Read(39, 7)); + return new ShaderIrOperPred(opCode.Read(39, 7)); } - private static ShaderIrOperPred Pred48(this long OpCode) + private static ShaderIrOperPred Pred48(this long opCode) { - return new ShaderIrOperPred(OpCode.Read(48, 7)); + return new ShaderIrOperPred(opCode.Read(48, 7)); } - private static ShaderIrInst Cmp(this long OpCode) + private static ShaderIrInst Cmp(this long opCode) { - switch (OpCode.Read(49, 7)) + switch (opCode.Read(49, 7)) { case 1: return ShaderIrInst.Clt; case 2: return ShaderIrInst.Ceq; @@ -234,12 +234,12 @@ namespace Ryujinx.Graphics.Gal.Shader case 6: return ShaderIrInst.Cge; } - throw new ArgumentException(nameof(OpCode)); + throw new ArgumentException(nameof(opCode)); } - private static ShaderIrInst CmpF(this long OpCode) + private static ShaderIrInst CmpF(this long opCode) { - switch (OpCode.Read(48, 0xf)) + switch (opCode.Read(48, 0xf)) { case 0x1: return ShaderIrInst.Fclt; case 0x2: return ShaderIrInst.Fceq; @@ -257,57 +257,57 @@ namespace Ryujinx.Graphics.Gal.Shader case 0xe: return ShaderIrInst.Fcgeu; } - throw new ArgumentException(nameof(OpCode)); + throw new ArgumentException(nameof(opCode)); } - private static ShaderIrInst BLop45(this long OpCode) + private static ShaderIrInst BLop45(this long opCode) { - switch (OpCode.Read(45, 3)) + switch (opCode.Read(45, 3)) { case 0: return ShaderIrInst.Band; case 1: return ShaderIrInst.Bor; case 2: return ShaderIrInst.Bxor; } - throw new ArgumentException(nameof(OpCode)); + throw new ArgumentException(nameof(opCode)); } - private static ShaderIrInst BLop24(this long OpCode) + private static ShaderIrInst BLop24(this long opCode) { - switch (OpCode.Read(24, 3)) + switch (opCode.Read(24, 3)) { case 0: return ShaderIrInst.Band; case 1: return ShaderIrInst.Bor; case 2: return ShaderIrInst.Bxor; } - throw new ArgumentException(nameof(OpCode)); + throw new ArgumentException(nameof(opCode)); } - private static ShaderIrNode PredNode(this long OpCode, ShaderIrNode Node) + private static ShaderIrNode PredNode(this long opCode, ShaderIrNode node) { - ShaderIrOperPred Pred = OpCode.PredNode(); + ShaderIrOperPred pred = opCode.PredNode(); - if (Pred.Index != ShaderIrOperPred.UnusedIndex) + if (pred.Index != ShaderIrOperPred.UnusedIndex) { - bool Inv = OpCode.Read(19); + bool inv = opCode.Read(19); - Node = new ShaderIrCond(Pred, Node, Inv); + node = new ShaderIrCond(pred, node, inv); } - return Node; + return node; } - private static ShaderIrOperPred PredNode(this long OpCode) + private static ShaderIrOperPred PredNode(this long opCode) { - int Pred = OpCode.Read(16, 0xf); + int pred = opCode.Read(16, 0xf); - if (Pred != 0xf) + if (pred != 0xf) { - Pred &= 7; + pred &= 7; } - return new ShaderIrOperPred(Pred); + return new ShaderIrOperPred(pred); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeSpecial.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeSpecial.cs index 35abdb76..9098ca5e 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeSpecial.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeSpecial.cs @@ -2,23 +2,23 @@ { static partial class ShaderDecode { - public static void Out_R(ShaderIrBlock Block, long OpCode, int Position) + public static void Out_R(ShaderIrBlock block, long opCode, int position) { //TODO: Those registers have to be used for something - ShaderIrOperGpr Gpr0 = OpCode.Gpr0(); - ShaderIrOperGpr Gpr8 = OpCode.Gpr8(); - ShaderIrOperGpr Gpr20 = OpCode.Gpr20(); + ShaderIrOperGpr gpr0 = opCode.Gpr0(); + ShaderIrOperGpr gpr8 = opCode.Gpr8(); + ShaderIrOperGpr gpr20 = opCode.Gpr20(); - int Type = OpCode.Read(39, 3); + int type = opCode.Read(39, 3); - if ((Type & 1) != 0) + if ((type & 1) != 0) { - Block.AddNode(OpCode.PredNode(new ShaderIrOp(ShaderIrInst.Emit))); + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Emit))); } - if ((Type & 2) != 0) + if ((type & 2) != 0) { - Block.AddNode(OpCode.PredNode(new ShaderIrOp(ShaderIrInst.Cut))); + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Cut))); } } } diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs index f8c07f31..4b23f8d0 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs @@ -8,74 +8,74 @@ namespace Ryujinx.Graphics.Gal.Shader private const bool AddDbgComments = true; - public static ShaderIrBlock[] Decode(IGalMemory Memory, long Start) + public static ShaderIrBlock[] Decode(IGalMemory memory, long start) { - Dictionary Visited = new Dictionary(); - Dictionary VisitedEnd = new Dictionary(); + Dictionary visited = new Dictionary(); + Dictionary visitedEnd = new Dictionary(); - Queue Blocks = new Queue(); + Queue blocks = new Queue(); - long Beginning = Start + HeaderSize; + long beginning = start + HeaderSize; - ShaderIrBlock Enqueue(int Position, ShaderIrBlock Source = null) + ShaderIrBlock Enqueue(int position, ShaderIrBlock source = null) { - if (!Visited.TryGetValue(Position, out ShaderIrBlock Output)) + if (!visited.TryGetValue(position, out ShaderIrBlock output)) { - Output = new ShaderIrBlock(Position); + output = new ShaderIrBlock(position); - Blocks.Enqueue(Output); + blocks.Enqueue(output); - Visited.Add(Position, Output); + visited.Add(position, output); } - if (Source != null) + if (source != null) { - Output.Sources.Add(Source); + output.Sources.Add(source); } - return Output; + return output; } - ShaderIrBlock Entry = Enqueue(0); + ShaderIrBlock entry = Enqueue(0); - while (Blocks.Count > 0) + while (blocks.Count > 0) { - ShaderIrBlock Current = Blocks.Dequeue(); + ShaderIrBlock current = blocks.Dequeue(); - FillBlock(Memory, Current, Beginning); + FillBlock(memory, current, beginning); //Set child blocks. "Branch" is the block the branch instruction //points to (when taken), "Next" is the block at the next address, //executed when the branch is not taken. For Unconditional Branches //or end of shader, Next is null. - if (Current.Nodes.Count > 0) + if (current.Nodes.Count > 0) { - ShaderIrNode LastNode = Current.GetLastNode(); + ShaderIrNode lastNode = current.GetLastNode(); - ShaderIrOp InnerOp = GetInnermostOp(LastNode); + ShaderIrOp innerOp = GetInnermostOp(lastNode); - if (InnerOp?.Inst == ShaderIrInst.Bra) + if (innerOp?.Inst == ShaderIrInst.Bra) { - int Target = ((ShaderIrOperImm)InnerOp.OperandA).Value; + int target = ((ShaderIrOperImm)innerOp.OperandA).Value; - Current.Branch = Enqueue(Target, Current); + current.Branch = Enqueue(target, current); } - foreach (ShaderIrNode Node in Current.Nodes) + foreach (ShaderIrNode node in current.Nodes) { - InnerOp = GetInnermostOp(Node); + innerOp = GetInnermostOp(node); - if (InnerOp is ShaderIrOp CurrOp && CurrOp.Inst == ShaderIrInst.Ssy) + if (innerOp is ShaderIrOp currOp && currOp.Inst == ShaderIrInst.Ssy) { - int Target = ((ShaderIrOperImm)CurrOp.OperandA).Value; + int target = ((ShaderIrOperImm)currOp.OperandA).Value; - Enqueue(Target, Current); + Enqueue(target, current); } } - if (NodeHasNext(LastNode)) + if (NodeHasNext(lastNode)) { - Current.Next = Enqueue(Current.EndPosition); + current.Next = Enqueue(current.EndPosition); } } @@ -83,136 +83,136 @@ namespace Ryujinx.Graphics.Gal.Shader //then we need to split the bigger block and have two small blocks, //the end position of the bigger "Current" block should then be == to //the position of the "Smaller" block. - while (VisitedEnd.TryGetValue(Current.EndPosition, out ShaderIrBlock Smaller)) + while (visitedEnd.TryGetValue(current.EndPosition, out ShaderIrBlock smaller)) { - if (Current.Position > Smaller.Position) + if (current.Position > smaller.Position) { - ShaderIrBlock Temp = Smaller; + ShaderIrBlock temp = smaller; - Smaller = Current; - Current = Temp; + smaller = current; + current = temp; } - Current.EndPosition = Smaller.Position; - Current.Next = Smaller; - Current.Branch = null; + current.EndPosition = smaller.Position; + current.Next = smaller; + current.Branch = null; - Current.Nodes.RemoveRange( - Current.Nodes.Count - Smaller.Nodes.Count, - Smaller.Nodes.Count); + current.Nodes.RemoveRange( + current.Nodes.Count - smaller.Nodes.Count, + smaller.Nodes.Count); - VisitedEnd[Smaller.EndPosition] = Smaller; + visitedEnd[smaller.EndPosition] = smaller; } - VisitedEnd.Add(Current.EndPosition, Current); + visitedEnd.Add(current.EndPosition, current); } //Make and sort Graph blocks array by position. - ShaderIrBlock[] Graph = new ShaderIrBlock[Visited.Count]; + ShaderIrBlock[] graph = new ShaderIrBlock[visited.Count]; - while (Visited.Count > 0) + while (visited.Count > 0) { - uint FirstPos = uint.MaxValue; + uint firstPos = uint.MaxValue; - foreach (ShaderIrBlock Block in Visited.Values) + foreach (ShaderIrBlock block in visited.Values) { - if (FirstPos > (uint)Block.Position) - FirstPos = (uint)Block.Position; + if (firstPos > (uint)block.Position) + firstPos = (uint)block.Position; } - ShaderIrBlock Current = Visited[(int)FirstPos]; + ShaderIrBlock current = visited[(int)firstPos]; do { - Graph[Graph.Length - Visited.Count] = Current; + graph[graph.Length - visited.Count] = current; - Visited.Remove(Current.Position); + visited.Remove(current.Position); - Current = Current.Next; + current = current.Next; } - while (Current != null); + while (current != null); } - return Graph; + return graph; } - private static void FillBlock(IGalMemory Memory, ShaderIrBlock Block, long Beginning) + private static void FillBlock(IGalMemory memory, ShaderIrBlock block, long beginning) { - int Position = Block.Position; + int position = block.Position; do { //Ignore scheduling instructions, which are written every 32 bytes. - if ((Position & 0x1f) == 0) + if ((position & 0x1f) == 0) { - Position += 8; + position += 8; continue; } - uint Word0 = (uint)Memory.ReadInt32(Position + Beginning + 0); - uint Word1 = (uint)Memory.ReadInt32(Position + Beginning + 4); + uint word0 = (uint)memory.ReadInt32(position + beginning + 0); + uint word1 = (uint)memory.ReadInt32(position + beginning + 4); - Position += 8; + position += 8; - long OpCode = Word0 | (long)Word1 << 32; + long opCode = word0 | (long)word1 << 32; - ShaderDecodeFunc Decode = ShaderOpCodeTable.GetDecoder(OpCode); + ShaderDecodeFunc decode = ShaderOpCodeTable.GetDecoder(opCode); if (AddDbgComments) { - string DbgOpCode = $"0x{(Position - 8):x16}: 0x{OpCode:x16} "; + string dbgOpCode = $"0x{(position - 8):x16}: 0x{opCode:x16} "; - DbgOpCode += (Decode?.Method.Name ?? "???"); + dbgOpCode += (decode?.Method.Name ?? "???"); - if (Decode == ShaderDecode.Bra || Decode == ShaderDecode.Ssy) + if (decode == ShaderDecode.Bra || decode == ShaderDecode.Ssy) { - int Offset = ((int)(OpCode >> 20) << 8) >> 8; + int offset = ((int)(opCode >> 20) << 8) >> 8; - long Target = Position + Offset; + long target = position + offset; - DbgOpCode += " (0x" + Target.ToString("x16") + ")"; + dbgOpCode += " (0x" + target.ToString("x16") + ")"; } - Block.AddNode(new ShaderIrCmnt(DbgOpCode)); + block.AddNode(new ShaderIrCmnt(dbgOpCode)); } - if (Decode == null) + if (decode == null) { continue; } - Decode(Block, OpCode, Position); + decode(block, opCode, position); } - while (!IsFlowChange(Block.GetLastNode())); + while (!IsFlowChange(block.GetLastNode())); - Block.EndPosition = Position; + block.EndPosition = position; } - private static bool IsFlowChange(ShaderIrNode Node) + private static bool IsFlowChange(ShaderIrNode node) { - return !NodeHasNext(GetInnermostOp(Node)); + return !NodeHasNext(GetInnermostOp(node)); } - private static ShaderIrOp GetInnermostOp(ShaderIrNode Node) + private static ShaderIrOp GetInnermostOp(ShaderIrNode node) { - if (Node is ShaderIrCond Cond) + if (node is ShaderIrCond cond) { - Node = Cond.Child; + node = cond.Child; } - return Node is ShaderIrOp Op ? Op : null; + return node is ShaderIrOp op ? op : null; } - private static bool NodeHasNext(ShaderIrNode Node) + private static bool NodeHasNext(ShaderIrNode node) { - if (!(Node is ShaderIrOp Op)) + if (!(node is ShaderIrOp op)) { return true; } - return Op.Inst != ShaderIrInst.Exit && - Op.Inst != ShaderIrInst.Bra; + return op.Inst != ShaderIrInst.Exit && + op.Inst != ShaderIrInst.Bra; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs b/Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs index eca90fc3..2f9326e1 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs @@ -11,9 +11,9 @@ namespace Ryujinx.Graphics.Gal.Shader public bool Enabled => Red || Green || Blue || Alpha; - public bool ComponentEnabled(int Component) + public bool ComponentEnabled(int component) { - switch (Component) + switch (component) { case 0: return Red; case 1: return Green; @@ -21,7 +21,7 @@ namespace Ryujinx.Graphics.Gal.Shader case 3: return Alpha; } - throw new ArgumentException(nameof(Component)); + throw new ArgumentException(nameof(component)); } } @@ -59,88 +59,88 @@ namespace Ryujinx.Graphics.Gal.Shader public bool OmapSampleMask { get; private set; } public bool OmapDepth { get; private set; } - public ShaderHeader(IGalMemory Memory, long Position) + public ShaderHeader(IGalMemory memory, long position) { - uint CommonWord0 = (uint)Memory.ReadInt32(Position + 0); - uint CommonWord1 = (uint)Memory.ReadInt32(Position + 4); - uint CommonWord2 = (uint)Memory.ReadInt32(Position + 8); - uint CommonWord3 = (uint)Memory.ReadInt32(Position + 12); - uint CommonWord4 = (uint)Memory.ReadInt32(Position + 16); + uint commonWord0 = (uint)memory.ReadInt32(position + 0); + uint commonWord1 = (uint)memory.ReadInt32(position + 4); + uint commonWord2 = (uint)memory.ReadInt32(position + 8); + uint commonWord3 = (uint)memory.ReadInt32(position + 12); + uint commonWord4 = (uint)memory.ReadInt32(position + 16); - SphType = ReadBits(CommonWord0, 0, 5); - Version = ReadBits(CommonWord0, 5, 5); - ShaderType = ReadBits(CommonWord0, 10, 4); - MrtEnable = ReadBits(CommonWord0, 14, 1) != 0; - KillsPixels = ReadBits(CommonWord0, 15, 1) != 0; - DoesGlobalStore = ReadBits(CommonWord0, 16, 1) != 0; - SassVersion = ReadBits(CommonWord0, 17, 4); - DoesLoadOrStore = ReadBits(CommonWord0, 26, 1) != 0; - DoesFp64 = ReadBits(CommonWord0, 27, 1) != 0; - StreamOutMask = ReadBits(CommonWord0, 28, 4); + SphType = ReadBits(commonWord0, 0, 5); + Version = ReadBits(commonWord0, 5, 5); + ShaderType = ReadBits(commonWord0, 10, 4); + MrtEnable = ReadBits(commonWord0, 14, 1) != 0; + KillsPixels = ReadBits(commonWord0, 15, 1) != 0; + DoesGlobalStore = ReadBits(commonWord0, 16, 1) != 0; + SassVersion = ReadBits(commonWord0, 17, 4); + DoesLoadOrStore = ReadBits(commonWord0, 26, 1) != 0; + DoesFp64 = ReadBits(commonWord0, 27, 1) != 0; + StreamOutMask = ReadBits(commonWord0, 28, 4); - ShaderLocalMemoryLowSize = ReadBits(CommonWord1, 0, 24); - PerPatchAttributeCount = ReadBits(CommonWord1, 24, 8); + ShaderLocalMemoryLowSize = ReadBits(commonWord1, 0, 24); + PerPatchAttributeCount = ReadBits(commonWord1, 24, 8); - ShaderLocalMemoryHighSize = ReadBits(CommonWord2, 0, 24); - ThreadsPerInputPrimitive = ReadBits(CommonWord2, 24, 8); + ShaderLocalMemoryHighSize = ReadBits(commonWord2, 0, 24); + ThreadsPerInputPrimitive = ReadBits(commonWord2, 24, 8); - ShaderLocalMemoryCrsSize = ReadBits(CommonWord3, 0, 24); - OutputTopology = ReadBits(CommonWord3, 24, 4); + ShaderLocalMemoryCrsSize = ReadBits(commonWord3, 0, 24); + OutputTopology = ReadBits(commonWord3, 24, 4); - MaxOutputVertexCount = ReadBits(CommonWord4, 0, 12); - StoreReqStart = ReadBits(CommonWord4, 12, 8); - StoreReqEnd = ReadBits(CommonWord4, 24, 8); + MaxOutputVertexCount = ReadBits(commonWord4, 0, 12); + StoreReqStart = ReadBits(commonWord4, 12, 8); + StoreReqEnd = ReadBits(commonWord4, 24, 8); //Type 2 (fragment?) reading - uint Type2OmapTarget = (uint)Memory.ReadInt32(Position + 72); - uint Type2Omap = (uint)Memory.ReadInt32(Position + 76); + uint type2OmapTarget = (uint)memory.ReadInt32(position + 72); + uint type2Omap = (uint)memory.ReadInt32(position + 76); OmapTargets = new OmapTarget[8]; for (int i = 0; i < OmapTargets.Length; i++) { - int Offset = i * 4; + int offset = i * 4; OmapTargets[i] = new OmapTarget { - Red = ReadBits(Type2OmapTarget, Offset + 0, 1) != 0, - Green = ReadBits(Type2OmapTarget, Offset + 1, 1) != 0, - Blue = ReadBits(Type2OmapTarget, Offset + 2, 1) != 0, - Alpha = ReadBits(Type2OmapTarget, Offset + 3, 1) != 0 + Red = ReadBits(type2OmapTarget, offset + 0, 1) != 0, + Green = ReadBits(type2OmapTarget, offset + 1, 1) != 0, + Blue = ReadBits(type2OmapTarget, offset + 2, 1) != 0, + Alpha = ReadBits(type2OmapTarget, offset + 3, 1) != 0 }; } - OmapSampleMask = ReadBits(Type2Omap, 0, 1) != 0; - OmapDepth = ReadBits(Type2Omap, 1, 1) != 0; + OmapSampleMask = ReadBits(type2Omap, 0, 1) != 0; + OmapDepth = ReadBits(type2Omap, 1, 1) != 0; } public int DepthRegister { get { - int Count = 0; + int count = 0; - for (int Index = 0; Index < OmapTargets.Length; Index++) + for (int index = 0; index < OmapTargets.Length; index++) { - for (int Component = 0; Component < 4; Component++) + for (int component = 0; component < 4; component++) { - if (OmapTargets[Index].ComponentEnabled(Component)) + if (OmapTargets[index].ComponentEnabled(component)) { - Count++; + count++; } } } // Depth register is always two registers after the last color output - return Count + 1; + return count + 1; } } - private static int ReadBits(uint Word, int Offset, int BitWidth) + private static int ReadBits(uint word, int offset, int bitWidth) { - uint Mask = (1u << BitWidth) - 1u; + uint mask = (1u << bitWidth) - 1u; - return (int)((Word >> Offset) & Mask); + return (int)((word >> offset) & mask); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrAsg.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrAsg.cs index 00f8f6a5..53871a14 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrAsg.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrAsg.cs @@ -5,10 +5,10 @@ namespace Ryujinx.Graphics.Gal.Shader public ShaderIrNode Dst { get; set; } public ShaderIrNode Src { get; set; } - public ShaderIrAsg(ShaderIrNode Dst, ShaderIrNode Src) + public ShaderIrAsg(ShaderIrNode dst, ShaderIrNode src) { - this.Dst = Dst; - this.Src = Src; + Dst = dst; + Src = src; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs index 782f9626..49257d28 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs @@ -14,18 +14,18 @@ namespace Ryujinx.Graphics.Gal.Shader public List Nodes { get; private set; } - public ShaderIrBlock(int Position) + public ShaderIrBlock(int position) { - this.Position = Position; + Position = position; Sources = new List(); Nodes = new List(); } - public void AddNode(ShaderIrNode Node) + public void AddNode(ShaderIrNode node) { - Nodes.Add(Node); + Nodes.Add(node); } public ShaderIrNode[] GetNodes() diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrCmnt.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrCmnt.cs index 03031ec5..5da04e5e 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrCmnt.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrCmnt.cs @@ -4,9 +4,9 @@ namespace Ryujinx.Graphics.Gal.Shader { public string Comment { get; private set; } - public ShaderIrCmnt(string Comment) + public ShaderIrCmnt(string comment) { - this.Comment = Comment; + Comment = comment; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrCond.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrCond.cs index 8fb01660..34acf90d 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrCond.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrCond.cs @@ -7,11 +7,11 @@ namespace Ryujinx.Graphics.Gal.Shader public bool Not { get; private set; } - public ShaderIrCond(ShaderIrNode Pred, ShaderIrNode Child, bool Not) + public ShaderIrCond(ShaderIrNode pred, ShaderIrNode child, bool not) { - this.Pred = Pred; - this.Child = Child; - this.Not = Not; + Pred = pred; + Child = child; + Not = not; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaIpa.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaIpa.cs index 3b884621..07db6467 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaIpa.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaIpa.cs @@ -4,9 +4,9 @@ { public ShaderIpaMode Mode { get; private set; } - public ShaderIrMetaIpa(ShaderIpaMode Mode) + public ShaderIrMetaIpa(ShaderIpaMode mode) { - this.Mode = Mode; + Mode = mode; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaTex.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaTex.cs index 72ea221a..e0265138 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaTex.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaTex.cs @@ -13,12 +13,12 @@ namespace Ryujinx.Graphics.Gal.Shader public ShaderIrOperGpr DepthCompare; public int Component; // for TLD4(S) - public ShaderIrMetaTex(int Elem, GalTextureTarget TextureTarget, TextureInstructionSuffix TextureInstructionSuffix, params ShaderIrNode[] Coordinates) + public ShaderIrMetaTex(int elem, GalTextureTarget textureTarget, TextureInstructionSuffix textureInstructionSuffix, params ShaderIrNode[] coordinates) { - this.Elem = Elem; - this.TextureTarget = TextureTarget; - this.TextureInstructionSuffix = TextureInstructionSuffix; - this.Coordinates = Coordinates; + Elem = elem; + TextureTarget = textureTarget; + TextureInstructionSuffix = textureInstructionSuffix; + Coordinates = coordinates; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaTexq.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaTexq.cs index 92871137..c925ea4e 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaTexq.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrMetaTexq.cs @@ -6,10 +6,10 @@ namespace Ryujinx.Graphics.Gal.Shader public int Elem { get; private set; } - public ShaderIrMetaTexq(ShaderTexqInfo Info, int Elem) + public ShaderIrMetaTexq(ShaderTexqInfo info, int elem) { - this.Info = Info; - this.Elem = Elem; + Info = info; + Elem = elem; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrOp.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrOp.cs index 12a6123c..c91c3926 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrOp.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrOp.cs @@ -9,17 +9,17 @@ namespace Ryujinx.Graphics.Gal.Shader public ShaderIrMeta MetaData { get; set; } public ShaderIrOp( - ShaderIrInst Inst, - ShaderIrNode OperandA = null, - ShaderIrNode OperandB = null, - ShaderIrNode OperandC = null, - ShaderIrMeta MetaData = null) + ShaderIrInst inst, + ShaderIrNode operandA = null, + ShaderIrNode operandB = null, + ShaderIrNode operandC = null, + ShaderIrMeta metaData = null) { - this.Inst = Inst; - this.OperandA = OperandA; - this.OperandB = OperandB; - this.OperandC = OperandC; - this.MetaData = MetaData; + Inst = inst; + OperandA = operandA; + OperandB = operandB; + OperandC = operandC; + MetaData = metaData; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperAbuf.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperAbuf.cs index f17d9c0e..1f339e80 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperAbuf.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperAbuf.cs @@ -6,10 +6,10 @@ namespace Ryujinx.Graphics.Gal.Shader public ShaderIrNode Vertex { get; private set; } - public ShaderIrOperAbuf(int Offs, ShaderIrNode Vertex) + public ShaderIrOperAbuf(int offs, ShaderIrNode vertex) { - this.Offs = Offs; - this.Vertex = Vertex; + Offs = offs; + Vertex = vertex; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperCbuf.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperCbuf.cs index b040c5c6..9f419bbb 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperCbuf.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperCbuf.cs @@ -7,11 +7,11 @@ namespace Ryujinx.Graphics.Gal.Shader public ShaderIrNode Offs { get; private set; } - public ShaderIrOperCbuf(int Index, int Pos, ShaderIrNode Offs = null) + public ShaderIrOperCbuf(int index, int pos, ShaderIrNode offs = null) { - this.Index = Index; - this.Pos = Pos; - this.Offs = Offs; + Index = index; + Pos = pos; + Offs = offs; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperGpr.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperGpr.cs index b4a5cab4..0d102d89 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperGpr.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperGpr.cs @@ -2,35 +2,35 @@ namespace Ryujinx.Graphics.Gal.Shader { class ShaderIrOperGpr : ShaderIrNode { - public const int ZRIndex = 0xff; + public const int ZrIndex = 0xff; - public bool IsConst => Index == ZRIndex; + public bool IsConst => Index == ZrIndex; - public bool IsValidRegister => (uint)Index <= ZRIndex; + public bool IsValidRegister => (uint)Index <= ZrIndex; public int Index { get; set; } public int HalfPart { get; set; } public ShaderRegisterSize RegisterSize { get; private set; } - public ShaderIrOperGpr(int Index) + public ShaderIrOperGpr(int index) { - this.Index = Index; + Index = index; RegisterSize = ShaderRegisterSize.Single; } - public ShaderIrOperGpr(int Index, int HalfPart) + public ShaderIrOperGpr(int index, int halfPart) { - this.Index = Index; - this.HalfPart = HalfPart; + Index = index; + HalfPart = halfPart; RegisterSize = ShaderRegisterSize.Half; } - public static ShaderIrOperGpr MakeTemporary(int Index = 0) + public static ShaderIrOperGpr MakeTemporary(int index = 0) { - return new ShaderIrOperGpr(0x100 + Index); + return new ShaderIrOperGpr(0x100 + index); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperImm.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperImm.cs index ba2c2c9b..6b23b365 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperImm.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperImm.cs @@ -4,9 +4,9 @@ namespace Ryujinx.Graphics.Gal.Shader { public int Value { get; private set; } - public ShaderIrOperImm(int Value) + public ShaderIrOperImm(int value) { - this.Value = Value; + Value = value; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperImmf.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperImmf.cs index 3c27e483..5b08c5b1 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperImmf.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperImmf.cs @@ -4,9 +4,9 @@ namespace Ryujinx.Graphics.Gal.Shader { public float Value { get; private set; } - public ShaderIrOperImmf(float Value) + public ShaderIrOperImmf(float value) { - this.Value = Value; + Value = value; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperPred.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperPred.cs index 74cca0ef..6c16a145 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrOperPred.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrOperPred.cs @@ -9,9 +9,9 @@ namespace Ryujinx.Graphics.Gal.Shader public int Index { get; set; } - public ShaderIrOperPred(int Index) + public ShaderIrOperPred(int index) { - this.Index = Index; + Index = index; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderOpCodeTable.cs b/Ryujinx.Graphics/Gal/Shader/ShaderOpCodeTable.cs index d2bbd38c..1edf91a0 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderOpCodeTable.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderOpCodeTable.cs @@ -12,18 +12,18 @@ namespace Ryujinx.Graphics.Gal.Shader public int XBits; - public ShaderDecodeEntry(ShaderDecodeFunc Func, int XBits) + public ShaderDecodeEntry(ShaderDecodeFunc func, int xBits) { - this.Func = Func; - this.XBits = XBits; + Func = func; + XBits = xBits; } } - private static ShaderDecodeEntry[] OpCodes; + private static ShaderDecodeEntry[] _opCodes; static ShaderOpCodeTable() { - OpCodes = new ShaderDecodeEntry[1 << EncodingBits]; + _opCodes = new ShaderDecodeEntry[1 << EncodingBits]; #region Instructions Set("0100110000000x", ShaderDecode.Bfe_C); @@ -123,7 +123,7 @@ namespace Ryujinx.Graphics.Gal.Shader Set("1101x00xxxxxxx", ShaderDecode.Texs); Set("1101101xxxxxxx", ShaderDecode.Tlds); Set("110010xxxx111x", ShaderDecode.Tld4); - Set("1101111100xxxx", ShaderDecode.Tld4s); + Set("1101111100xxxx", ShaderDecode.Tld4S); Set("01011111xxxxxx", ShaderDecode.Vmad); Set("0100111xxxxxxx", ShaderDecode.Xmad_CR); Set("0011011x00xxxx", ShaderDecode.Xmad_I); @@ -132,59 +132,59 @@ namespace Ryujinx.Graphics.Gal.Shader #endregion } - private static void Set(string Encoding, ShaderDecodeFunc Func) + private static void Set(string encoding, ShaderDecodeFunc func) { - if (Encoding.Length != EncodingBits) + if (encoding.Length != EncodingBits) { - throw new ArgumentException(nameof(Encoding)); + throw new ArgumentException(nameof(encoding)); } - int Bit = Encoding.Length - 1; - int Value = 0; - int XMask = 0; - int XBits = 0; + int bit = encoding.Length - 1; + int value = 0; + int xMask = 0; + int xBits = 0; - int[] XPos = new int[Encoding.Length]; + int[] xPos = new int[encoding.Length]; - for (int Index = 0; Index < Encoding.Length; Index++, Bit--) + for (int index = 0; index < encoding.Length; index++, bit--) { - char Chr = Encoding[Index]; + char chr = encoding[index]; - if (Chr == '1') + if (chr == '1') { - Value |= 1 << Bit; + value |= 1 << bit; } - else if (Chr == 'x') + else if (chr == 'x') { - XMask |= 1 << Bit; + xMask |= 1 << bit; - XPos[XBits++] = Bit; + xPos[xBits++] = bit; } } - XMask = ~XMask; + xMask = ~xMask; - ShaderDecodeEntry Entry = new ShaderDecodeEntry(Func, XBits); + ShaderDecodeEntry entry = new ShaderDecodeEntry(func, xBits); - for (int Index = 0; Index < (1 << XBits); Index++) + for (int index = 0; index < (1 << xBits); index++) { - Value &= XMask; + value &= xMask; - for (int X = 0; X < XBits; X++) + for (int x = 0; x < xBits; x++) { - Value |= ((Index >> X) & 1) << XPos[X]; + value |= ((index >> x) & 1) << xPos[x]; } - if (OpCodes[Value] == null || OpCodes[Value].XBits > XBits) + if (_opCodes[value] == null || _opCodes[value].XBits > xBits) { - OpCodes[Value] = Entry; + _opCodes[value] = entry; } } } - public static ShaderDecodeFunc GetDecoder(long OpCode) + public static ShaderDecodeFunc GetDecoder(long opCode) { - return OpCodes[(ulong)OpCode >> (64 - EncodingBits)]?.Func; + return _opCodes[(ulong)opCode >> (64 - EncodingBits)]?.Func; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderOper.cs b/Ryujinx.Graphics/Gal/Shader/ShaderOper.cs index aa485482..22a2ab85 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderOper.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderOper.cs @@ -2,10 +2,10 @@ namespace Ryujinx.Graphics.Gal.Shader { enum ShaderOper { - CR, + Cr, Imm, Immf, - RC, - RR + Rc, + Rr } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/ShaderDeclInfo.cs b/Ryujinx.Graphics/Gal/ShaderDeclInfo.cs index ed1955cd..f1f4650c 100644 --- a/Ryujinx.Graphics/Gal/ShaderDeclInfo.cs +++ b/Ryujinx.Graphics/Gal/ShaderDeclInfo.cs @@ -16,29 +16,29 @@ namespace Ryujinx.Graphics.Gal public TextureInstructionSuffix TextureSuffix { get; private set; } public ShaderDeclInfo( - string Name, - int Index, - bool IsCb = false, - int Cbuf = 0, - int Size = 1, - GalTextureTarget TextureTarget = GalTextureTarget.TwoD, - TextureInstructionSuffix TextureSuffix = TextureInstructionSuffix.None) + string name, + int index, + bool isCb = false, + int cbuf = 0, + int size = 1, + GalTextureTarget textureTarget = GalTextureTarget.TwoD, + TextureInstructionSuffix textureSuffix = TextureInstructionSuffix.None) { - this.Name = Name; - this.Index = Index; - this.IsCb = IsCb; - this.Cbuf = Cbuf; - this.Size = Size; + Name = name; + Index = index; + IsCb = isCb; + Cbuf = cbuf; + Size = size; - this.TextureTarget = TextureTarget; - this.TextureSuffix = TextureSuffix; + TextureTarget = textureTarget; + TextureSuffix = textureSuffix; } - internal void Enlarge(int NewSize) + internal void Enlarge(int newSize) { - if (Size < NewSize) + if (Size < newSize) { - Size = NewSize; + Size = newSize; } } } diff --git a/Ryujinx.Graphics/Gal/ShaderDumper.cs b/Ryujinx.Graphics/Gal/ShaderDumper.cs index 21e92491..726447e4 100644 --- a/Ryujinx.Graphics/Gal/ShaderDumper.cs +++ b/Ryujinx.Graphics/Gal/ShaderDumper.cs @@ -5,67 +5,67 @@ namespace Ryujinx.Graphics.Gal { static class ShaderDumper { - private static string RuntimeDir; + private static string _runtimeDir; public static int DumpIndex { get; private set; } = 1; - public static void Dump(IGalMemory Memory, long Position, GalShaderType Type, string ExtSuffix = "") + public static void Dump(IGalMemory memory, long position, GalShaderType type, string extSuffix = "") { if (!IsDumpEnabled()) { return; } - string FileName = "Shader" + DumpIndex.ToString("d4") + "." + ShaderExtension(Type) + ExtSuffix + ".bin"; + string fileName = "Shader" + DumpIndex.ToString("d4") + "." + ShaderExtension(type) + extSuffix + ".bin"; - string FullPath = Path.Combine(FullDir(), FileName); - string CodePath = Path.Combine(CodeDir(), FileName); + string fullPath = Path.Combine(FullDir(), fileName); + string codePath = Path.Combine(CodeDir(), fileName); DumpIndex++; - using (FileStream FullFile = File.Create(FullPath)) - using (FileStream CodeFile = File.Create(CodePath)) + using (FileStream fullFile = File.Create(fullPath)) + using (FileStream codeFile = File.Create(codePath)) { - BinaryWriter FullWriter = new BinaryWriter(FullFile); - BinaryWriter CodeWriter = new BinaryWriter(CodeFile); + BinaryWriter fullWriter = new BinaryWriter(fullFile); + BinaryWriter codeWriter = new BinaryWriter(codeFile); for (long i = 0; i < 0x50; i += 4) { - FullWriter.Write(Memory.ReadInt32(Position + i)); + fullWriter.Write(memory.ReadInt32(position + i)); } - long Offset = 0; + long offset = 0; - ulong Instruction = 0; + ulong instruction = 0; //Dump until a NOP instruction is found - while ((Instruction >> 48 & 0xfff8) != 0x50b0) + while ((instruction >> 48 & 0xfff8) != 0x50b0) { - uint Word0 = (uint)Memory.ReadInt32(Position + 0x50 + Offset + 0); - uint Word1 = (uint)Memory.ReadInt32(Position + 0x50 + Offset + 4); + uint word0 = (uint)memory.ReadInt32(position + 0x50 + offset + 0); + uint word1 = (uint)memory.ReadInt32(position + 0x50 + offset + 4); - Instruction = Word0 | (ulong)Word1 << 32; + instruction = word0 | (ulong)word1 << 32; //Zero instructions (other kind of NOP) stop immediatly, //this is to avoid two rows of zeroes - if (Instruction == 0) + if (instruction == 0) { break; } - FullWriter.Write(Instruction); - CodeWriter.Write(Instruction); + fullWriter.Write(instruction); + codeWriter.Write(instruction); - Offset += 8; + offset += 8; } //Align to meet nvdisasm requeriments - while (Offset % 0x20 != 0) + while (offset % 0x20 != 0) { - FullWriter.Write(0); - CodeWriter.Write(0); + fullWriter.Write(0); + codeWriter.Write(0); - Offset += 4; + offset += 4; } } } @@ -87,37 +87,37 @@ namespace Ryujinx.Graphics.Gal private static string DumpDir() { - if (string.IsNullOrEmpty(RuntimeDir)) + if (string.IsNullOrEmpty(_runtimeDir)) { - int Index = 1; + int index = 1; do { - RuntimeDir = Path.Combine(GraphicsConfig.ShadersDumpPath, "Dumps" + Index.ToString("d2")); + _runtimeDir = Path.Combine(GraphicsConfig.ShadersDumpPath, "Dumps" + index.ToString("d2")); - Index++; + index++; } - while (Directory.Exists(RuntimeDir)); + while (Directory.Exists(_runtimeDir)); - Directory.CreateDirectory(RuntimeDir); + Directory.CreateDirectory(_runtimeDir); } - return RuntimeDir; + return _runtimeDir; } - private static string CreateAndReturn(string Dir) + private static string CreateAndReturn(string dir) { - if (!Directory.Exists(Dir)) + if (!Directory.Exists(dir)) { - Directory.CreateDirectory(Dir); + Directory.CreateDirectory(dir); } - return Dir; + return dir; } - private static string ShaderExtension(GalShaderType Type) + private static string ShaderExtension(GalShaderType type) { - switch (Type) + switch (type) { case GalShaderType.Vertex: return "vert"; case GalShaderType.TessControl: return "tesc"; @@ -125,7 +125,7 @@ namespace Ryujinx.Graphics.Gal case GalShaderType.Geometry: return "geom"; case GalShaderType.Fragment: return "frag"; - default: throw new ArgumentException(nameof(Type)); + default: throw new ArgumentException(nameof(type)); } } } diff --git a/Ryujinx.Graphics/Gal/ShaderException.cs b/Ryujinx.Graphics/Gal/ShaderException.cs index 9bc87ff3..b0aff42b 100644 --- a/Ryujinx.Graphics/Gal/ShaderException.cs +++ b/Ryujinx.Graphics/Gal/ShaderException.cs @@ -6,6 +6,6 @@ namespace Ryujinx.Graphics.Gal { public ShaderException() : base() { } - public ShaderException(string Message) : base(Message) { } + public ShaderException(string message) : base(message) { } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/GpuMethodCall.cs b/Ryujinx.Graphics/GpuMethodCall.cs index 762d10f1..4a310b07 100644 --- a/Ryujinx.Graphics/GpuMethodCall.cs +++ b/Ryujinx.Graphics/GpuMethodCall.cs @@ -10,15 +10,15 @@ namespace Ryujinx.Graphics public bool IsLastCall => MethodCount <= 1; public GpuMethodCall( - int Method, - int Argument, - int SubChannel = 0, - int MethodCount = 0) + int method, + int argument, + int subChannel = 0, + int methodCount = 0) { - this.Method = Method; - this.Argument = Argument; - this.SubChannel = SubChannel; - this.MethodCount = MethodCount; + Method = method; + Argument = argument; + SubChannel = subChannel; + MethodCount = methodCount; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/GpuResourceManager.cs b/Ryujinx.Graphics/GpuResourceManager.cs index 4f2d92b0..740e6be8 100644 --- a/Ryujinx.Graphics/GpuResourceManager.cs +++ b/Ryujinx.Graphics/GpuResourceManager.cs @@ -1,8 +1,6 @@ -using Ryujinx.Common.Logging; using Ryujinx.Graphics.Gal; using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Texture; -using System; using System.Collections.Generic; namespace Ryujinx.Graphics @@ -18,124 +16,124 @@ namespace Ryujinx.Graphics ZetaBuffer } - private NvGpu Gpu; + private NvGpu _gpu; - private HashSet[] UploadedKeys; + private HashSet[] _uploadedKeys; - private Dictionary ImageTypes; - private Dictionary MirroredTextures; + private Dictionary _imageTypes; + private Dictionary _mirroredTextures; - public GpuResourceManager(NvGpu Gpu) + public GpuResourceManager(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; - UploadedKeys = new HashSet[(int)NvGpuBufferType.Count]; + _uploadedKeys = new HashSet[(int)NvGpuBufferType.Count]; - for (int Index = 0; Index < UploadedKeys.Length; Index++) + for (int index = 0; index < _uploadedKeys.Length; index++) { - UploadedKeys[Index] = new HashSet(); + _uploadedKeys[index] = new HashSet(); } - ImageTypes = new Dictionary(); - MirroredTextures = new Dictionary(); + _imageTypes = new Dictionary(); + _mirroredTextures = new Dictionary(); } - public void SendColorBuffer(NvGpuVmm Vmm, long Position, int Attachment, GalImage NewImage) + public void SendColorBuffer(NvGpuVmm vmm, long position, int attachment, GalImage newImage) { - long Size = (uint)ImageUtils.GetSize(NewImage); + long size = (uint)ImageUtils.GetSize(newImage); - ImageTypes[Position] = ImageType.ColorBuffer; + _imageTypes[position] = ImageType.ColorBuffer; - if (!TryReuse(Vmm, Position, NewImage)) + if (!TryReuse(vmm, position, newImage)) { - Gpu.Renderer.Texture.Create(Position, (int)Size, NewImage); + _gpu.Renderer.Texture.Create(position, (int)size, newImage); } - Gpu.Renderer.RenderTarget.BindColor(Position, Attachment); + _gpu.Renderer.RenderTarget.BindColor(position, attachment); } - public void SendZetaBuffer(NvGpuVmm Vmm, long Position, GalImage NewImage) + public void SendZetaBuffer(NvGpuVmm vmm, long position, GalImage newImage) { - long Size = (uint)ImageUtils.GetSize(NewImage); + long size = (uint)ImageUtils.GetSize(newImage); - ImageTypes[Position] = ImageType.ZetaBuffer; + _imageTypes[position] = ImageType.ZetaBuffer; - if (!TryReuse(Vmm, Position, NewImage)) + if (!TryReuse(vmm, position, newImage)) { - Gpu.Renderer.Texture.Create(Position, (int)Size, NewImage); + _gpu.Renderer.Texture.Create(position, (int)size, newImage); } - Gpu.Renderer.RenderTarget.BindZeta(Position); + _gpu.Renderer.RenderTarget.BindZeta(position); } - public void SendTexture(NvGpuVmm Vmm, long Position, GalImage NewImage) + public void SendTexture(NvGpuVmm vmm, long position, GalImage newImage) { - PrepareSendTexture(Vmm, Position, NewImage); + PrepareSendTexture(vmm, position, newImage); - ImageTypes[Position] = ImageType.Texture; + _imageTypes[position] = ImageType.Texture; } - public bool TryGetTextureLayer(long Position, out int LayerIndex) + public bool TryGetTextureLayer(long position, out int layerIndex) { - if (MirroredTextures.TryGetValue(Position, out LayerIndex)) + if (_mirroredTextures.TryGetValue(position, out layerIndex)) { - ImageType Type = ImageTypes[Position]; + ImageType type = _imageTypes[position]; // FIXME(thog): I'm actually unsure if we should deny all other image type, gpu testing needs to be done here. - if (Type != ImageType.Texture && Type != ImageType.TextureArrayLayer) + if (type != ImageType.Texture && type != ImageType.TextureArrayLayer) { - LayerIndex = -1; + layerIndex = -1; return false; } return true; } - LayerIndex = -1; + layerIndex = -1; return false; } - public void SetTextureArrayLayer(long Position, int LayerIndex) + public void SetTextureArrayLayer(long position, int layerIndex) { - ImageTypes[Position] = ImageType.TextureArrayLayer; - MirroredTextures[Position] = LayerIndex; + _imageTypes[position] = ImageType.TextureArrayLayer; + _mirroredTextures[position] = layerIndex; } - private void PrepareSendTexture(NvGpuVmm Vmm, long Position, GalImage NewImage) + private void PrepareSendTexture(NvGpuVmm vmm, long position, GalImage newImage) { - long Size = ImageUtils.GetSize(NewImage); + long size = ImageUtils.GetSize(newImage); - bool SkipCheck = false; + bool skipCheck = false; - if (ImageTypes.TryGetValue(Position, out ImageType OldType)) + if (_imageTypes.TryGetValue(position, out ImageType oldType)) { - if (OldType == ImageType.ColorBuffer || OldType == ImageType.ZetaBuffer) + if (oldType == ImageType.ColorBuffer || oldType == ImageType.ZetaBuffer) { //Avoid data destruction - MemoryRegionModified(Vmm, Position, Size, NvGpuBufferType.Texture); + MemoryRegionModified(vmm, position, size, NvGpuBufferType.Texture); - SkipCheck = true; + skipCheck = true; } } - if (SkipCheck || !MemoryRegionModified(Vmm, Position, Size, NvGpuBufferType.Texture)) + if (skipCheck || !MemoryRegionModified(vmm, position, size, NvGpuBufferType.Texture)) { - if (TryReuse(Vmm, Position, NewImage)) + if (TryReuse(vmm, position, newImage)) { return; } } - byte[] Data = ImageUtils.ReadTexture(Vmm, NewImage, Position); + byte[] data = ImageUtils.ReadTexture(vmm, newImage, position); - Gpu.Renderer.Texture.Create(Position, Data, NewImage); + _gpu.Renderer.Texture.Create(position, data, newImage); } - private bool TryReuse(NvGpuVmm Vmm, long Position, GalImage NewImage) + private bool TryReuse(NvGpuVmm vmm, long position, GalImage newImage) { - if (Gpu.Renderer.Texture.TryGetImage(Position, out GalImage CachedImage) && CachedImage.TextureTarget == NewImage.TextureTarget && CachedImage.SizeMatches(NewImage)) + if (_gpu.Renderer.Texture.TryGetImage(position, out GalImage cachedImage) && cachedImage.TextureTarget == newImage.TextureTarget && cachedImage.SizeMatches(newImage)) { - Gpu.Renderer.RenderTarget.Reinterpret(Position, NewImage); + _gpu.Renderer.RenderTarget.Reinterpret(position, newImage); return true; } @@ -143,29 +141,29 @@ namespace Ryujinx.Graphics return false; } - public bool MemoryRegionModified(NvGpuVmm Vmm, long Position, long Size, NvGpuBufferType Type) + public bool MemoryRegionModified(NvGpuVmm vmm, long position, long size, NvGpuBufferType type) { - HashSet Uploaded = UploadedKeys[(int)Type]; + HashSet uploaded = _uploadedKeys[(int)type]; - if (!Uploaded.Add(Position)) + if (!uploaded.Add(position)) { return false; } - return Vmm.IsRegionModified(Position, Size, Type); + return vmm.IsRegionModified(position, size, type); } public void ClearPbCache() { - for (int Index = 0; Index < UploadedKeys.Length; Index++) + for (int index = 0; index < _uploadedKeys.Length; index++) { - UploadedKeys[Index].Clear(); + _uploadedKeys[index].Clear(); } } - public void ClearPbCache(NvGpuBufferType Type) + public void ClearPbCache(NvGpuBufferType type) { - UploadedKeys[(int)Type].Clear(); + _uploadedKeys[(int)type].Clear(); } } } diff --git a/Ryujinx.Graphics/Graphics3d/INvGpuEngine.cs b/Ryujinx.Graphics/Graphics3d/INvGpuEngine.cs index c2474a17..aa0db682 100644 --- a/Ryujinx.Graphics/Graphics3d/INvGpuEngine.cs +++ b/Ryujinx.Graphics/Graphics3d/INvGpuEngine.cs @@ -6,6 +6,6 @@ namespace Ryujinx.Graphics.Graphics3d { int[] Registers { get; } - void CallMethod(NvGpuVmm Vmm, GpuMethodCall MethCall); + void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall); } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs b/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs index a124aca4..84576213 100644 --- a/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs +++ b/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs @@ -42,78 +42,78 @@ namespace Ryujinx.Graphics.Graphics3d BitwiseNotAnd = 12 } - private NvGpuFifo PFifo; - private INvGpuEngine Engine; + private NvGpuFifo _pFifo; + private INvGpuEngine _engine; public Queue Fifo { get; private set; } - private int[] Gprs; + private int[] _gprs; - private int MethAddr; - private int MethIncr; + private int _methAddr; + private int _methIncr; - private bool Carry; + private bool _carry; - private int OpCode; + private int _opCode; - private int PipeOp; + private int _pipeOp; - private int Pc; + private int _pc; - public MacroInterpreter(NvGpuFifo PFifo, INvGpuEngine Engine) + public MacroInterpreter(NvGpuFifo pFifo, INvGpuEngine engine) { - this.PFifo = PFifo; - this.Engine = Engine; + _pFifo = pFifo; + _engine = engine; Fifo = new Queue(); - Gprs = new int[8]; + _gprs = new int[8]; } - public void Execute(NvGpuVmm Vmm, int[] Mme, int Position, int Param) + public void Execute(NvGpuVmm vmm, int[] mme, int position, int param) { Reset(); - Gprs[1] = Param; + _gprs[1] = param; - Pc = Position; + _pc = position; - FetchOpCode(Mme); + FetchOpCode(mme); - while (Step(Vmm, Mme)); + while (Step(vmm, mme)); //Due to the delay slot, we still need to execute //one more instruction before we actually exit. - Step(Vmm, Mme); + Step(vmm, mme); } private void Reset() { - for (int Index = 0; Index < Gprs.Length; Index++) + for (int index = 0; index < _gprs.Length; index++) { - Gprs[Index] = 0; + _gprs[index] = 0; } - MethAddr = 0; - MethIncr = 0; + _methAddr = 0; + _methIncr = 0; - Carry = false; + _carry = false; } - private bool Step(NvGpuVmm Vmm, int[] Mme) + private bool Step(NvGpuVmm vmm, int[] mme) { - int BaseAddr = Pc - 1; + int baseAddr = _pc - 1; - FetchOpCode(Mme); + FetchOpCode(mme); - if ((OpCode & 7) < 7) + if ((_opCode & 7) < 7) { //Operation produces a value. - AssignmentOperation AsgOp = (AssignmentOperation)((OpCode >> 4) & 7); + AssignmentOperation asgOp = (AssignmentOperation)((_opCode >> 4) & 7); - int Result = GetAluResult(); + int result = GetAluResult(); - switch (AsgOp) + switch (asgOp) { //Fetch parameter and ignore result. case AssignmentOperation.IgnoreAndFetch: @@ -126,7 +126,7 @@ namespace Ryujinx.Graphics.Graphics3d //Move result. case AssignmentOperation.Move: { - SetDstGpr(Result); + SetDstGpr(result); break; } @@ -134,9 +134,9 @@ namespace Ryujinx.Graphics.Graphics3d //Move result and use as Method Address. case AssignmentOperation.MoveAndSetMaddr: { - SetDstGpr(Result); + SetDstGpr(result); - SetMethAddr(Result); + SetMethAddr(result); break; } @@ -146,7 +146,7 @@ namespace Ryujinx.Graphics.Graphics3d { SetDstGpr(FetchParam()); - Send(Vmm, Result); + Send(vmm, result); break; } @@ -154,9 +154,9 @@ namespace Ryujinx.Graphics.Graphics3d //Move and send result. case AssignmentOperation.MoveAndSend: { - SetDstGpr(Result); + SetDstGpr(result); - Send(Vmm, Result); + Send(vmm, result); break; } @@ -166,7 +166,7 @@ namespace Ryujinx.Graphics.Graphics3d { SetDstGpr(FetchParam()); - SetMethAddr(Result); + SetMethAddr(result); break; } @@ -174,11 +174,11 @@ namespace Ryujinx.Graphics.Graphics3d //Move result and use as Method Address, then fetch and send paramter. case AssignmentOperation.MoveAndSetMaddrThenFetchAndSend: { - SetDstGpr(Result); + SetDstGpr(result); - SetMethAddr(Result); + SetMethAddr(result); - Send(Vmm, FetchParam()); + Send(vmm, FetchParam()); break; } @@ -186,11 +186,11 @@ namespace Ryujinx.Graphics.Graphics3d //Move result and use as Method Address, then send bits 17:12 of result. case AssignmentOperation.MoveAndSetMaddrThenSendHigh: { - SetDstGpr(Result); + SetDstGpr(result); - SetMethAddr(Result); + SetMethAddr(result); - Send(Vmm, (Result >> 12) & 0x3f); + Send(vmm, (result >> 12) & 0x3f); break; } @@ -199,50 +199,50 @@ namespace Ryujinx.Graphics.Graphics3d else { //Branch. - bool OnNotZero = ((OpCode >> 4) & 1) != 0; + bool onNotZero = ((_opCode >> 4) & 1) != 0; - bool Taken = OnNotZero + bool taken = onNotZero ? GetGprA() != 0 : GetGprA() == 0; - if (Taken) + if (taken) { - Pc = BaseAddr + GetImm(); + _pc = baseAddr + GetImm(); - bool NoDelays = (OpCode & 0x20) != 0; + bool noDelays = (_opCode & 0x20) != 0; - if (NoDelays) + if (noDelays) { - FetchOpCode(Mme); + FetchOpCode(mme); } return true; } } - bool Exit = (OpCode & 0x80) != 0; + bool exit = (_opCode & 0x80) != 0; - return !Exit; + return !exit; } - private void FetchOpCode(int[] Mme) + private void FetchOpCode(int[] mme) { - OpCode = PipeOp; + _opCode = _pipeOp; - PipeOp = Mme[Pc++]; + _pipeOp = mme[_pc++]; } private int GetAluResult() { - AluOperation Op = (AluOperation)(OpCode & 7); + AluOperation op = (AluOperation)(_opCode & 7); - switch (Op) + switch (op) { case AluOperation.AluReg: { - AluRegOperation AluOp = (AluRegOperation)((OpCode >> 17) & 0x1f); + AluRegOperation aluOp = (AluRegOperation)((_opCode >> 17) & 0x1f); - return GetAluResult(AluOp, GetGprA(), GetGprB()); + return GetAluResult(aluOp, GetGprA(), GetGprB()); } case AluOperation.AddImmediate: @@ -254,40 +254,40 @@ namespace Ryujinx.Graphics.Graphics3d case AluOperation.BitfieldExtractLslImm: case AluOperation.BitfieldExtractLslReg: { - int BfSrcBit = (OpCode >> 17) & 0x1f; - int BfSize = (OpCode >> 22) & 0x1f; - int BfDstBit = (OpCode >> 27) & 0x1f; + int bfSrcBit = (_opCode >> 17) & 0x1f; + int bfSize = (_opCode >> 22) & 0x1f; + int bfDstBit = (_opCode >> 27) & 0x1f; - int BfMask = (1 << BfSize) - 1; + int bfMask = (1 << bfSize) - 1; - int Dst = GetGprA(); - int Src = GetGprB(); + int dst = GetGprA(); + int src = GetGprB(); - switch (Op) + switch (op) { case AluOperation.BitfieldReplace: { - Src = (int)((uint)Src >> BfSrcBit) & BfMask; + src = (int)((uint)src >> bfSrcBit) & bfMask; - Dst &= ~(BfMask << BfDstBit); + dst &= ~(bfMask << bfDstBit); - Dst |= Src << BfDstBit; + dst |= src << bfDstBit; - return Dst; + return dst; } case AluOperation.BitfieldExtractLslImm: { - Src = (int)((uint)Src >> Dst) & BfMask; + src = (int)((uint)src >> dst) & bfMask; - return Src << BfDstBit; + return src << bfDstBit; } case AluOperation.BitfieldExtractLslReg: { - Src = (int)((uint)Src >> BfSrcBit) & BfMask; + src = (int)((uint)src >> bfSrcBit) & bfMask; - return Src << Dst; + return src << dst; } } @@ -300,117 +300,117 @@ namespace Ryujinx.Graphics.Graphics3d } } - throw new ArgumentException(nameof(OpCode)); + throw new ArgumentException(nameof(_opCode)); } - private int GetAluResult(AluRegOperation AluOp, int A, int B) + private int GetAluResult(AluRegOperation aluOp, int a, int b) { - switch (AluOp) + switch (aluOp) { case AluRegOperation.Add: { - ulong Result = (ulong)A + (ulong)B; + ulong result = (ulong)a + (ulong)b; - Carry = Result > 0xffffffff; + _carry = result > 0xffffffff; - return (int)Result; + return (int)result; } case AluRegOperation.AddWithCarry: { - ulong Result = (ulong)A + (ulong)B + (Carry ? 1UL : 0UL); + ulong result = (ulong)a + (ulong)b + (_carry ? 1UL : 0UL); - Carry = Result > 0xffffffff; + _carry = result > 0xffffffff; - return (int)Result; + return (int)result; } case AluRegOperation.Subtract: { - ulong Result = (ulong)A - (ulong)B; + ulong result = (ulong)a - (ulong)b; - Carry = Result < 0x100000000; + _carry = result < 0x100000000; - return (int)Result; + return (int)result; } case AluRegOperation.SubtractWithBorrow: { - ulong Result = (ulong)A - (ulong)B - (Carry ? 0UL : 1UL); + ulong result = (ulong)a - (ulong)b - (_carry ? 0UL : 1UL); - Carry = Result < 0x100000000; + _carry = result < 0x100000000; - return (int)Result; + return (int)result; } - case AluRegOperation.BitwiseExclusiveOr: return A ^ B; - case AluRegOperation.BitwiseOr: return A | B; - case AluRegOperation.BitwiseAnd: return A & B; - case AluRegOperation.BitwiseAndNot: return A & ~B; - case AluRegOperation.BitwiseNotAnd: return ~(A & B); + case AluRegOperation.BitwiseExclusiveOr: return a ^ b; + case AluRegOperation.BitwiseOr: return a | b; + case AluRegOperation.BitwiseAnd: return a & b; + case AluRegOperation.BitwiseAndNot: return a & ~b; + case AluRegOperation.BitwiseNotAnd: return ~(a & b); } - throw new ArgumentOutOfRangeException(nameof(AluOp)); + throw new ArgumentOutOfRangeException(nameof(aluOp)); } private int GetImm() { //Note: The immediate is signed, the sign-extension is intended here. - return OpCode >> 14; + return _opCode >> 14; } - private void SetMethAddr(int Value) + private void SetMethAddr(int value) { - MethAddr = (Value >> 0) & 0xfff; - MethIncr = (Value >> 12) & 0x3f; + _methAddr = (value >> 0) & 0xfff; + _methIncr = (value >> 12) & 0x3f; } - private void SetDstGpr(int Value) + private void SetDstGpr(int value) { - Gprs[(OpCode >> 8) & 7] = Value; + _gprs[(_opCode >> 8) & 7] = value; } private int GetGprA() { - return GetGprValue((OpCode >> 11) & 7); + return GetGprValue((_opCode >> 11) & 7); } private int GetGprB() { - return GetGprValue((OpCode >> 14) & 7); + return GetGprValue((_opCode >> 14) & 7); } - private int GetGprValue(int Index) + private int GetGprValue(int index) { - return Index != 0 ? Gprs[Index] : 0; + return index != 0 ? _gprs[index] : 0; } private int FetchParam() { - int Value; + int value; - if (!Fifo.TryDequeue(out Value)) + if (!Fifo.TryDequeue(out value)) { Logger.PrintWarning(LogClass.Gpu, "Macro attempted to fetch an inexistent argument."); return 0; } - return Value; + return value; } - private int Read(int Reg) + private int Read(int reg) { - return Engine.Registers[Reg]; + return _engine.Registers[reg]; } - private void Send(NvGpuVmm Vmm, int Value) + private void Send(NvGpuVmm vmm, int value) { - GpuMethodCall MethCall = new GpuMethodCall(MethAddr, Value); + GpuMethodCall methCall = new GpuMethodCall(_methAddr, value); - Engine.CallMethod(Vmm, MethCall); + _engine.CallMethod(vmm, methCall); - MethAddr += MethIncr; + _methAddr += _methIncr; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngine2d.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngine2d.cs index 3295f6da..361b1706 100644 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngine2d.cs +++ b/Ryujinx.Graphics/Graphics3d/NvGpuEngine2d.cs @@ -1,4 +1,3 @@ -using Ryujinx.Common.Logging; using Ryujinx.Graphics.Gal; using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Texture; @@ -20,187 +19,187 @@ namespace Ryujinx.Graphics.Graphics3d public int[] Registers { get; private set; } - private NvGpu Gpu; + private NvGpu _gpu; - public NvGpuEngine2d(NvGpu Gpu) + public NvGpuEngine2d(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; Registers = new int[0x238]; } - public void CallMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - WriteRegister(MethCall); + WriteRegister(methCall); - if ((NvGpuEngine2dReg)MethCall.Method == NvGpuEngine2dReg.BlitSrcYInt) + if ((NvGpuEngine2dReg)methCall.Method == NvGpuEngine2dReg.BlitSrcYInt) { - TextureCopy(Vmm); + TextureCopy(vmm); } } - private void TextureCopy(NvGpuVmm Vmm) + private void TextureCopy(NvGpuVmm vmm) { - CopyOperation Operation = (CopyOperation)ReadRegister(NvGpuEngine2dReg.CopyOperation); + CopyOperation operation = (CopyOperation)ReadRegister(NvGpuEngine2dReg.CopyOperation); - int DstFormat = ReadRegister(NvGpuEngine2dReg.DstFormat); - bool DstLinear = ReadRegister(NvGpuEngine2dReg.DstLinear) != 0; - int DstWidth = ReadRegister(NvGpuEngine2dReg.DstWidth); - int DstHeight = ReadRegister(NvGpuEngine2dReg.DstHeight); - int DstDepth = ReadRegister(NvGpuEngine2dReg.DstDepth); - int DstLayer = ReadRegister(NvGpuEngine2dReg.DstLayer); - int DstPitch = ReadRegister(NvGpuEngine2dReg.DstPitch); - int DstBlkDim = ReadRegister(NvGpuEngine2dReg.DstBlockDimensions); + int dstFormat = ReadRegister(NvGpuEngine2dReg.DstFormat); + bool dstLinear = ReadRegister(NvGpuEngine2dReg.DstLinear) != 0; + int dstWidth = ReadRegister(NvGpuEngine2dReg.DstWidth); + int dstHeight = ReadRegister(NvGpuEngine2dReg.DstHeight); + int dstDepth = ReadRegister(NvGpuEngine2dReg.DstDepth); + int dstLayer = ReadRegister(NvGpuEngine2dReg.DstLayer); + int dstPitch = ReadRegister(NvGpuEngine2dReg.DstPitch); + int dstBlkDim = ReadRegister(NvGpuEngine2dReg.DstBlockDimensions); - int SrcFormat = ReadRegister(NvGpuEngine2dReg.SrcFormat); - bool SrcLinear = ReadRegister(NvGpuEngine2dReg.SrcLinear) != 0; - int SrcWidth = ReadRegister(NvGpuEngine2dReg.SrcWidth); - int SrcHeight = ReadRegister(NvGpuEngine2dReg.SrcHeight); - int SrcDepth = ReadRegister(NvGpuEngine2dReg.SrcDepth); - int SrcLayer = ReadRegister(NvGpuEngine2dReg.SrcLayer); - int SrcPitch = ReadRegister(NvGpuEngine2dReg.SrcPitch); - int SrcBlkDim = ReadRegister(NvGpuEngine2dReg.SrcBlockDimensions); + int srcFormat = ReadRegister(NvGpuEngine2dReg.SrcFormat); + bool srcLinear = ReadRegister(NvGpuEngine2dReg.SrcLinear) != 0; + int srcWidth = ReadRegister(NvGpuEngine2dReg.SrcWidth); + int srcHeight = ReadRegister(NvGpuEngine2dReg.SrcHeight); + int srcDepth = ReadRegister(NvGpuEngine2dReg.SrcDepth); + int srcLayer = ReadRegister(NvGpuEngine2dReg.SrcLayer); + int srcPitch = ReadRegister(NvGpuEngine2dReg.SrcPitch); + int srcBlkDim = ReadRegister(NvGpuEngine2dReg.SrcBlockDimensions); - int DstBlitX = ReadRegister(NvGpuEngine2dReg.BlitDstX); - int DstBlitY = ReadRegister(NvGpuEngine2dReg.BlitDstY); - int DstBlitW = ReadRegister(NvGpuEngine2dReg.BlitDstW); - int DstBlitH = ReadRegister(NvGpuEngine2dReg.BlitDstH); + int dstBlitX = ReadRegister(NvGpuEngine2dReg.BlitDstX); + int dstBlitY = ReadRegister(NvGpuEngine2dReg.BlitDstY); + int dstBlitW = ReadRegister(NvGpuEngine2dReg.BlitDstW); + int dstBlitH = ReadRegister(NvGpuEngine2dReg.BlitDstH); - long BlitDuDx = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitDuDxFract); - long BlitDvDy = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitDvDyFract); + long blitDuDx = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitDuDxFract); + long blitDvDy = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitDvDyFract); - long SrcBlitX = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitSrcXFract); - long SrcBlitY = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitSrcYFract); + long srcBlitX = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitSrcXFract); + long srcBlitY = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitSrcYFract); - GalImageFormat SrcImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)SrcFormat); - GalImageFormat DstImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)DstFormat); + GalImageFormat srcImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)srcFormat); + GalImageFormat dstImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)dstFormat); - GalMemoryLayout SrcLayout = GetLayout(SrcLinear); - GalMemoryLayout DstLayout = GetLayout(DstLinear); + GalMemoryLayout srcLayout = GetLayout(srcLinear); + GalMemoryLayout dstLayout = GetLayout(dstLinear); - int SrcBlockHeight = 1 << ((SrcBlkDim >> 4) & 0xf); - int DstBlockHeight = 1 << ((DstBlkDim >> 4) & 0xf); + int srcBlockHeight = 1 << ((srcBlkDim >> 4) & 0xf); + int dstBlockHeight = 1 << ((dstBlkDim >> 4) & 0xf); - long SrcAddress = MakeInt64From2xInt32(NvGpuEngine2dReg.SrcAddress); - long DstAddress = MakeInt64From2xInt32(NvGpuEngine2dReg.DstAddress); + long srcAddress = MakeInt64From2xInt32(NvGpuEngine2dReg.SrcAddress); + long dstAddress = MakeInt64From2xInt32(NvGpuEngine2dReg.DstAddress); - long SrcKey = Vmm.GetPhysicalAddress(SrcAddress); - long DstKey = Vmm.GetPhysicalAddress(DstAddress); + long srcKey = vmm.GetPhysicalAddress(srcAddress); + long dstKey = vmm.GetPhysicalAddress(dstAddress); - bool IsSrcLayered = false; - bool IsDstLayered = false; + bool isSrcLayered = false; + bool isDstLayered = false; - GalTextureTarget SrcTarget = GalTextureTarget.TwoD; + GalTextureTarget srcTarget = GalTextureTarget.TwoD; - if (SrcDepth != 0) + if (srcDepth != 0) { - SrcTarget = GalTextureTarget.TwoDArray; - SrcDepth++; - IsSrcLayered = true; + srcTarget = GalTextureTarget.TwoDArray; + srcDepth++; + isSrcLayered = true; } else { - SrcDepth = 1; + srcDepth = 1; } - GalTextureTarget DstTarget = GalTextureTarget.TwoD; + GalTextureTarget dstTarget = GalTextureTarget.TwoD; - if (DstDepth != 0) + if (dstDepth != 0) { - DstTarget = GalTextureTarget.TwoDArray; - DstDepth++; - IsDstLayered = true; + dstTarget = GalTextureTarget.TwoDArray; + dstDepth++; + isDstLayered = true; } else { - DstDepth = 1; + dstDepth = 1; } - GalImage SrcTexture = new GalImage( - SrcWidth, - SrcHeight, - 1, SrcDepth, 1, - SrcBlockHeight, 1, - SrcLayout, - SrcImgFormat, - SrcTarget); + GalImage srcTexture = new GalImage( + srcWidth, + srcHeight, + 1, srcDepth, 1, + srcBlockHeight, 1, + srcLayout, + srcImgFormat, + srcTarget); - GalImage DstTexture = new GalImage( - DstWidth, - DstHeight, - 1, DstDepth, 1, - DstBlockHeight, 1, - DstLayout, - DstImgFormat, - DstTarget); + GalImage dstTexture = new GalImage( + dstWidth, + dstHeight, + 1, dstDepth, 1, + dstBlockHeight, 1, + dstLayout, + dstImgFormat, + dstTarget); - SrcTexture.Pitch = SrcPitch; - DstTexture.Pitch = DstPitch; + srcTexture.Pitch = srcPitch; + dstTexture.Pitch = dstPitch; - long GetLayerOffset(GalImage Image, int Layer) + long GetLayerOffset(GalImage image, int layer) { - int TargetMipLevel = Image.MaxMipmapLevel <= 1 ? 1 : Image.MaxMipmapLevel - 1; - return ImageUtils.GetLayerOffset(Image, TargetMipLevel) * Layer; + int targetMipLevel = image.MaxMipmapLevel <= 1 ? 1 : image.MaxMipmapLevel - 1; + return ImageUtils.GetLayerOffset(image, targetMipLevel) * layer; } - int SrcLayerIndex = -1; + int srcLayerIndex = -1; - if (IsSrcLayered && Gpu.ResourceManager.TryGetTextureLayer(SrcKey, out SrcLayerIndex) && SrcLayerIndex != 0) + if (isSrcLayered && _gpu.ResourceManager.TryGetTextureLayer(srcKey, out srcLayerIndex) && srcLayerIndex != 0) { - SrcKey = SrcKey - GetLayerOffset(SrcTexture, SrcLayerIndex); + srcKey = srcKey - GetLayerOffset(srcTexture, srcLayerIndex); } - int DstLayerIndex = -1; + int dstLayerIndex = -1; - if (IsDstLayered && Gpu.ResourceManager.TryGetTextureLayer(DstKey, out DstLayerIndex) && DstLayerIndex != 0) + if (isDstLayered && _gpu.ResourceManager.TryGetTextureLayer(dstKey, out dstLayerIndex) && dstLayerIndex != 0) { - DstKey = DstKey - GetLayerOffset(DstTexture, DstLayerIndex); + dstKey = dstKey - GetLayerOffset(dstTexture, dstLayerIndex); } - Gpu.ResourceManager.SendTexture(Vmm, SrcKey, SrcTexture); - Gpu.ResourceManager.SendTexture(Vmm, DstKey, DstTexture); + _gpu.ResourceManager.SendTexture(vmm, srcKey, srcTexture); + _gpu.ResourceManager.SendTexture(vmm, dstKey, dstTexture); - if (IsSrcLayered && SrcLayerIndex == -1) + if (isSrcLayered && srcLayerIndex == -1) { - for (int Layer = 0; Layer < SrcTexture.LayerCount; Layer++) + for (int layer = 0; layer < srcTexture.LayerCount; layer++) { - Gpu.ResourceManager.SetTextureArrayLayer(SrcKey + GetLayerOffset(SrcTexture, Layer), Layer); + _gpu.ResourceManager.SetTextureArrayLayer(srcKey + GetLayerOffset(srcTexture, layer), layer); } - SrcLayerIndex = 0; + srcLayerIndex = 0; } - if (IsDstLayered && DstLayerIndex == -1) + if (isDstLayered && dstLayerIndex == -1) { - for (int Layer = 0; Layer < DstTexture.LayerCount; Layer++) + for (int layer = 0; layer < dstTexture.LayerCount; layer++) { - Gpu.ResourceManager.SetTextureArrayLayer(DstKey + GetLayerOffset(DstTexture, Layer), Layer); + _gpu.ResourceManager.SetTextureArrayLayer(dstKey + GetLayerOffset(dstTexture, layer), layer); } - DstLayerIndex = 0; + dstLayerIndex = 0; } - int SrcBlitX1 = (int)(SrcBlitX >> 32); - int SrcBlitY1 = (int)(SrcBlitY >> 32); + int srcBlitX1 = (int)(srcBlitX >> 32); + int srcBlitY1 = (int)(srcBlitY >> 32); - int SrcBlitX2 = (int)(SrcBlitX + DstBlitW * BlitDuDx >> 32); - int SrcBlitY2 = (int)(SrcBlitY + DstBlitH * BlitDvDy >> 32); + int srcBlitX2 = (int)(srcBlitX + dstBlitW * blitDuDx >> 32); + int srcBlitY2 = (int)(srcBlitY + dstBlitH * blitDvDy >> 32); - Gpu.Renderer.RenderTarget.Copy( - SrcTexture, - DstTexture, - SrcKey, - DstKey, - SrcLayerIndex, - DstLayerIndex, - SrcBlitX1, - SrcBlitY1, - SrcBlitX2, - SrcBlitY2, - DstBlitX, - DstBlitY, - DstBlitX + DstBlitW, - DstBlitY + DstBlitH); + _gpu.Renderer.RenderTarget.Copy( + srcTexture, + dstTexture, + srcKey, + dstKey, + srcLayerIndex, + dstLayerIndex, + srcBlitX1, + srcBlitY1, + srcBlitX2, + srcBlitY2, + dstBlitX, + dstBlitY, + dstBlitX + dstBlitW, + dstBlitY + dstBlitH); //Do a guest side copy aswell. This is necessary when //the texture is modified by the guest, however it doesn't @@ -209,51 +208,51 @@ namespace Ryujinx.Graphics.Graphics3d // FIXME: SUPPORT MULTILAYER CORRECTLY HERE (this will cause weird stuffs on the first layer) ImageUtils.CopyTexture( - Vmm, - SrcTexture, - DstTexture, - SrcAddress, - DstAddress, - SrcBlitX1, - SrcBlitY1, - DstBlitX, - DstBlitY, - DstBlitW, - DstBlitH); + vmm, + srcTexture, + dstTexture, + srcAddress, + dstAddress, + srcBlitX1, + srcBlitY1, + dstBlitX, + dstBlitY, + dstBlitW, + dstBlitH); - Vmm.IsRegionModified(DstKey, ImageUtils.GetSize(DstTexture), NvGpuBufferType.Texture); + vmm.IsRegionModified(dstKey, ImageUtils.GetSize(dstTexture), NvGpuBufferType.Texture); } - private static GalMemoryLayout GetLayout(bool Linear) + private static GalMemoryLayout GetLayout(bool linear) { - return Linear + return linear ? GalMemoryLayout.Pitch : GalMemoryLayout.BlockLinear; } - private long MakeInt64From2xInt32(NvGpuEngine2dReg Reg) + private long MakeInt64From2xInt32(NvGpuEngine2dReg reg) { return - (long)Registers[(int)Reg + 0] << 32 | - (uint)Registers[(int)Reg + 1]; + (long)Registers[(int)reg + 0] << 32 | + (uint)Registers[(int)reg + 1]; } - private void WriteRegister(GpuMethodCall MethCall) + private void WriteRegister(GpuMethodCall methCall) { - Registers[MethCall.Method] = MethCall.Argument; + Registers[methCall.Method] = methCall.Argument; } - private long ReadRegisterFixed1_31_32(NvGpuEngine2dReg Reg) + private long ReadRegisterFixed1_31_32(NvGpuEngine2dReg reg) { - long Low = (uint)ReadRegister(Reg + 0); - long High = (uint)ReadRegister(Reg + 1); + long low = (uint)ReadRegister(reg + 0); + long high = (uint)ReadRegister(reg + 1); - return Low | (High << 32); + return low | (high << 32); } - private int ReadRegister(NvGpuEngine2dReg Reg) + private int ReadRegister(NvGpuEngine2dReg reg) { - return Registers[(int)Reg]; + return Registers[(int)reg]; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngine3d.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngine3d.cs index 370fe1fa..605cbda8 100644 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngine3d.cs +++ b/Ryujinx.Graphics/Graphics3d/NvGpuEngine3d.cs @@ -1,5 +1,4 @@ using Ryujinx.Common; -using Ryujinx.Common.Logging; using Ryujinx.Graphics.Gal; using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Texture; @@ -12,9 +11,9 @@ namespace Ryujinx.Graphics.Graphics3d { public int[] Registers { get; private set; } - private NvGpu Gpu; + private NvGpu _gpu; - private Dictionary Methods; + private Dictionary _methods; private struct ConstBuffer { @@ -23,33 +22,33 @@ namespace Ryujinx.Graphics.Graphics3d public int Size; } - private ConstBuffer[][] ConstBuffers; + private ConstBuffer[][] _constBuffers; // Viewport dimensions kept for scissor test limits - private int ViewportX0 = 0; - private int ViewportY0 = 0; - private int ViewportX1 = 0; - private int ViewportY1 = 0; - private int ViewportWidth = 0; - private int ViewportHeight = 0; + private int _viewportX0 = 0; + private int _viewportY0 = 0; + private int _viewportX1 = 0; + private int _viewportY1 = 0; + private int _viewportWidth = 0; + private int _viewportHeight = 0; - private int CurrentInstance = 0; + private int _currentInstance = 0; - public NvGpuEngine3d(NvGpu Gpu) + public NvGpuEngine3d(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; Registers = new int[0xe00]; - Methods = new Dictionary(); + _methods = new Dictionary(); - void AddMethod(int Meth, int Count, int Stride, NvGpuMethod Method) + void AddMethod(int meth, int count, int stride, NvGpuMethod method) { - while (Count-- > 0) + while (count-- > 0) { - Methods.Add(Meth, Method); + _methods.Add(meth, method); - Meth += Stride; + meth += stride; } } @@ -59,11 +58,11 @@ namespace Ryujinx.Graphics.Graphics3d AddMethod(0x8e4, 16, 1, CbData); AddMethod(0x904, 5, 8, CbBind); - ConstBuffers = new ConstBuffer[6][]; + _constBuffers = new ConstBuffer[6][]; - for (int Index = 0; Index < ConstBuffers.Length; Index++) + for (int index = 0; index < _constBuffers.Length; index++) { - ConstBuffers[Index] = new ConstBuffer[18]; + _constBuffers[index] = new ConstBuffer[18]; } //Ensure that all components are enabled by default. @@ -72,227 +71,227 @@ namespace Ryujinx.Graphics.Graphics3d WriteRegister(NvGpuEngine3dReg.FrameBufferSrgb, 1); - WriteRegister(NvGpuEngine3dReg.FrontFace, (int)GalFrontFace.CW); + WriteRegister(NvGpuEngine3dReg.FrontFace, (int)GalFrontFace.Cw); - for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++) + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) { - WriteRegister(NvGpuEngine3dReg.IBlendNEquationRgb + Index * 8, (int)GalBlendEquation.FuncAdd); - WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcRgb + Index * 8, (int)GalBlendFactor.One); - WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstRgb + Index * 8, (int)GalBlendFactor.Zero); - WriteRegister(NvGpuEngine3dReg.IBlendNEquationAlpha + Index * 8, (int)GalBlendEquation.FuncAdd); - WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcAlpha + Index * 8, (int)GalBlendFactor.One); - WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstAlpha + Index * 8, (int)GalBlendFactor.Zero); + WriteRegister(NvGpuEngine3dReg.IBlendNEquationRgb + index * 8, (int)GalBlendEquation.FuncAdd); + WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcRgb + index * 8, (int)GalBlendFactor.One); + WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstRgb + index * 8, (int)GalBlendFactor.Zero); + WriteRegister(NvGpuEngine3dReg.IBlendNEquationAlpha + index * 8, (int)GalBlendEquation.FuncAdd); + WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcAlpha + index * 8, (int)GalBlendFactor.One); + WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstAlpha + index * 8, (int)GalBlendFactor.Zero); } } - public void CallMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - if (Methods.TryGetValue(MethCall.Method, out NvGpuMethod Method)) + if (_methods.TryGetValue(methCall.Method, out NvGpuMethod method)) { - Method(Vmm, MethCall); + method(vmm, methCall); } else { - WriteRegister(MethCall); + WriteRegister(methCall); } } - private void VertexEndGl(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void VertexEndGl(NvGpuVmm vmm, GpuMethodCall methCall) { LockCaches(); - GalPipelineState State = new GalPipelineState(); + GalPipelineState state = new GalPipelineState(); // Framebuffer must be run configured because viewport dimensions may be used in other methods - SetFrameBuffer(State); + SetFrameBuffer(state); - for (int FbIndex = 0; FbIndex < 8; FbIndex++) + for (int fbIndex = 0; fbIndex < 8; fbIndex++) { - SetFrameBuffer(Vmm, FbIndex); + SetFrameBuffer(vmm, fbIndex); } - SetFrontFace(State); - SetCullFace(State); - SetDepth(State); - SetStencil(State); - SetScissor(State); - SetBlending(State); - SetColorMask(State); - SetPrimitiveRestart(State); + SetFrontFace(state); + SetCullFace(state); + SetDepth(state); + SetStencil(state); + SetScissor(state); + SetBlending(state); + SetColorMask(state); + SetPrimitiveRestart(state); - SetZeta(Vmm); + SetZeta(vmm); SetRenderTargets(); - long[] Keys = UploadShaders(Vmm); + long[] keys = UploadShaders(vmm); - Gpu.Renderer.Shader.BindProgram(); + _gpu.Renderer.Shader.BindProgram(); - UploadTextures(Vmm, State, Keys); - UploadConstBuffers(Vmm, State, Keys); - UploadVertexArrays(Vmm, State); + UploadTextures(vmm, state, keys); + UploadConstBuffers(vmm, state, keys); + UploadVertexArrays(vmm, state); - DispatchRender(Vmm, State); + DispatchRender(vmm, state); UnlockCaches(); } private void LockCaches() { - Gpu.Renderer.Buffer.LockCache(); - Gpu.Renderer.Rasterizer.LockCaches(); - Gpu.Renderer.Texture.LockCache(); + _gpu.Renderer.Buffer.LockCache(); + _gpu.Renderer.Rasterizer.LockCaches(); + _gpu.Renderer.Texture.LockCache(); } private void UnlockCaches() { - Gpu.Renderer.Buffer.UnlockCache(); - Gpu.Renderer.Rasterizer.UnlockCaches(); - Gpu.Renderer.Texture.UnlockCache(); + _gpu.Renderer.Buffer.UnlockCache(); + _gpu.Renderer.Rasterizer.UnlockCaches(); + _gpu.Renderer.Texture.UnlockCache(); } - private void ClearBuffers(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void ClearBuffers(NvGpuVmm vmm, GpuMethodCall methCall) { - int Attachment = (MethCall.Argument >> 6) & 0xf; + int attachment = (methCall.Argument >> 6) & 0xf; - GalClearBufferFlags Flags = (GalClearBufferFlags)(MethCall.Argument & 0x3f); + GalClearBufferFlags flags = (GalClearBufferFlags)(methCall.Argument & 0x3f); - float Red = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 0); - float Green = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 1); - float Blue = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 2); - float Alpha = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 3); + float red = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 0); + float green = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 1); + float blue = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 2); + float alpha = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 3); - float Depth = ReadRegisterFloat(NvGpuEngine3dReg.ClearDepth); + float depth = ReadRegisterFloat(NvGpuEngine3dReg.ClearDepth); - int Stencil = ReadRegister(NvGpuEngine3dReg.ClearStencil); + int stencil = ReadRegister(NvGpuEngine3dReg.ClearStencil); - SetFrameBuffer(Vmm, Attachment); + SetFrameBuffer(vmm, attachment); - SetZeta(Vmm); + SetZeta(vmm); SetRenderTargets(); - Gpu.Renderer.RenderTarget.Bind(); + _gpu.Renderer.RenderTarget.Bind(); - Gpu.Renderer.Rasterizer.ClearBuffers(Flags, Attachment, Red, Green, Blue, Alpha, Depth, Stencil); + _gpu.Renderer.Rasterizer.ClearBuffers(flags, attachment, red, green, blue, alpha, depth, stencil); - Gpu.Renderer.Pipeline.ResetDepthMask(); - Gpu.Renderer.Pipeline.ResetColorMask(Attachment); + _gpu.Renderer.Pipeline.ResetDepthMask(); + _gpu.Renderer.Pipeline.ResetColorMask(attachment); } - private void SetFrameBuffer(NvGpuVmm Vmm, int FbIndex) + private void SetFrameBuffer(NvGpuVmm vmm, int fbIndex) { - long VA = MakeInt64From2xInt32(NvGpuEngine3dReg.FrameBufferNAddress + FbIndex * 0x10); + long va = MakeInt64From2xInt32(NvGpuEngine3dReg.FrameBufferNAddress + fbIndex * 0x10); - int SurfFormat = ReadRegister(NvGpuEngine3dReg.FrameBufferNFormat + FbIndex * 0x10); + int surfFormat = ReadRegister(NvGpuEngine3dReg.FrameBufferNFormat + fbIndex * 0x10); - if (VA == 0 || SurfFormat == 0) + if (va == 0 || surfFormat == 0) { - Gpu.Renderer.RenderTarget.UnbindColor(FbIndex); + _gpu.Renderer.RenderTarget.UnbindColor(fbIndex); return; } - long Key = Vmm.GetPhysicalAddress(VA); + long key = vmm.GetPhysicalAddress(va); - int Width = ReadRegister(NvGpuEngine3dReg.FrameBufferNWidth + FbIndex * 0x10); - int Height = ReadRegister(NvGpuEngine3dReg.FrameBufferNHeight + FbIndex * 0x10); + int width = ReadRegister(NvGpuEngine3dReg.FrameBufferNWidth + fbIndex * 0x10); + int height = ReadRegister(NvGpuEngine3dReg.FrameBufferNHeight + fbIndex * 0x10); - int ArrayMode = ReadRegister(NvGpuEngine3dReg.FrameBufferNArrayMode + FbIndex * 0x10); - int LayerCount = ArrayMode & 0xFFFF; - int LayerStride = ReadRegister(NvGpuEngine3dReg.FrameBufferNLayerStride + FbIndex * 0x10); - int BaseLayer = ReadRegister(NvGpuEngine3dReg.FrameBufferNBaseLayer + FbIndex * 0x10); - int BlockDim = ReadRegister(NvGpuEngine3dReg.FrameBufferNBlockDim + FbIndex * 0x10); + int arrayMode = ReadRegister(NvGpuEngine3dReg.FrameBufferNArrayMode + fbIndex * 0x10); + int layerCount = arrayMode & 0xFFFF; + int layerStride = ReadRegister(NvGpuEngine3dReg.FrameBufferNLayerStride + fbIndex * 0x10); + int baseLayer = ReadRegister(NvGpuEngine3dReg.FrameBufferNBaseLayer + fbIndex * 0x10); + int blockDim = ReadRegister(NvGpuEngine3dReg.FrameBufferNBlockDim + fbIndex * 0x10); - int GobBlockHeight = 1 << ((BlockDim >> 4) & 7); + int gobBlockHeight = 1 << ((blockDim >> 4) & 7); - GalMemoryLayout Layout = (GalMemoryLayout)((BlockDim >> 12) & 1); + GalMemoryLayout layout = (GalMemoryLayout)((blockDim >> 12) & 1); - float TX = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateX + FbIndex * 8); - float TY = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateY + FbIndex * 8); + float tx = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateX + fbIndex * 8); + float ty = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateY + fbIndex * 8); - float SX = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleX + FbIndex * 8); - float SY = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleY + FbIndex * 8); + float sx = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleX + fbIndex * 8); + float sy = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleY + fbIndex * 8); - ViewportX0 = (int)MathF.Max(0, TX - MathF.Abs(SX)); - ViewportY0 = (int)MathF.Max(0, TY - MathF.Abs(SY)); + _viewportX0 = (int)MathF.Max(0, tx - MathF.Abs(sx)); + _viewportY0 = (int)MathF.Max(0, ty - MathF.Abs(sy)); - ViewportX1 = (int)(TX + MathF.Abs(SX)); - ViewportY1 = (int)(TY + MathF.Abs(SY)); + _viewportX1 = (int)(tx + MathF.Abs(sx)); + _viewportY1 = (int)(ty + MathF.Abs(sy)); - GalImageFormat Format = ImageUtils.ConvertSurface((GalSurfaceFormat)SurfFormat); + GalImageFormat format = ImageUtils.ConvertSurface((GalSurfaceFormat)surfFormat); - GalImage Image = new GalImage(Width, Height, 1, 1, 1, GobBlockHeight, 1, Layout, Format, GalTextureTarget.TwoD); + GalImage image = new GalImage(width, height, 1, 1, 1, gobBlockHeight, 1, layout, format, GalTextureTarget.TwoD); - Gpu.ResourceManager.SendColorBuffer(Vmm, Key, FbIndex, Image); + _gpu.ResourceManager.SendColorBuffer(vmm, key, fbIndex, image); - Gpu.Renderer.RenderTarget.SetViewport(FbIndex, ViewportX0, ViewportY0, ViewportX1 - ViewportX0, ViewportY1 - ViewportY0); + _gpu.Renderer.RenderTarget.SetViewport(fbIndex, _viewportX0, _viewportY0, _viewportX1 - _viewportX0, _viewportY1 - _viewportY0); } - private void SetFrameBuffer(GalPipelineState State) + private void SetFrameBuffer(GalPipelineState state) { - State.FramebufferSrgb = ReadRegisterBool(NvGpuEngine3dReg.FrameBufferSrgb); + state.FramebufferSrgb = ReadRegisterBool(NvGpuEngine3dReg.FrameBufferSrgb); - State.FlipX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX); - State.FlipY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY); + state.FlipX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX); + state.FlipY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY); - int ScreenYControl = ReadRegister(NvGpuEngine3dReg.ScreenYControl); + int screenYControl = ReadRegister(NvGpuEngine3dReg.ScreenYControl); - bool NegateY = (ScreenYControl & 1) != 0; + bool negateY = (screenYControl & 1) != 0; - if (NegateY) + if (negateY) { - State.FlipY = -State.FlipY; + state.FlipY = -state.FlipY; } } - private void SetZeta(NvGpuVmm Vmm) + private void SetZeta(NvGpuVmm vmm) { - long VA = MakeInt64From2xInt32(NvGpuEngine3dReg.ZetaAddress); + long va = MakeInt64From2xInt32(NvGpuEngine3dReg.ZetaAddress); - int ZetaFormat = ReadRegister(NvGpuEngine3dReg.ZetaFormat); + int zetaFormat = ReadRegister(NvGpuEngine3dReg.ZetaFormat); - int BlockDim = ReadRegister(NvGpuEngine3dReg.ZetaBlockDimensions); + int blockDim = ReadRegister(NvGpuEngine3dReg.ZetaBlockDimensions); - int GobBlockHeight = 1 << ((BlockDim >> 4) & 7); + int gobBlockHeight = 1 << ((blockDim >> 4) & 7); - GalMemoryLayout Layout = (GalMemoryLayout)((BlockDim >> 12) & 1); //? + GalMemoryLayout layout = (GalMemoryLayout)((blockDim >> 12) & 1); //? - bool ZetaEnable = ReadRegisterBool(NvGpuEngine3dReg.ZetaEnable); + bool zetaEnable = ReadRegisterBool(NvGpuEngine3dReg.ZetaEnable); - if (VA == 0 || ZetaFormat == 0 || !ZetaEnable) + if (va == 0 || zetaFormat == 0 || !zetaEnable) { - Gpu.Renderer.RenderTarget.UnbindZeta(); + _gpu.Renderer.RenderTarget.UnbindZeta(); return; } - long Key = Vmm.GetPhysicalAddress(VA); + long key = vmm.GetPhysicalAddress(va); - int Width = ReadRegister(NvGpuEngine3dReg.ZetaHoriz); - int Height = ReadRegister(NvGpuEngine3dReg.ZetaVert); + int width = ReadRegister(NvGpuEngine3dReg.ZetaHoriz); + int height = ReadRegister(NvGpuEngine3dReg.ZetaVert); - GalImageFormat Format = ImageUtils.ConvertZeta((GalZetaFormat)ZetaFormat); + GalImageFormat format = ImageUtils.ConvertZeta((GalZetaFormat)zetaFormat); // TODO: Support non 2D? - GalImage Image = new GalImage(Width, Height, 1, 1, 1, GobBlockHeight, 1, Layout, Format, GalTextureTarget.TwoD); + GalImage image = new GalImage(width, height, 1, 1, 1, gobBlockHeight, 1, layout, format, GalTextureTarget.TwoD); - Gpu.ResourceManager.SendZetaBuffer(Vmm, Key, Image); + _gpu.ResourceManager.SendZetaBuffer(vmm, key, image); } - private long[] UploadShaders(NvGpuVmm Vmm) + private long[] UploadShaders(NvGpuVmm vmm) { - long[] Keys = new long[5]; + long[] keys = new long[5]; - long BasePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress); + long basePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress); - int Index = 1; + int index = 1; - int VpAControl = ReadRegister(NvGpuEngine3dReg.ShaderNControl); + int vpAControl = ReadRegister(NvGpuEngine3dReg.ShaderNControl); - bool VpAEnable = (VpAControl & 1) != 0; + bool vpAEnable = (vpAControl & 1) != 0; - if (VpAEnable) + if (vpAEnable) { //Note: The maxwell supports 2 vertex programs, usually //only VP B is used, but in some cases VP A is also used. @@ -300,51 +299,51 @@ namespace Ryujinx.Graphics.Graphics3d //shader stage. //The graphics abstraction layer has a special overload for this //case, which should merge the two shaders into one vertex shader. - int VpAOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset); - int VpBOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + 0x10); + int vpAOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset); + int vpBOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + 0x10); - long VpAPos = BasePosition + (uint)VpAOffset; - long VpBPos = BasePosition + (uint)VpBOffset; + long vpAPos = basePosition + (uint)vpAOffset; + long vpBPos = basePosition + (uint)vpBOffset; - Keys[(int)GalShaderType.Vertex] = VpBPos; + keys[(int)GalShaderType.Vertex] = vpBPos; - Gpu.Renderer.Shader.Create(Vmm, VpAPos, VpBPos, GalShaderType.Vertex); - Gpu.Renderer.Shader.Bind(VpBPos); + _gpu.Renderer.Shader.Create(vmm, vpAPos, vpBPos, GalShaderType.Vertex); + _gpu.Renderer.Shader.Bind(vpBPos); - Index = 2; + index = 2; } - for (; Index < 6; Index++) + for (; index < 6; index++) { - GalShaderType Type = GetTypeFromProgram(Index); + GalShaderType type = GetTypeFromProgram(index); - int Control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + Index * 0x10); - int Offset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + Index * 0x10); + int control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + index * 0x10); + int offset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + index * 0x10); //Note: Vertex Program (B) is always enabled. - bool Enable = (Control & 1) != 0 || Index == 1; + bool enable = (control & 1) != 0 || index == 1; - if (!Enable) + if (!enable) { - Gpu.Renderer.Shader.Unbind(Type); + _gpu.Renderer.Shader.Unbind(type); continue; } - long Key = BasePosition + (uint)Offset; + long key = basePosition + (uint)offset; - Keys[(int)Type] = Key; + keys[(int)type] = key; - Gpu.Renderer.Shader.Create(Vmm, Key, Type); - Gpu.Renderer.Shader.Bind(Key); + _gpu.Renderer.Shader.Create(vmm, key, type); + _gpu.Renderer.Shader.Bind(key); } - return Keys; + return keys; } - private static GalShaderType GetTypeFromProgram(int Program) + private static GalShaderType GetTypeFromProgram(int program) { - switch (Program) + switch (program) { case 0: case 1: return GalShaderType.Vertex; @@ -354,104 +353,104 @@ namespace Ryujinx.Graphics.Graphics3d case 5: return GalShaderType.Fragment; } - throw new ArgumentOutOfRangeException(nameof(Program)); + throw new ArgumentOutOfRangeException(nameof(program)); } - private void SetFrontFace(GalPipelineState State) + private void SetFrontFace(GalPipelineState state) { - float SignX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX); - float SignY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY); + float signX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX); + float signY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY); - GalFrontFace FrontFace = (GalFrontFace)ReadRegister(NvGpuEngine3dReg.FrontFace); + GalFrontFace frontFace = (GalFrontFace)ReadRegister(NvGpuEngine3dReg.FrontFace); //Flipping breaks facing. Flipping front facing too fixes it - if (SignX != SignY) + if (signX != signY) { - switch (FrontFace) + switch (frontFace) { - case GalFrontFace.CW: FrontFace = GalFrontFace.CCW; break; - case GalFrontFace.CCW: FrontFace = GalFrontFace.CW; break; + case GalFrontFace.Cw: frontFace = GalFrontFace.Ccw; break; + case GalFrontFace.Ccw: frontFace = GalFrontFace.Cw; break; } } - State.FrontFace = FrontFace; + state.FrontFace = frontFace; } - private void SetCullFace(GalPipelineState State) + private void SetCullFace(GalPipelineState state) { - State.CullFaceEnabled = ReadRegisterBool(NvGpuEngine3dReg.CullFaceEnable); + state.CullFaceEnabled = ReadRegisterBool(NvGpuEngine3dReg.CullFaceEnable); - if (State.CullFaceEnabled) + if (state.CullFaceEnabled) { - State.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace); + state.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace); } } - private void SetDepth(GalPipelineState State) + private void SetDepth(GalPipelineState state) { - State.DepthTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthTestEnable); + state.DepthTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthTestEnable); - State.DepthWriteEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthWriteEnable); + state.DepthWriteEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthWriteEnable); - if (State.DepthTestEnabled) + if (state.DepthTestEnabled) { - State.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction); + state.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction); } - State.DepthRangeNear = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNNear); - State.DepthRangeFar = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNFar); + state.DepthRangeNear = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNNear); + state.DepthRangeFar = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNFar); } - private void SetStencil(GalPipelineState State) + private void SetStencil(GalPipelineState state) { - State.StencilTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.StencilEnable); + state.StencilTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.StencilEnable); - if (State.StencilTestEnabled) + if (state.StencilTestEnabled) { - State.StencilBackFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilBackFuncFunc); - State.StencilBackFuncRef = ReadRegister(NvGpuEngine3dReg.StencilBackFuncRef); - State.StencilBackFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackFuncMask); - State.StencilBackOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpFail); - State.StencilBackOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZFail); - State.StencilBackOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZPass); - State.StencilBackMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackMask); + state.StencilBackFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilBackFuncFunc); + state.StencilBackFuncRef = ReadRegister(NvGpuEngine3dReg.StencilBackFuncRef); + state.StencilBackFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackFuncMask); + state.StencilBackOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpFail); + state.StencilBackOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZFail); + state.StencilBackOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZPass); + state.StencilBackMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackMask); - State.StencilFrontFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncFunc); - State.StencilFrontFuncRef = ReadRegister(NvGpuEngine3dReg.StencilFrontFuncRef); - State.StencilFrontFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncMask); - State.StencilFrontOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpFail); - State.StencilFrontOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZFail); - State.StencilFrontOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZPass); - State.StencilFrontMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontMask); + state.StencilFrontFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncFunc); + state.StencilFrontFuncRef = ReadRegister(NvGpuEngine3dReg.StencilFrontFuncRef); + state.StencilFrontFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncMask); + state.StencilFrontOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpFail); + state.StencilFrontOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZFail); + state.StencilFrontOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZPass); + state.StencilFrontMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontMask); } } - private void SetScissor(GalPipelineState State) + private void SetScissor(GalPipelineState state) { int count = 0; - for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++) + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) { - State.ScissorTestEnabled[Index] = ReadRegisterBool(NvGpuEngine3dReg.ScissorEnable + Index * 4); + state.ScissorTestEnabled[index] = ReadRegisterBool(NvGpuEngine3dReg.ScissorEnable + index * 4); - if (State.ScissorTestEnabled[Index]) + if (state.ScissorTestEnabled[index]) { - uint ScissorHorizontal = (uint)ReadRegister(NvGpuEngine3dReg.ScissorHorizontal + Index * 4); - uint ScissorVertical = (uint)ReadRegister(NvGpuEngine3dReg.ScissorVertical + Index * 4); + uint scissorHorizontal = (uint)ReadRegister(NvGpuEngine3dReg.ScissorHorizontal + index * 4); + uint scissorVertical = (uint)ReadRegister(NvGpuEngine3dReg.ScissorVertical + index * 4); - int left = (int)(ScissorHorizontal & 0xFFFF); // Left, lower 16 bits - int right = (int)(ScissorHorizontal >> 16); // Right, upper 16 bits + int left = (int)(scissorHorizontal & 0xFFFF); // Left, lower 16 bits + int right = (int)(scissorHorizontal >> 16); // Right, upper 16 bits - int bottom = (int)(ScissorVertical & 0xFFFF); // Bottom, lower 16 bits - int top = (int)(ScissorVertical >> 16); // Top, upper 16 bits + int bottom = (int)(scissorVertical & 0xFFFF); // Bottom, lower 16 bits + int top = (int)(scissorVertical >> 16); // Top, upper 16 bits int width = Math.Abs(right - left); int height = Math.Abs(top - bottom); - // If the scissor test covers the whole possible viewport, i.e. uninititalized, disable scissor test + // If the scissor test covers the whole possible viewport, i.e. uninitialized, disable scissor test if ((width > NvGpu.MaxViewportSize && height > NvGpu.MaxViewportSize) || width <= 0 || height <= 0) { - State.ScissorTestEnabled[Index] = false; + state.ScissorTestEnabled[index] = false; continue; } @@ -460,10 +459,10 @@ namespace Ryujinx.Graphics.Graphics3d count++; // Flip X - if (State.FlipX == -1) + if (state.FlipX == -1) { - left = ViewportX1 - (left - ViewportX0); - right = ViewportX1 - (right - ViewportX0); + left = _viewportX1 - (left - _viewportX0); + right = _viewportX1 - (right - _viewportX0); } // Ensure X is in the right order @@ -475,10 +474,10 @@ namespace Ryujinx.Graphics.Graphics3d } // Flip Y - if (State.FlipY == -1) + if (state.FlipY == -1) { - bottom = ViewportY1 - (bottom - ViewportY0); - top = ViewportY1 - (top - ViewportY0); + bottom = _viewportY1 - (bottom - _viewportY0); + top = _viewportY1 - (top - _viewportY0); } // Ensure Y is in the right order @@ -490,102 +489,102 @@ namespace Ryujinx.Graphics.Graphics3d } // Handle out of active viewport dimensions - left = Math.Clamp(left, ViewportX0, ViewportX1); - right = Math.Clamp(right, ViewportX0, ViewportX1); - top = Math.Clamp(top, ViewportY0, ViewportY1); - bottom = Math.Clamp(bottom, ViewportY0, ViewportY1); + left = Math.Clamp(left, _viewportX0, _viewportX1); + right = Math.Clamp(right, _viewportX0, _viewportX1); + top = Math.Clamp(top, _viewportY0, _viewportY1); + bottom = Math.Clamp(bottom, _viewportY0, _viewportY1); // Save values to state - State.ScissorTestX[Index] = left; - State.ScissorTestY[Index] = bottom; + state.ScissorTestX[index] = left; + state.ScissorTestY[index] = bottom; - State.ScissorTestWidth[Index] = right - left; - State.ScissorTestHeight[Index] = top - bottom; + state.ScissorTestWidth[index] = right - left; + state.ScissorTestHeight[index] = top - bottom; } } - State.ScissorTestCount = count; + state.ScissorTestCount = count; } - private void SetBlending(GalPipelineState State) + private void SetBlending(GalPipelineState state) { - bool BlendIndependent = ReadRegisterBool(NvGpuEngine3dReg.BlendIndependent); + bool blendIndependent = ReadRegisterBool(NvGpuEngine3dReg.BlendIndependent); - State.BlendIndependent = BlendIndependent; + state.BlendIndependent = blendIndependent; - for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++) + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) { - if (BlendIndependent) + if (blendIndependent) { - State.Blends[Index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable + Index); + state.Blends[index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable + index); - if (State.Blends[Index].Enabled) + if (state.Blends[index].Enabled) { - State.Blends[Index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.IBlendNSeparateAlpha + Index * 8); + state.Blends[index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.IBlendNSeparateAlpha + index * 8); - State.Blends[Index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationRgb + Index * 8); - State.Blends[Index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcRgb + Index * 8); - State.Blends[Index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstRgb + Index * 8); - State.Blends[Index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationAlpha + Index * 8); - State.Blends[Index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcAlpha + Index * 8); - State.Blends[Index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstAlpha + Index * 8); + state.Blends[index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationRgb + index * 8); + state.Blends[index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcRgb + index * 8); + state.Blends[index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstRgb + index * 8); + state.Blends[index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationAlpha + index * 8); + state.Blends[index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcAlpha + index * 8); + state.Blends[index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstAlpha + index * 8); } } else { //It seems that even when independent blend is disabled, the first IBlend enable //register is still set to indicate whenever blend is enabled or not (?). - State.Blends[Index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable); + state.Blends[index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable); - if (State.Blends[Index].Enabled) + if (state.Blends[index].Enabled) { - State.Blends[Index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.BlendSeparateAlpha); + state.Blends[index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.BlendSeparateAlpha); - State.Blends[Index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationRgb); - State.Blends[Index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcRgb); - State.Blends[Index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstRgb); - State.Blends[Index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationAlpha); - State.Blends[Index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcAlpha); - State.Blends[Index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstAlpha); + state.Blends[index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationRgb); + state.Blends[index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcRgb); + state.Blends[index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstRgb); + state.Blends[index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationAlpha); + state.Blends[index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcAlpha); + state.Blends[index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstAlpha); } } } } - private GalBlendEquation ReadBlendEquation(NvGpuEngine3dReg Register) + private GalBlendEquation ReadBlendEquation(NvGpuEngine3dReg register) { - return (GalBlendEquation)ReadRegister(Register); + return (GalBlendEquation)ReadRegister(register); } - private GalBlendFactor ReadBlendFactor(NvGpuEngine3dReg Register) + private GalBlendFactor ReadBlendFactor(NvGpuEngine3dReg register) { - return (GalBlendFactor)ReadRegister(Register); + return (GalBlendFactor)ReadRegister(register); } - private void SetColorMask(GalPipelineState State) + private void SetColorMask(GalPipelineState state) { - bool ColorMaskCommon = ReadRegisterBool(NvGpuEngine3dReg.ColorMaskCommon); + bool colorMaskCommon = ReadRegisterBool(NvGpuEngine3dReg.ColorMaskCommon); - State.ColorMaskCommon = ColorMaskCommon; + state.ColorMaskCommon = colorMaskCommon; - for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++) + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) { - int ColorMask = ReadRegister(NvGpuEngine3dReg.ColorMaskN + (ColorMaskCommon ? 0 : Index)); + int colorMask = ReadRegister(NvGpuEngine3dReg.ColorMaskN + (colorMaskCommon ? 0 : index)); - State.ColorMasks[Index].Red = ((ColorMask >> 0) & 0xf) != 0; - State.ColorMasks[Index].Green = ((ColorMask >> 4) & 0xf) != 0; - State.ColorMasks[Index].Blue = ((ColorMask >> 8) & 0xf) != 0; - State.ColorMasks[Index].Alpha = ((ColorMask >> 12) & 0xf) != 0; + state.ColorMasks[index].Red = ((colorMask >> 0) & 0xf) != 0; + state.ColorMasks[index].Green = ((colorMask >> 4) & 0xf) != 0; + state.ColorMasks[index].Blue = ((colorMask >> 8) & 0xf) != 0; + state.ColorMasks[index].Alpha = ((colorMask >> 12) & 0xf) != 0; } } - private void SetPrimitiveRestart(GalPipelineState State) + private void SetPrimitiveRestart(GalPipelineState state) { - State.PrimitiveRestartEnabled = ReadRegisterBool(NvGpuEngine3dReg.PrimRestartEnable); + state.PrimitiveRestartEnabled = ReadRegisterBool(NvGpuEngine3dReg.PrimRestartEnable); - if (State.PrimitiveRestartEnabled) + if (state.PrimitiveRestartEnabled) { - State.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex); + state.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex); } } @@ -594,461 +593,461 @@ namespace Ryujinx.Graphics.Graphics3d //Commercial games do not seem to //bool SeparateFragData = ReadRegisterBool(NvGpuEngine3dReg.RTSeparateFragData); - uint Control = (uint)(ReadRegister(NvGpuEngine3dReg.RTControl)); + uint control = (uint)(ReadRegister(NvGpuEngine3dReg.RtControl)); - uint Count = Control & 0xf; + uint count = control & 0xf; - if (Count > 0) + if (count > 0) { - int[] Map = new int[Count]; + int[] map = new int[count]; - for (int Index = 0; Index < Count; Index++) + for (int index = 0; index < count; index++) { - int Shift = 4 + Index * 3; + int shift = 4 + index * 3; - Map[Index] = (int)((Control >> Shift) & 7); + map[index] = (int)((control >> shift) & 7); } - Gpu.Renderer.RenderTarget.SetMap(Map); + _gpu.Renderer.RenderTarget.SetMap(map); } else { - Gpu.Renderer.RenderTarget.SetMap(null); + _gpu.Renderer.RenderTarget.SetMap(null); } } - private void UploadTextures(NvGpuVmm Vmm, GalPipelineState State, long[] Keys) + private void UploadTextures(NvGpuVmm vmm, GalPipelineState state, long[] keys) { - long BaseShPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress); + long baseShPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress); - int TextureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex); + int textureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex); - List<(long, GalImage, GalTextureSampler)> UnboundTextures = new List<(long, GalImage, GalTextureSampler)>(); + List<(long, GalImage, GalTextureSampler)> unboundTextures = new List<(long, GalImage, GalTextureSampler)>(); - for (int Index = 0; Index < Keys.Length; Index++) + for (int index = 0; index < keys.Length; index++) { - foreach (ShaderDeclInfo DeclInfo in Gpu.Renderer.Shader.GetTextureUsage(Keys[Index])) + foreach (ShaderDeclInfo declInfo in _gpu.Renderer.Shader.GetTextureUsage(keys[index])) { - long Position; + long position; - if (DeclInfo.IsCb) + if (declInfo.IsCb) { - Position = ConstBuffers[Index][DeclInfo.Cbuf].Position; + position = _constBuffers[index][declInfo.Cbuf].Position; } else { - Position = ConstBuffers[Index][TextureCbIndex].Position; + position = _constBuffers[index][textureCbIndex].Position; } - int TextureHandle = Vmm.ReadInt32(Position + DeclInfo.Index * 4); + int textureHandle = vmm.ReadInt32(position + declInfo.Index * 4); - UnboundTextures.Add(UploadTexture(Vmm, TextureHandle)); + unboundTextures.Add(UploadTexture(vmm, textureHandle)); } } - for (int Index = 0; Index < UnboundTextures.Count; Index++) + for (int index = 0; index < unboundTextures.Count; index++) { - (long Key, GalImage Image, GalTextureSampler Sampler) = UnboundTextures[Index]; + (long key, GalImage image, GalTextureSampler sampler) = unboundTextures[index]; - if (Key == 0) + if (key == 0) { continue; } - Gpu.Renderer.Texture.Bind(Key, Index, Image); - Gpu.Renderer.Texture.SetSampler(Image, Sampler); + _gpu.Renderer.Texture.Bind(key, index, image); + _gpu.Renderer.Texture.SetSampler(image, sampler); } } - private (long, GalImage, GalTextureSampler) UploadTexture(NvGpuVmm Vmm, int TextureHandle) + private (long, GalImage, GalTextureSampler) UploadTexture(NvGpuVmm vmm, int textureHandle) { - if (TextureHandle == 0) + if (textureHandle == 0) { //FIXME: Some games like puyo puyo will use handles with the value 0. //This is a bug, most likely caused by sync issues. return (0, default(GalImage), default(GalTextureSampler)); } - bool LinkedTsc = ReadRegisterBool(NvGpuEngine3dReg.LinkedTsc); + bool linkedTsc = ReadRegisterBool(NvGpuEngine3dReg.LinkedTsc); - int TicIndex = (TextureHandle >> 0) & 0xfffff; + int ticIndex = (textureHandle >> 0) & 0xfffff; - int TscIndex = LinkedTsc ? TicIndex : (TextureHandle >> 20) & 0xfff; + int tscIndex = linkedTsc ? ticIndex : (textureHandle >> 20) & 0xfff; - long TicPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexHeaderPoolOffset); - long TscPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexSamplerPoolOffset); + long ticPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexHeaderPoolOffset); + long tscPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexSamplerPoolOffset); - TicPosition += TicIndex * 0x20; - TscPosition += TscIndex * 0x20; + ticPosition += ticIndex * 0x20; + tscPosition += tscIndex * 0x20; - GalImage Image = TextureFactory.MakeTexture(Vmm, TicPosition); + GalImage image = TextureFactory.MakeTexture(vmm, ticPosition); - GalTextureSampler Sampler = TextureFactory.MakeSampler(Gpu, Vmm, TscPosition); + GalTextureSampler sampler = TextureFactory.MakeSampler(_gpu, vmm, tscPosition); - long Key = Vmm.ReadInt64(TicPosition + 4) & 0xffffffffffff; + long key = vmm.ReadInt64(ticPosition + 4) & 0xffffffffffff; - if (Image.Layout == GalMemoryLayout.BlockLinear) + if (image.Layout == GalMemoryLayout.BlockLinear) { - Key &= ~0x1ffL; + key &= ~0x1ffL; } - else if (Image.Layout == GalMemoryLayout.Pitch) + else if (image.Layout == GalMemoryLayout.Pitch) { - Key &= ~0x1fL; + key &= ~0x1fL; } - Key = Vmm.GetPhysicalAddress(Key); + key = vmm.GetPhysicalAddress(key); - if (Key == -1) + if (key == -1) { //FIXME: Shouldn't ignore invalid addresses. return (0, default(GalImage), default(GalTextureSampler)); } - Gpu.ResourceManager.SendTexture(Vmm, Key, Image); + _gpu.ResourceManager.SendTexture(vmm, key, image); - return (Key, Image, Sampler); + return (key, image, sampler); } - private void UploadConstBuffers(NvGpuVmm Vmm, GalPipelineState State, long[] Keys) + private void UploadConstBuffers(NvGpuVmm vmm, GalPipelineState state, long[] keys) { - for (int Stage = 0; Stage < Keys.Length; Stage++) + for (int stage = 0; stage < keys.Length; stage++) { - foreach (ShaderDeclInfo DeclInfo in Gpu.Renderer.Shader.GetConstBufferUsage(Keys[Stage])) + foreach (ShaderDeclInfo declInfo in _gpu.Renderer.Shader.GetConstBufferUsage(keys[stage])) { - ConstBuffer Cb = ConstBuffers[Stage][DeclInfo.Cbuf]; + ConstBuffer cb = _constBuffers[stage][declInfo.Cbuf]; - if (!Cb.Enabled) + if (!cb.Enabled) { continue; } - long Key = Vmm.GetPhysicalAddress(Cb.Position); + long key = vmm.GetPhysicalAddress(cb.Position); - if (Gpu.ResourceManager.MemoryRegionModified(Vmm, Key, Cb.Size, NvGpuBufferType.ConstBuffer)) + if (_gpu.ResourceManager.MemoryRegionModified(vmm, key, cb.Size, NvGpuBufferType.ConstBuffer)) { - if (Vmm.TryGetHostAddress(Cb.Position, Cb.Size, out IntPtr CbPtr)) + if (vmm.TryGetHostAddress(cb.Position, cb.Size, out IntPtr cbPtr)) { - Gpu.Renderer.Buffer.SetData(Key, Cb.Size, CbPtr); + _gpu.Renderer.Buffer.SetData(key, cb.Size, cbPtr); } else { - Gpu.Renderer.Buffer.SetData(Key, Vmm.ReadBytes(Cb.Position, Cb.Size)); + _gpu.Renderer.Buffer.SetData(key, vmm.ReadBytes(cb.Position, cb.Size)); } } - State.ConstBufferKeys[Stage][DeclInfo.Cbuf] = Key; + state.ConstBufferKeys[stage][declInfo.Cbuf] = key; } } } - private void UploadVertexArrays(NvGpuVmm Vmm, GalPipelineState State) + private void UploadVertexArrays(NvGpuVmm vmm, GalPipelineState state) { - long IbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress); + long ibPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress); - long IboKey = Vmm.GetPhysicalAddress(IbPosition); + long iboKey = vmm.GetPhysicalAddress(ibPosition); - int IndexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat); - int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount); - int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl); + int indexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat); + int indexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount); + int primCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl); - GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff); + GalPrimitiveType primType = (GalPrimitiveType)(primCtrl & 0xffff); - GalIndexFormat IndexFormat = (GalIndexFormat)IndexEntryFmt; + GalIndexFormat indexFormat = (GalIndexFormat)indexEntryFmt; - int IndexEntrySize = 1 << IndexEntryFmt; + int indexEntrySize = 1 << indexEntryFmt; - if (IndexEntrySize > 4) + if (indexEntrySize > 4) { - throw new InvalidOperationException("Invalid index entry size \"" + IndexEntrySize + "\"!"); + throw new InvalidOperationException("Invalid index entry size \"" + indexEntrySize + "\"!"); } - if (IndexCount != 0) + if (indexCount != 0) { - int IbSize = IndexCount * IndexEntrySize; + int ibSize = indexCount * indexEntrySize; - bool IboCached = Gpu.Renderer.Rasterizer.IsIboCached(IboKey, (uint)IbSize); + bool iboCached = _gpu.Renderer.Rasterizer.IsIboCached(iboKey, (uint)ibSize); - bool UsesLegacyQuads = - PrimType == GalPrimitiveType.Quads || - PrimType == GalPrimitiveType.QuadStrip; + bool usesLegacyQuads = + primType == GalPrimitiveType.Quads || + primType == GalPrimitiveType.QuadStrip; - if (!IboCached || Gpu.ResourceManager.MemoryRegionModified(Vmm, IboKey, (uint)IbSize, NvGpuBufferType.Index)) + if (!iboCached || _gpu.ResourceManager.MemoryRegionModified(vmm, iboKey, (uint)ibSize, NvGpuBufferType.Index)) { - if (!UsesLegacyQuads) + if (!usesLegacyQuads) { - if (Vmm.TryGetHostAddress(IbPosition, IbSize, out IntPtr IbPtr)) + if (vmm.TryGetHostAddress(ibPosition, ibSize, out IntPtr ibPtr)) { - Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, IbPtr); + _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, ibPtr); } else { - Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, Vmm.ReadBytes(IbPosition, IbSize)); + _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, vmm.ReadBytes(ibPosition, ibSize)); } } else { - byte[] Buffer = Vmm.ReadBytes(IbPosition, IbSize); + byte[] buffer = vmm.ReadBytes(ibPosition, ibSize); - if (PrimType == GalPrimitiveType.Quads) + if (primType == GalPrimitiveType.Quads) { - Buffer = QuadHelper.ConvertQuadsToTris(Buffer, IndexEntrySize, IndexCount); + buffer = QuadHelper.ConvertQuadsToTris(buffer, indexEntrySize, indexCount); } else /* if (PrimType == GalPrimitiveType.QuadStrip) */ { - Buffer = QuadHelper.ConvertQuadStripToTris(Buffer, IndexEntrySize, IndexCount); + buffer = QuadHelper.ConvertQuadStripToTris(buffer, indexEntrySize, indexCount); } - Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, Buffer); + _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, buffer); } } - if (!UsesLegacyQuads) + if (!usesLegacyQuads) { - Gpu.Renderer.Rasterizer.SetIndexArray(IbSize, IndexFormat); + _gpu.Renderer.Rasterizer.SetIndexArray(ibSize, indexFormat); } else { - if (PrimType == GalPrimitiveType.Quads) + if (primType == GalPrimitiveType.Quads) { - Gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadsToTris(IbSize), IndexFormat); + _gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadsToTris(ibSize), indexFormat); } else /* if (PrimType == GalPrimitiveType.QuadStrip) */ { - Gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadStripToTris(IbSize), IndexFormat); + _gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadStripToTris(ibSize), indexFormat); } } } - List[] Attribs = new List[32]; + List[] attribs = new List[32]; - for (int Attr = 0; Attr < 16; Attr++) + for (int attr = 0; attr < 16; attr++) { - int Packed = ReadRegister(NvGpuEngine3dReg.VertexAttribNFormat + Attr); + int packed = ReadRegister(NvGpuEngine3dReg.VertexAttribNFormat + attr); - int ArrayIndex = Packed & 0x1f; + int arrayIndex = packed & 0x1f; - if (Attribs[ArrayIndex] == null) + if (attribs[arrayIndex] == null) { - Attribs[ArrayIndex] = new List(); + attribs[arrayIndex] = new List(); } - long VbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + ArrayIndex * 4); + long vbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + arrayIndex * 4); - if (VbPosition == 0) + if (vbPosition == 0) { continue; } - bool IsConst = ((Packed >> 6) & 1) != 0; + bool isConst = ((packed >> 6) & 1) != 0; - int Offset = (Packed >> 7) & 0x3fff; + int offset = (packed >> 7) & 0x3fff; - GalVertexAttribSize Size = (GalVertexAttribSize)((Packed >> 21) & 0x3f); - GalVertexAttribType Type = (GalVertexAttribType)((Packed >> 27) & 0x7); + GalVertexAttribSize size = (GalVertexAttribSize)((packed >> 21) & 0x3f); + GalVertexAttribType type = (GalVertexAttribType)((packed >> 27) & 0x7); - bool IsRgba = ((Packed >> 31) & 1) != 0; + bool isRgba = ((packed >> 31) & 1) != 0; // Check vertex array is enabled to avoid out of bounds exception when reading bytes - bool Enable = (ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + ArrayIndex * 4) & 0x1000) != 0; + bool enable = (ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + arrayIndex * 4) & 0x1000) != 0; //Note: 16 is the maximum size of an attribute, //having a component size of 32-bits with 4 elements (a vec4). - if (Enable) + if (enable) { - byte[] Data = Vmm.ReadBytes(VbPosition + Offset, 16); + byte[] data = vmm.ReadBytes(vbPosition + offset, 16); - Attribs[ArrayIndex].Add(new GalVertexAttrib(Attr, IsConst, Offset, Data, Size, Type, IsRgba)); + attribs[arrayIndex].Add(new GalVertexAttrib(attr, isConst, offset, data, size, type, isRgba)); } } - State.VertexBindings = new GalVertexBinding[32]; + state.VertexBindings = new GalVertexBinding[32]; - for (int Index = 0; Index < 32; Index++) + for (int index = 0; index < 32; index++) { - if (Attribs[Index] == null) + if (attribs[index] == null) { continue; } - int Control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + Index * 4); + int control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + index * 4); - bool Enable = (Control & 0x1000) != 0; + bool enable = (control & 0x1000) != 0; - if (!Enable) + if (!enable) { continue; } - long VbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + Index * 4); - long VbEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + Index * 2); + long vbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + index * 4); + long vbEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + index * 2); - int VertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + Index * 4); + int vertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + index * 4); - bool Instanced = ReadRegisterBool(NvGpuEngine3dReg.VertexArrayNInstance + Index); + bool instanced = ReadRegisterBool(NvGpuEngine3dReg.VertexArrayNInstance + index); - int Stride = Control & 0xfff; + int stride = control & 0xfff; - if (Instanced && VertexDivisor != 0) + if (instanced && vertexDivisor != 0) { - VbPosition += Stride * (CurrentInstance / VertexDivisor); + vbPosition += stride * (_currentInstance / vertexDivisor); } - if (VbPosition > VbEndPos) + if (vbPosition > vbEndPos) { //Instance is invalid, ignore the draw call continue; } - long VboKey = Vmm.GetPhysicalAddress(VbPosition); + long vboKey = vmm.GetPhysicalAddress(vbPosition); - long VbSize = (VbEndPos - VbPosition) + 1; - int ModifiedVbSize = (int)VbSize; + long vbSize = (vbEndPos - vbPosition) + 1; + int modifiedVbSize = (int)vbSize; // If quads convert size to triangle length - if (Stride == 0) + if (stride == 0) { - if (PrimType == GalPrimitiveType.Quads) + if (primType == GalPrimitiveType.Quads) { - ModifiedVbSize = QuadHelper.ConvertSizeQuadsToTris(ModifiedVbSize); + modifiedVbSize = QuadHelper.ConvertSizeQuadsToTris(modifiedVbSize); } - else if (PrimType == GalPrimitiveType.QuadStrip) + else if (primType == GalPrimitiveType.QuadStrip) { - ModifiedVbSize = QuadHelper.ConvertSizeQuadStripToTris(ModifiedVbSize); + modifiedVbSize = QuadHelper.ConvertSizeQuadStripToTris(modifiedVbSize); } } - bool VboCached = Gpu.Renderer.Rasterizer.IsVboCached(VboKey, ModifiedVbSize); + bool vboCached = _gpu.Renderer.Rasterizer.IsVboCached(vboKey, modifiedVbSize); - if (!VboCached || Gpu.ResourceManager.MemoryRegionModified(Vmm, VboKey, VbSize, NvGpuBufferType.Vertex)) + if (!vboCached || _gpu.ResourceManager.MemoryRegionModified(vmm, vboKey, vbSize, NvGpuBufferType.Vertex)) { - if ((PrimType == GalPrimitiveType.Quads | PrimType == GalPrimitiveType.QuadStrip) && Stride != 0) + if ((primType == GalPrimitiveType.Quads | primType == GalPrimitiveType.QuadStrip) && stride != 0) { // Convert quad buffer to triangles - byte[] data = Vmm.ReadBytes(VbPosition, VbSize); + byte[] data = vmm.ReadBytes(vbPosition, vbSize); - if (PrimType == GalPrimitiveType.Quads) + if (primType == GalPrimitiveType.Quads) { - data = QuadHelper.ConvertQuadsToTris(data, Stride, (int)(VbSize / Stride)); + data = QuadHelper.ConvertQuadsToTris(data, stride, (int)(vbSize / stride)); } else { - data = QuadHelper.ConvertQuadStripToTris(data, Stride, (int)(VbSize / Stride)); + data = QuadHelper.ConvertQuadStripToTris(data, stride, (int)(vbSize / stride)); } - Gpu.Renderer.Rasterizer.CreateVbo(VboKey, data); + _gpu.Renderer.Rasterizer.CreateVbo(vboKey, data); } - else if (Vmm.TryGetHostAddress(VbPosition, VbSize, out IntPtr VbPtr)) + else if (vmm.TryGetHostAddress(vbPosition, vbSize, out IntPtr vbPtr)) { - Gpu.Renderer.Rasterizer.CreateVbo(VboKey, (int)VbSize, VbPtr); + _gpu.Renderer.Rasterizer.CreateVbo(vboKey, (int)vbSize, vbPtr); } else { - Gpu.Renderer.Rasterizer.CreateVbo(VboKey, Vmm.ReadBytes(VbPosition, VbSize)); + _gpu.Renderer.Rasterizer.CreateVbo(vboKey, vmm.ReadBytes(vbPosition, vbSize)); } } - State.VertexBindings[Index].Enabled = true; - State.VertexBindings[Index].Stride = Stride; - State.VertexBindings[Index].VboKey = VboKey; - State.VertexBindings[Index].Instanced = Instanced; - State.VertexBindings[Index].Divisor = VertexDivisor; - State.VertexBindings[Index].Attribs = Attribs[Index].ToArray(); + state.VertexBindings[index].Enabled = true; + state.VertexBindings[index].Stride = stride; + state.VertexBindings[index].VboKey = vboKey; + state.VertexBindings[index].Instanced = instanced; + state.VertexBindings[index].Divisor = vertexDivisor; + state.VertexBindings[index].Attribs = attribs[index].ToArray(); } } - private void DispatchRender(NvGpuVmm Vmm, GalPipelineState State) + private void DispatchRender(NvGpuVmm vmm, GalPipelineState state) { - int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount); - int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl); + int indexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount); + int primCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl); - GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff); + GalPrimitiveType primType = (GalPrimitiveType)(primCtrl & 0xffff); - bool InstanceNext = ((PrimCtrl >> 26) & 1) != 0; - bool InstanceCont = ((PrimCtrl >> 27) & 1) != 0; + bool instanceNext = ((primCtrl >> 26) & 1) != 0; + bool instanceCont = ((primCtrl >> 27) & 1) != 0; - if (InstanceNext && InstanceCont) + if (instanceNext && instanceCont) { throw new InvalidOperationException("GPU tried to increase and reset instance count at the same time"); } - if (InstanceNext) + if (instanceNext) { - CurrentInstance++; + _currentInstance++; } - else if (!InstanceCont) + else if (!instanceCont) { - CurrentInstance = 0; + _currentInstance = 0; } - State.Instance = CurrentInstance; + state.Instance = _currentInstance; - Gpu.Renderer.Pipeline.Bind(State); + _gpu.Renderer.Pipeline.Bind(state); - Gpu.Renderer.RenderTarget.Bind(); + _gpu.Renderer.RenderTarget.Bind(); - if (IndexCount != 0) + if (indexCount != 0) { - int IndexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat); - int IndexFirst = ReadRegister(NvGpuEngine3dReg.IndexBatchFirst); - int VertexBase = ReadRegister(NvGpuEngine3dReg.VertexArrayElemBase); + int indexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat); + int indexFirst = ReadRegister(NvGpuEngine3dReg.IndexBatchFirst); + int vertexBase = ReadRegister(NvGpuEngine3dReg.VertexArrayElemBase); - long IndexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress); + long indexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress); - long IboKey = Vmm.GetPhysicalAddress(IndexPosition); + long iboKey = vmm.GetPhysicalAddress(indexPosition); //Quad primitive types were deprecated on OpenGL 3.x, //they are converted to a triangles index buffer on IB creation, //so we should use the triangles type here too. - if (PrimType == GalPrimitiveType.Quads || PrimType == GalPrimitiveType.QuadStrip) + if (primType == GalPrimitiveType.Quads || primType == GalPrimitiveType.QuadStrip) { //Note: We assume that index first points to the first //vertex of a quad, if it points to the middle of a //quad (First % 4 != 0 for Quads) then it will not work properly. - if (PrimType == GalPrimitiveType.Quads) + if (primType == GalPrimitiveType.Quads) { - IndexFirst = QuadHelper.ConvertSizeQuadsToTris(IndexFirst); + indexFirst = QuadHelper.ConvertSizeQuadsToTris(indexFirst); } else // QuadStrip { - IndexFirst = QuadHelper.ConvertSizeQuadStripToTris(IndexFirst); + indexFirst = QuadHelper.ConvertSizeQuadStripToTris(indexFirst); } - PrimType = GalPrimitiveType.Triangles; + primType = GalPrimitiveType.Triangles; } - Gpu.Renderer.Rasterizer.DrawElements(IboKey, IndexFirst, VertexBase, PrimType); + _gpu.Renderer.Rasterizer.DrawElements(iboKey, indexFirst, vertexBase, primType); } else { - int VertexFirst = ReadRegister(NvGpuEngine3dReg.VertexArrayFirst); - int VertexCount = ReadRegister(NvGpuEngine3dReg.VertexArrayCount); + int vertexFirst = ReadRegister(NvGpuEngine3dReg.VertexArrayFirst); + int vertexCount = ReadRegister(NvGpuEngine3dReg.VertexArrayCount); //Quad primitive types were deprecated on OpenGL 3.x, //they are converted to a triangles index buffer on IB creation, //so we should use the triangles type here too. - if (PrimType == GalPrimitiveType.Quads || PrimType == GalPrimitiveType.QuadStrip) + if (primType == GalPrimitiveType.Quads || primType == GalPrimitiveType.QuadStrip) { //Note: We assume that index first points to the first //vertex of a quad, if it points to the middle of a //quad (First % 4 != 0 for Quads) then it will not work properly. - if (PrimType == GalPrimitiveType.Quads) + if (primType == GalPrimitiveType.Quads) { - VertexFirst = QuadHelper.ConvertSizeQuadsToTris(VertexFirst); + vertexFirst = QuadHelper.ConvertSizeQuadsToTris(vertexFirst); } else // QuadStrip { - VertexFirst = QuadHelper.ConvertSizeQuadStripToTris(VertexFirst); + vertexFirst = QuadHelper.ConvertSizeQuadStripToTris(vertexFirst); } - PrimType = GalPrimitiveType.Triangles; - VertexCount = QuadHelper.ConvertSizeQuadsToTris(VertexCount); + primType = GalPrimitiveType.Triangles; + vertexCount = QuadHelper.ConvertSizeQuadsToTris(vertexCount); } - Gpu.Renderer.Rasterizer.DrawArrays(VertexFirst, VertexCount, PrimType); + _gpu.Renderer.Rasterizer.DrawArrays(vertexFirst, vertexCount, primType); } // Reset pipeline for host OpenGL calls - Gpu.Renderer.Pipeline.Unbind(State); + _gpu.Renderer.Pipeline.Unbind(state); //Is the GPU really clearing those registers after draw? WriteRegister(NvGpuEngine3dReg.IndexBatchFirst, 0); @@ -1062,115 +1061,115 @@ namespace Ryujinx.Graphics.Graphics3d WriteCounterAndTimestamp } - private void QueryControl(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void QueryControl(NvGpuVmm vmm, GpuMethodCall methCall) { - WriteRegister(MethCall); + WriteRegister(methCall); - long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.QueryAddress); + long position = MakeInt64From2xInt32(NvGpuEngine3dReg.QueryAddress); - int Seq = Registers[(int)NvGpuEngine3dReg.QuerySequence]; - int Ctrl = Registers[(int)NvGpuEngine3dReg.QueryControl]; + int seq = Registers[(int)NvGpuEngine3dReg.QuerySequence]; + int ctrl = Registers[(int)NvGpuEngine3dReg.QueryControl]; - QueryMode Mode = (QueryMode)(Ctrl & 3); + QueryMode mode = (QueryMode)(ctrl & 3); - switch (Mode) + switch (mode) { - case QueryMode.WriteSeq: Vmm.WriteInt32(Position, Seq); break; + case QueryMode.WriteSeq: vmm.WriteInt32(position, seq); break; case QueryMode.WriteCounterAndTimestamp: { //TODO: Implement counters. - long Counter = 1; + long counter = 1; - long Timestamp = PerformanceCounter.ElapsedMilliseconds; + long timestamp = PerformanceCounter.ElapsedMilliseconds; - Vmm.WriteInt64(Position + 0, Counter); - Vmm.WriteInt64(Position + 8, Timestamp); + vmm.WriteInt64(position + 0, counter); + vmm.WriteInt64(position + 8, timestamp); break; } } } - private void CbData(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void CbData(NvGpuVmm vmm, GpuMethodCall methCall) { - long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress); + long position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress); - int Offset = ReadRegister(NvGpuEngine3dReg.ConstBufferOffset); + int offset = ReadRegister(NvGpuEngine3dReg.ConstBufferOffset); - Vmm.WriteInt32(Position + Offset, MethCall.Argument); + vmm.WriteInt32(position + offset, methCall.Argument); - WriteRegister(NvGpuEngine3dReg.ConstBufferOffset, Offset + 4); + WriteRegister(NvGpuEngine3dReg.ConstBufferOffset, offset + 4); - Gpu.ResourceManager.ClearPbCache(NvGpuBufferType.ConstBuffer); + _gpu.ResourceManager.ClearPbCache(NvGpuBufferType.ConstBuffer); } - private void CbBind(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void CbBind(NvGpuVmm vmm, GpuMethodCall methCall) { - int Stage = (MethCall.Method - 0x904) >> 3; + int stage = (methCall.Method - 0x904) >> 3; - int Index = MethCall.Argument; + int index = methCall.Argument; - bool Enabled = (Index & 1) != 0; + bool enabled = (index & 1) != 0; - Index = (Index >> 4) & 0x1f; + index = (index >> 4) & 0x1f; - long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress); + long position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress); - long CbKey = Vmm.GetPhysicalAddress(Position); + long cbKey = vmm.GetPhysicalAddress(position); - int Size = ReadRegister(NvGpuEngine3dReg.ConstBufferSize); + int size = ReadRegister(NvGpuEngine3dReg.ConstBufferSize); - if (!Gpu.Renderer.Buffer.IsCached(CbKey, Size)) + if (!_gpu.Renderer.Buffer.IsCached(cbKey, size)) { - Gpu.Renderer.Buffer.Create(CbKey, Size); + _gpu.Renderer.Buffer.Create(cbKey, size); } - ConstBuffer Cb = ConstBuffers[Stage][Index]; + ConstBuffer cb = _constBuffers[stage][index]; - if (Cb.Position != Position || Cb.Enabled != Enabled || Cb.Size != Size) + if (cb.Position != position || cb.Enabled != enabled || cb.Size != size) { - ConstBuffers[Stage][Index].Position = Position; - ConstBuffers[Stage][Index].Enabled = Enabled; - ConstBuffers[Stage][Index].Size = Size; + _constBuffers[stage][index].Position = position; + _constBuffers[stage][index].Enabled = enabled; + _constBuffers[stage][index].Size = size; } } - private float GetFlipSign(NvGpuEngine3dReg Reg) + private float GetFlipSign(NvGpuEngine3dReg reg) { - return MathF.Sign(ReadRegisterFloat(Reg)); + return MathF.Sign(ReadRegisterFloat(reg)); } - private long MakeInt64From2xInt32(NvGpuEngine3dReg Reg) + private long MakeInt64From2xInt32(NvGpuEngine3dReg reg) { return - (long)Registers[(int)Reg + 0] << 32 | - (uint)Registers[(int)Reg + 1]; + (long)Registers[(int)reg + 0] << 32 | + (uint)Registers[(int)reg + 1]; } - private void WriteRegister(GpuMethodCall MethCall) + private void WriteRegister(GpuMethodCall methCall) { - Registers[MethCall.Method] = MethCall.Argument; + Registers[methCall.Method] = methCall.Argument; } - private int ReadRegister(NvGpuEngine3dReg Reg) + private int ReadRegister(NvGpuEngine3dReg reg) { - return Registers[(int)Reg]; + return Registers[(int)reg]; } - private float ReadRegisterFloat(NvGpuEngine3dReg Reg) + private float ReadRegisterFloat(NvGpuEngine3dReg reg) { - return BitConverter.Int32BitsToSingle(ReadRegister(Reg)); + return BitConverter.Int32BitsToSingle(ReadRegister(reg)); } - private bool ReadRegisterBool(NvGpuEngine3dReg Reg) + private bool ReadRegisterBool(NvGpuEngine3dReg reg) { - return (ReadRegister(Reg) & 1) != 0; + return (ReadRegister(reg) & 1) != 0; } - private void WriteRegister(NvGpuEngine3dReg Reg, int Value) + private void WriteRegister(NvGpuEngine3dReg reg, int value) { - Registers[(int)Reg] = Value; + Registers[(int)reg] = value; } } } diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngine3dReg.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngine3dReg.cs index 91346464..c6596a30 100644 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngine3dReg.cs +++ b/Ryujinx.Graphics/Graphics3d/NvGpuEngine3dReg.cs @@ -32,13 +32,13 @@ namespace Ryujinx.Graphics.Graphics3d StencilBackMask = 0x3d6, StencilBackFuncMask = 0x3d7, ColorMaskCommon = 0x3e4, - RTSeparateFragData = 0x3eb, + RtSeparateFragData = 0x3eb, ZetaAddress = 0x3f8, ZetaFormat = 0x3fa, ZetaBlockDimensions = 0x3fb, ZetaLayerStride = 0x3fc, VertexAttribNFormat = 0x458, - RTControl = 0x487, + RtControl = 0x487, ZetaHoriz = 0x48a, ZetaVert = 0x48b, ZetaArrayMode = 0x48c, diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mf.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mf.cs index 2f1df3d3..c0f444c3 100644 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mf.cs +++ b/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mf.cs @@ -1,4 +1,3 @@ -using Ryujinx.Common.Logging; using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Texture; using System.Collections.Generic; @@ -9,188 +8,188 @@ namespace Ryujinx.Graphics.Graphics3d { public int[] Registers { get; private set; } - private NvGpu Gpu; + private NvGpu _gpu; - private Dictionary Methods; + private Dictionary _methods; - public NvGpuEngineM2mf(NvGpu Gpu) + public NvGpuEngineM2mf(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; Registers = new int[0x1d6]; - Methods = new Dictionary(); + _methods = new Dictionary(); - void AddMethod(int Meth, int Count, int Stride, NvGpuMethod Method) + void AddMethod(int meth, int count, int stride, NvGpuMethod method) { - while (Count-- > 0) + while (count-- > 0) { - Methods.Add(Meth, Method); + _methods.Add(meth, method); - Meth += Stride; + meth += stride; } } AddMethod(0xc0, 1, 1, Execute); } - public void CallMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - if (Methods.TryGetValue(MethCall.Method, out NvGpuMethod Method)) + if (_methods.TryGetValue(methCall.Method, out NvGpuMethod method)) { - Method(Vmm, MethCall); + method(vmm, methCall); } else { - WriteRegister(MethCall); + WriteRegister(methCall); } } - private void Execute(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void Execute(NvGpuVmm vmm, GpuMethodCall methCall) { //TODO: Some registers and copy modes are still not implemented. - int Control = MethCall.Argument; + int control = methCall.Argument; - bool SrcLinear = ((Control >> 7) & 1) != 0; - bool DstLinear = ((Control >> 8) & 1) != 0; - bool Copy2d = ((Control >> 9) & 1) != 0; + bool srcLinear = ((control >> 7) & 1) != 0; + bool dstLinear = ((control >> 8) & 1) != 0; + bool copy2D = ((control >> 9) & 1) != 0; - long SrcAddress = MakeInt64From2xInt32(NvGpuEngineM2mfReg.SrcAddress); - long DstAddress = MakeInt64From2xInt32(NvGpuEngineM2mfReg.DstAddress); + long srcAddress = MakeInt64From2xInt32(NvGpuEngineM2mfReg.SrcAddress); + long dstAddress = MakeInt64From2xInt32(NvGpuEngineM2mfReg.DstAddress); - int SrcPitch = ReadRegister(NvGpuEngineM2mfReg.SrcPitch); - int DstPitch = ReadRegister(NvGpuEngineM2mfReg.DstPitch); + int srcPitch = ReadRegister(NvGpuEngineM2mfReg.SrcPitch); + int dstPitch = ReadRegister(NvGpuEngineM2mfReg.DstPitch); - int XCount = ReadRegister(NvGpuEngineM2mfReg.XCount); - int YCount = ReadRegister(NvGpuEngineM2mfReg.YCount); + int xCount = ReadRegister(NvGpuEngineM2mfReg.XCount); + int yCount = ReadRegister(NvGpuEngineM2mfReg.YCount); - int Swizzle = ReadRegister(NvGpuEngineM2mfReg.Swizzle); + int swizzle = ReadRegister(NvGpuEngineM2mfReg.Swizzle); - int DstBlkDim = ReadRegister(NvGpuEngineM2mfReg.DstBlkDim); - int DstSizeX = ReadRegister(NvGpuEngineM2mfReg.DstSizeX); - int DstSizeY = ReadRegister(NvGpuEngineM2mfReg.DstSizeY); - int DstSizeZ = ReadRegister(NvGpuEngineM2mfReg.DstSizeZ); - int DstPosXY = ReadRegister(NvGpuEngineM2mfReg.DstPosXY); - int DstPosZ = ReadRegister(NvGpuEngineM2mfReg.DstPosZ); + int dstBlkDim = ReadRegister(NvGpuEngineM2mfReg.DstBlkDim); + int dstSizeX = ReadRegister(NvGpuEngineM2mfReg.DstSizeX); + int dstSizeY = ReadRegister(NvGpuEngineM2mfReg.DstSizeY); + int dstSizeZ = ReadRegister(NvGpuEngineM2mfReg.DstSizeZ); + int dstPosXY = ReadRegister(NvGpuEngineM2mfReg.DstPosXY); + int dstPosZ = ReadRegister(NvGpuEngineM2mfReg.DstPosZ); - int SrcBlkDim = ReadRegister(NvGpuEngineM2mfReg.SrcBlkDim); - int SrcSizeX = ReadRegister(NvGpuEngineM2mfReg.SrcSizeX); - int SrcSizeY = ReadRegister(NvGpuEngineM2mfReg.SrcSizeY); - int SrcSizeZ = ReadRegister(NvGpuEngineM2mfReg.SrcSizeZ); - int SrcPosXY = ReadRegister(NvGpuEngineM2mfReg.SrcPosXY); - int SrcPosZ = ReadRegister(NvGpuEngineM2mfReg.SrcPosZ); + int srcBlkDim = ReadRegister(NvGpuEngineM2mfReg.SrcBlkDim); + int srcSizeX = ReadRegister(NvGpuEngineM2mfReg.SrcSizeX); + int srcSizeY = ReadRegister(NvGpuEngineM2mfReg.SrcSizeY); + int srcSizeZ = ReadRegister(NvGpuEngineM2mfReg.SrcSizeZ); + int srcPosXY = ReadRegister(NvGpuEngineM2mfReg.SrcPosXY); + int srcPosZ = ReadRegister(NvGpuEngineM2mfReg.SrcPosZ); - int SrcCpp = ((Swizzle >> 20) & 7) + 1; - int DstCpp = ((Swizzle >> 24) & 7) + 1; + int srcCpp = ((swizzle >> 20) & 7) + 1; + int dstCpp = ((swizzle >> 24) & 7) + 1; - int DstPosX = (DstPosXY >> 0) & 0xffff; - int DstPosY = (DstPosXY >> 16) & 0xffff; + int dstPosX = (dstPosXY >> 0) & 0xffff; + int dstPosY = (dstPosXY >> 16) & 0xffff; - int SrcPosX = (SrcPosXY >> 0) & 0xffff; - int SrcPosY = (SrcPosXY >> 16) & 0xffff; + int srcPosX = (srcPosXY >> 0) & 0xffff; + int srcPosY = (srcPosXY >> 16) & 0xffff; - int SrcBlockHeight = 1 << ((SrcBlkDim >> 4) & 0xf); - int DstBlockHeight = 1 << ((DstBlkDim >> 4) & 0xf); + int srcBlockHeight = 1 << ((srcBlkDim >> 4) & 0xf); + int dstBlockHeight = 1 << ((dstBlkDim >> 4) & 0xf); - long SrcPA = Vmm.GetPhysicalAddress(SrcAddress); - long DstPA = Vmm.GetPhysicalAddress(DstAddress); + long srcPa = vmm.GetPhysicalAddress(srcAddress); + long dstPa = vmm.GetPhysicalAddress(dstAddress); - if (Copy2d) + if (copy2D) { - if (SrcLinear) + if (srcLinear) { - SrcPosX = SrcPosY = SrcPosZ = 0; + srcPosX = srcPosY = srcPosZ = 0; } - if (DstLinear) + if (dstLinear) { - DstPosX = DstPosY = DstPosZ = 0; + dstPosX = dstPosY = dstPosZ = 0; } - if (SrcLinear && DstLinear) + if (srcLinear && dstLinear) { - for (int Y = 0; Y < YCount; Y++) + for (int y = 0; y < yCount; y++) { - int SrcOffset = (SrcPosY + Y) * SrcPitch + SrcPosX * SrcCpp; - int DstOffset = (DstPosY + Y) * DstPitch + DstPosX * DstCpp; + int srcOffset = (srcPosY + y) * srcPitch + srcPosX * srcCpp; + int dstOffset = (dstPosY + y) * dstPitch + dstPosX * dstCpp; - long Src = SrcPA + (uint)SrcOffset; - long Dst = DstPA + (uint)DstOffset; + long src = srcPa + (uint)srcOffset; + long dst = dstPa + (uint)dstOffset; - Vmm.Memory.CopyBytes(Src, Dst, XCount * SrcCpp); + vmm.Memory.CopyBytes(src, dst, xCount * srcCpp); } } else { - ISwizzle SrcSwizzle; + ISwizzle srcSwizzle; - if (SrcLinear) + if (srcLinear) { - SrcSwizzle = new LinearSwizzle(SrcPitch, SrcCpp, SrcSizeX, SrcSizeY); + srcSwizzle = new LinearSwizzle(srcPitch, srcCpp, srcSizeX, srcSizeY); } else { - SrcSwizzle = new BlockLinearSwizzle( - SrcSizeX, - SrcSizeY, 1, - SrcBlockHeight, 1, - SrcCpp); + srcSwizzle = new BlockLinearSwizzle( + srcSizeX, + srcSizeY, 1, + srcBlockHeight, 1, + srcCpp); } - ISwizzle DstSwizzle; + ISwizzle dstSwizzle; - if (DstLinear) + if (dstLinear) { - DstSwizzle = new LinearSwizzle(DstPitch, DstCpp, SrcSizeX, SrcSizeY); + dstSwizzle = new LinearSwizzle(dstPitch, dstCpp, srcSizeX, srcSizeY); } else { - DstSwizzle = new BlockLinearSwizzle( - DstSizeX, - DstSizeY, 1, - DstBlockHeight, 1, - DstCpp); + dstSwizzle = new BlockLinearSwizzle( + dstSizeX, + dstSizeY, 1, + dstBlockHeight, 1, + dstCpp); } - for (int Y = 0; Y < YCount; Y++) - for (int X = 0; X < XCount; X++) + for (int y = 0; y < yCount; y++) + for (int x = 0; x < xCount; x++) { - int SrcOffset = SrcSwizzle.GetSwizzleOffset(SrcPosX + X, SrcPosY + Y, 0); - int DstOffset = DstSwizzle.GetSwizzleOffset(DstPosX + X, DstPosY + Y, 0); + int srcOffset = srcSwizzle.GetSwizzleOffset(srcPosX + x, srcPosY + y, 0); + int dstOffset = dstSwizzle.GetSwizzleOffset(dstPosX + x, dstPosY + y, 0); - long Src = SrcPA + (uint)SrcOffset; - long Dst = DstPA + (uint)DstOffset; + long src = srcPa + (uint)srcOffset; + long dst = dstPa + (uint)dstOffset; - Vmm.Memory.CopyBytes(Src, Dst, SrcCpp); + vmm.Memory.CopyBytes(src, dst, srcCpp); } } } else { - Vmm.Memory.CopyBytes(SrcPA, DstPA, XCount); + vmm.Memory.CopyBytes(srcPa, dstPa, xCount); } } - private long MakeInt64From2xInt32(NvGpuEngineM2mfReg Reg) + private long MakeInt64From2xInt32(NvGpuEngineM2mfReg reg) { return - (long)Registers[(int)Reg + 0] << 32 | - (uint)Registers[(int)Reg + 1]; + (long)Registers[(int)reg + 0] << 32 | + (uint)Registers[(int)reg + 1]; } - private void WriteRegister(GpuMethodCall MethCall) + private void WriteRegister(GpuMethodCall methCall) { - Registers[MethCall.Method] = MethCall.Argument; + Registers[methCall.Method] = methCall.Argument; } - private int ReadRegister(NvGpuEngineM2mfReg Reg) + private int ReadRegister(NvGpuEngineM2mfReg reg) { - return Registers[(int)Reg]; + return Registers[(int)reg]; } - private void WriteRegister(NvGpuEngineM2mfReg Reg, int Value) + private void WriteRegister(NvGpuEngineM2mfReg reg, int value) { - Registers[(int)Reg] = Value; + Registers[(int)reg] = value; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mf.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mf.cs index 62872ba1..d24f2303 100644 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mf.cs +++ b/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mf.cs @@ -1,4 +1,3 @@ -using Ryujinx.Common.Logging; using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Texture; using System.Collections.Generic; @@ -9,41 +8,41 @@ namespace Ryujinx.Graphics.Graphics3d { public int[] Registers { get; private set; } - private NvGpu Gpu; + private NvGpu _gpu; - private Dictionary Methods; + private Dictionary _methods; - private int CopyStartX; - private int CopyStartY; + private int _copyStartX; + private int _copyStartY; - private int CopyWidth; - private int CopyHeight; - private int CopyGobBlockHeight; + private int _copyWidth; + private int _copyHeight; + private int _copyGobBlockHeight; - private long CopyAddress; + private long _copyAddress; - private int CopyOffset; - private int CopySize; + private int _copyOffset; + private int _copySize; - private bool CopyLinear; + private bool _copyLinear; - private byte[] Buffer; + private byte[] _buffer; - public NvGpuEngineP2mf(NvGpu Gpu) + public NvGpuEngineP2mf(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; Registers = new int[0x80]; - Methods = new Dictionary(); + _methods = new Dictionary(); - void AddMethod(int Meth, int Count, int Stride, NvGpuMethod Method) + void AddMethod(int meth, int count, int stride, NvGpuMethod method) { - while (Count-- > 0) + while (count-- > 0) { - Methods.Add(Meth, Method); + _methods.Add(meth, method); - Meth += Stride; + meth += stride; } } @@ -51,115 +50,115 @@ namespace Ryujinx.Graphics.Graphics3d AddMethod(0x6d, 1, 1, PushData); } - public void CallMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - if (Methods.TryGetValue(MethCall.Method, out NvGpuMethod Method)) + if (_methods.TryGetValue(methCall.Method, out NvGpuMethod method)) { - Method(Vmm, MethCall); + method(vmm, methCall); } else { - WriteRegister(MethCall); + WriteRegister(methCall); } } - private void Execute(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void Execute(NvGpuVmm vmm, GpuMethodCall methCall) { //TODO: Some registers and copy modes are still not implemented. - int Control = MethCall.Argument; + int control = methCall.Argument; - long DstAddress = MakeInt64From2xInt32(NvGpuEngineP2mfReg.DstAddress); + long dstAddress = MakeInt64From2xInt32(NvGpuEngineP2mfReg.DstAddress); - int DstPitch = ReadRegister(NvGpuEngineP2mfReg.DstPitch); - int DstBlkDim = ReadRegister(NvGpuEngineP2mfReg.DstBlockDim); + int dstPitch = ReadRegister(NvGpuEngineP2mfReg.DstPitch); + int dstBlkDim = ReadRegister(NvGpuEngineP2mfReg.DstBlockDim); - int DstX = ReadRegister(NvGpuEngineP2mfReg.DstX); - int DstY = ReadRegister(NvGpuEngineP2mfReg.DstY); + int dstX = ReadRegister(NvGpuEngineP2mfReg.DstX); + int dstY = ReadRegister(NvGpuEngineP2mfReg.DstY); - int DstWidth = ReadRegister(NvGpuEngineP2mfReg.DstWidth); - int DstHeight = ReadRegister(NvGpuEngineP2mfReg.DstHeight); + int dstWidth = ReadRegister(NvGpuEngineP2mfReg.DstWidth); + int dstHeight = ReadRegister(NvGpuEngineP2mfReg.DstHeight); - int LineLengthIn = ReadRegister(NvGpuEngineP2mfReg.LineLengthIn); - int LineCount = ReadRegister(NvGpuEngineP2mfReg.LineCount); + int lineLengthIn = ReadRegister(NvGpuEngineP2mfReg.LineLengthIn); + int lineCount = ReadRegister(NvGpuEngineP2mfReg.LineCount); - CopyLinear = (Control & 1) != 0; + _copyLinear = (control & 1) != 0; - CopyGobBlockHeight = 1 << ((DstBlkDim >> 4) & 0xf); + _copyGobBlockHeight = 1 << ((dstBlkDim >> 4) & 0xf); - CopyStartX = DstX; - CopyStartY = DstY; + _copyStartX = dstX; + _copyStartY = dstY; - CopyWidth = DstWidth; - CopyHeight = DstHeight; + _copyWidth = dstWidth; + _copyHeight = dstHeight; - CopyAddress = DstAddress; + _copyAddress = dstAddress; - CopyOffset = 0; - CopySize = LineLengthIn * LineCount; + _copyOffset = 0; + _copySize = lineLengthIn * lineCount; - Buffer = new byte[CopySize]; + _buffer = new byte[_copySize]; } - private void PushData(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void PushData(NvGpuVmm vmm, GpuMethodCall methCall) { - if (Buffer == null) + if (_buffer == null) { return; } - for (int Shift = 0; Shift < 32 && CopyOffset < CopySize; Shift += 8, CopyOffset++) + for (int shift = 0; shift < 32 && _copyOffset < _copySize; shift += 8, _copyOffset++) { - Buffer[CopyOffset] = (byte)(MethCall.Argument >> Shift); + _buffer[_copyOffset] = (byte)(methCall.Argument >> shift); } - if (MethCall.IsLastCall) + if (methCall.IsLastCall) { - if (CopyLinear) + if (_copyLinear) { - Vmm.WriteBytes(CopyAddress, Buffer); + vmm.WriteBytes(_copyAddress, _buffer); } else { - BlockLinearSwizzle Swizzle = new BlockLinearSwizzle( - CopyWidth, - CopyHeight, 1, - CopyGobBlockHeight, 1, 1); + BlockLinearSwizzle swizzle = new BlockLinearSwizzle( + _copyWidth, + _copyHeight, 1, + _copyGobBlockHeight, 1, 1); - int SrcOffset = 0; + int srcOffset = 0; - for (int Y = CopyStartY; Y < CopyHeight && SrcOffset < CopySize; Y++) - for (int X = CopyStartX; X < CopyWidth && SrcOffset < CopySize; X++) + for (int y = _copyStartY; y < _copyHeight && srcOffset < _copySize; y++) + for (int x = _copyStartX; x < _copyWidth && srcOffset < _copySize; x++) { - int DstOffset = Swizzle.GetSwizzleOffset(X, Y, 0); + int dstOffset = swizzle.GetSwizzleOffset(x, y, 0); - Vmm.WriteByte(CopyAddress + DstOffset, Buffer[SrcOffset++]); + vmm.WriteByte(_copyAddress + dstOffset, _buffer[srcOffset++]); } } - Buffer = null; + _buffer = null; } } - private long MakeInt64From2xInt32(NvGpuEngineP2mfReg Reg) + private long MakeInt64From2xInt32(NvGpuEngineP2mfReg reg) { return - (long)Registers[(int)Reg + 0] << 32 | - (uint)Registers[(int)Reg + 1]; + (long)Registers[(int)reg + 0] << 32 | + (uint)Registers[(int)reg + 1]; } - private void WriteRegister(GpuMethodCall MethCall) + private void WriteRegister(GpuMethodCall methCall) { - Registers[MethCall.Method] = MethCall.Argument; + Registers[methCall.Method] = methCall.Argument; } - private int ReadRegister(NvGpuEngineP2mfReg Reg) + private int ReadRegister(NvGpuEngineP2mfReg reg) { - return Registers[(int)Reg]; + return Registers[(int)reg]; } - private void WriteRegister(NvGpuEngineP2mfReg Reg, int Value) + private void WriteRegister(NvGpuEngineP2mfReg reg, int value) { - Registers[(int)Reg] = Value; + Registers[(int)reg] = value; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuFifo.cs b/Ryujinx.Graphics/Graphics3d/NvGpuFifo.cs index f834ade7..25c1a9cd 100644 --- a/Ryujinx.Graphics/Graphics3d/NvGpuFifo.cs +++ b/Ryujinx.Graphics/Graphics3d/NvGpuFifo.cs @@ -11,166 +11,166 @@ namespace Ryujinx.Graphics.Graphics3d //a guess here and use 256kb as the size. Increase if needed. private const int MmeWords = 256 * 256; - private NvGpu Gpu; + private NvGpu _gpu; - private NvGpuEngine[] SubChannels; + private NvGpuEngine[] _subChannels; private struct CachedMacro { public int Position { get; private set; } - private bool ExecutionPending; - private int Argument; + private bool _executionPending; + private int _argument; - private MacroInterpreter Interpreter; + private MacroInterpreter _interpreter; - public CachedMacro(NvGpuFifo PFifo, INvGpuEngine Engine, int Position) + public CachedMacro(NvGpuFifo pFifo, INvGpuEngine engine, int position) { - this.Position = Position; + Position = position; - ExecutionPending = false; - Argument = 0; + _executionPending = false; + _argument = 0; - Interpreter = new MacroInterpreter(PFifo, Engine); + _interpreter = new MacroInterpreter(pFifo, engine); } - public void StartExecution(int Argument) + public void StartExecution(int argument) { - this.Argument = Argument; + _argument = argument; - ExecutionPending = true; + _executionPending = true; } - public void Execute(NvGpuVmm Vmm, int[] Mme) + public void Execute(NvGpuVmm vmm, int[] mme) { - if (ExecutionPending) + if (_executionPending) { - ExecutionPending = false; + _executionPending = false; - Interpreter?.Execute(Vmm, Mme, Position, Argument); + _interpreter?.Execute(vmm, mme, Position, _argument); } } - public void PushArgument(int Argument) + public void PushArgument(int argument) { - Interpreter?.Fifo.Enqueue(Argument); + _interpreter?.Fifo.Enqueue(argument); } } - private int CurrMacroPosition; - private int CurrMacroBindIndex; + private int _currMacroPosition; + private int _currMacroBindIndex; - private CachedMacro[] Macros; + private CachedMacro[] _macros; - private int[] Mme; + private int[] _mme; - public NvGpuFifo(NvGpu Gpu) + public NvGpuFifo(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; - SubChannels = new NvGpuEngine[8]; + _subChannels = new NvGpuEngine[8]; - Macros = new CachedMacro[MacrosCount]; + _macros = new CachedMacro[MacrosCount]; - Mme = new int[MmeWords]; + _mme = new int[MmeWords]; } - public void CallMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - if ((NvGpuFifoMeth)MethCall.Method == NvGpuFifoMeth.BindChannel) + if ((NvGpuFifoMeth)methCall.Method == NvGpuFifoMeth.BindChannel) { - NvGpuEngine Engine = (NvGpuEngine)MethCall.Argument; + NvGpuEngine engine = (NvGpuEngine)methCall.Argument; - SubChannels[MethCall.SubChannel] = Engine; + _subChannels[methCall.SubChannel] = engine; } else { - switch (SubChannels[MethCall.SubChannel]) + switch (_subChannels[methCall.SubChannel]) { - case NvGpuEngine._2d: Call2dMethod (Vmm, MethCall); break; - case NvGpuEngine._3d: Call3dMethod (Vmm, MethCall); break; - case NvGpuEngine.P2mf: CallP2mfMethod(Vmm, MethCall); break; - case NvGpuEngine.M2mf: CallM2mfMethod(Vmm, MethCall); break; + case NvGpuEngine._2d: Call2dMethod (vmm, methCall); break; + case NvGpuEngine._3d: Call3dMethod (vmm, methCall); break; + case NvGpuEngine.P2mf: CallP2mfMethod(vmm, methCall); break; + case NvGpuEngine.M2mf: CallM2mfMethod(vmm, methCall); break; } } } - private void Call2dMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void Call2dMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - Gpu.Engine2d.CallMethod(Vmm, MethCall); + _gpu.Engine2d.CallMethod(vmm, methCall); } - private void Call3dMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void Call3dMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - if (MethCall.Method < 0x80) + if (methCall.Method < 0x80) { - switch ((NvGpuFifoMeth)MethCall.Method) + switch ((NvGpuFifoMeth)methCall.Method) { case NvGpuFifoMeth.SetMacroUploadAddress: { - CurrMacroPosition = MethCall.Argument; + _currMacroPosition = methCall.Argument; break; } case NvGpuFifoMeth.SendMacroCodeData: { - Mme[CurrMacroPosition++] = MethCall.Argument; + _mme[_currMacroPosition++] = methCall.Argument; break; } case NvGpuFifoMeth.SetMacroBindingIndex: { - CurrMacroBindIndex = MethCall.Argument; + _currMacroBindIndex = methCall.Argument; break; } case NvGpuFifoMeth.BindMacro: { - int Position = MethCall.Argument; + int position = methCall.Argument; - Macros[CurrMacroBindIndex] = new CachedMacro(this, Gpu.Engine3d, Position); + _macros[_currMacroBindIndex] = new CachedMacro(this, _gpu.Engine3d, position); break; } - default: CallP2mfMethod(Vmm, MethCall); break; + default: CallP2mfMethod(vmm, methCall); break; } } - else if (MethCall.Method < 0xe00) + else if (methCall.Method < 0xe00) { - Gpu.Engine3d.CallMethod(Vmm, MethCall); + _gpu.Engine3d.CallMethod(vmm, methCall); } else { - int MacroIndex = (MethCall.Method >> 1) & MacroIndexMask; + int macroIndex = (methCall.Method >> 1) & MacroIndexMask; - if ((MethCall.Method & 1) != 0) + if ((methCall.Method & 1) != 0) { - Macros[MacroIndex].PushArgument(MethCall.Argument); + _macros[macroIndex].PushArgument(methCall.Argument); } else { - Macros[MacroIndex].StartExecution(MethCall.Argument); + _macros[macroIndex].StartExecution(methCall.Argument); } - if (MethCall.IsLastCall) + if (methCall.IsLastCall) { - Macros[MacroIndex].Execute(Vmm, Mme); + _macros[macroIndex].Execute(vmm, _mme); } } } - private void CallP2mfMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void CallP2mfMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - Gpu.EngineP2mf.CallMethod(Vmm, MethCall); + _gpu.EngineP2mf.CallMethod(vmm, methCall); } - private void CallM2mfMethod(NvGpuVmm Vmm, GpuMethodCall MethCall) + private void CallM2mfMethod(NvGpuVmm vmm, GpuMethodCall methCall) { - Gpu.EngineM2mf.CallMethod(Vmm, MethCall); + _gpu.EngineM2mf.CallMethod(vmm, methCall); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuMethod.cs b/Ryujinx.Graphics/Graphics3d/NvGpuMethod.cs index 8730d144..23185c81 100644 --- a/Ryujinx.Graphics/Graphics3d/NvGpuMethod.cs +++ b/Ryujinx.Graphics/Graphics3d/NvGpuMethod.cs @@ -2,5 +2,5 @@ using Ryujinx.Graphics.Memory; namespace Ryujinx.Graphics.Graphics3d { - delegate void NvGpuMethod(NvGpuVmm Vmm, GpuMethodCall MethCall); + delegate void NvGpuMethod(NvGpuVmm vmm, GpuMethodCall methCall); } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/ASTCDecoder.cs b/Ryujinx.Graphics/Graphics3d/Texture/ASTCDecoder.cs deleted file mode 100644 index 00158dc1..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/ASTCDecoder.cs +++ /dev/null @@ -1,1385 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; - -namespace Ryujinx.Graphics.Texture -{ - public class ASTCDecoderException : Exception - { - public ASTCDecoderException(string ExMsg) : base(ExMsg) { } - } - - //https://github.com/GammaUNC/FasTC/blob/master/ASTCEncoder/src/Decompressor.cpp - public static class ASTCDecoder - { - struct TexelWeightParams - { - public int Width; - public int Height; - public bool DualPlane; - public int MaxWeight; - public bool Error; - public bool VoidExtentLDR; - public bool VoidExtentHDR; - - public int GetPackedBitSize() - { - // How many indices do we have? - int Indices = Height * Width; - - if (DualPlane) - { - Indices *= 2; - } - - IntegerEncoded IntEncoded = IntegerEncoded.CreateEncoding(MaxWeight); - - return IntEncoded.GetBitLength(Indices); - } - - public int GetNumWeightValues() - { - int Ret = Width * Height; - - if (DualPlane) - { - Ret *= 2; - } - - return Ret; - } - } - - public static byte[] DecodeToRGBA8888( - byte[] InputBuffer, - int BlockX, - int BlockY, - int BlockZ, - int X, - int Y, - int Z) - { - using (MemoryStream InputStream = new MemoryStream(InputBuffer)) - { - BinaryReader BinReader = new BinaryReader(InputStream); - - if (BlockX > 12 || BlockY > 12) - { - throw new ASTCDecoderException("Block size unsupported!"); - } - - if (BlockZ != 1 || Z != 1) - { - // TODO: Support 3D textures? - throw new ASTCDecoderException("3D compressed textures unsupported!"); - } - - using (MemoryStream OutputStream = new MemoryStream()) - { - int BlockIndex = 0; - - for (int j = 0; j < Y; j += BlockY) - { - for (int i = 0; i < X; i += BlockX) - { - int[] DecompressedData = new int[144]; - - DecompressBlock(BinReader.ReadBytes(0x10), DecompressedData, BlockX, BlockY); - - int DecompressedWidth = Math.Min(BlockX, X - i); - int DecompressedHeight = Math.Min(BlockY, Y - j); - int BaseOffsets = (j * X + i) * 4; - - for (int jj = 0; jj < DecompressedHeight; jj++) - { - OutputStream.Seek(BaseOffsets + jj * X * 4, SeekOrigin.Begin); - - byte[] OutputBuffer = new byte[DecompressedData.Length * sizeof(int)]; - Buffer.BlockCopy(DecompressedData, 0, OutputBuffer, 0, OutputBuffer.Length); - - OutputStream.Write(OutputBuffer, jj * BlockX * 4, DecompressedWidth * 4); - } - - BlockIndex++; - } - } - - return OutputStream.ToArray(); - } - } - } - - public static bool DecompressBlock( - byte[] InputBuffer, - int[] OutputBuffer, - int BlockWidth, - int BlockHeight) - { - BitArrayStream BitStream = new BitArrayStream(new BitArray(InputBuffer)); - TexelWeightParams TexelParams = DecodeBlockInfo(BitStream); - - if (TexelParams.Error) - { - throw new ASTCDecoderException("Invalid block mode"); - } - - if (TexelParams.VoidExtentLDR) - { - FillVoidExtentLDR(BitStream, OutputBuffer, BlockWidth, BlockHeight); - - return true; - } - - if (TexelParams.VoidExtentHDR) - { - throw new ASTCDecoderException("HDR void extent blocks are unsupported!"); - } - - if (TexelParams.Width > BlockWidth) - { - throw new ASTCDecoderException("Texel weight grid width should be smaller than block width"); - } - - if (TexelParams.Height > BlockHeight) - { - throw new ASTCDecoderException("Texel weight grid height should be smaller than block height"); - } - - // Read num partitions - int NumberPartitions = BitStream.ReadBits(2) + 1; - Debug.Assert(NumberPartitions <= 4); - - if (NumberPartitions == 4 && TexelParams.DualPlane) - { - throw new ASTCDecoderException("Dual plane mode is incompatible with four partition blocks"); - } - - // Based on the number of partitions, read the color endpoint mode for - // each partition. - - // Determine partitions, partition index, and color endpoint modes - int PlaneIndices = -1; - int PartitionIndex; - uint[] ColorEndpointMode = { 0, 0, 0, 0 }; - - BitArrayStream ColorEndpointStream = new BitArrayStream(new BitArray(16 * 8)); - - // Read extra config data... - uint BaseColorEndpointMode = 0; - - if (NumberPartitions == 1) - { - ColorEndpointMode[0] = (uint)BitStream.ReadBits(4); - PartitionIndex = 0; - } - else - { - PartitionIndex = BitStream.ReadBits(10); - BaseColorEndpointMode = (uint)BitStream.ReadBits(6); - } - - uint BaseMode = (BaseColorEndpointMode & 3); - - // Remaining bits are color endpoint data... - int NumberWeightBits = TexelParams.GetPackedBitSize(); - int RemainingBits = 128 - NumberWeightBits - BitStream.Position; - - // Consider extra bits prior to texel data... - uint ExtraColorEndpointModeBits = 0; - - if (BaseMode != 0) - { - switch (NumberPartitions) - { - case 2: ExtraColorEndpointModeBits += 2; break; - case 3: ExtraColorEndpointModeBits += 5; break; - case 4: ExtraColorEndpointModeBits += 8; break; - default: Debug.Assert(false); break; - } - } - - RemainingBits -= (int)ExtraColorEndpointModeBits; - - // Do we have a dual plane situation? - int PlaneSelectorBits = 0; - - if (TexelParams.DualPlane) - { - PlaneSelectorBits = 2; - } - - RemainingBits -= PlaneSelectorBits; - - // Read color data... - int ColorDataBits = RemainingBits; - - while (RemainingBits > 0) - { - int NumberBits = Math.Min(RemainingBits, 8); - int Bits = BitStream.ReadBits(NumberBits); - ColorEndpointStream.WriteBits(Bits, NumberBits); - RemainingBits -= 8; - } - - // Read the plane selection bits - PlaneIndices = BitStream.ReadBits(PlaneSelectorBits); - - // Read the rest of the CEM - if (BaseMode != 0) - { - uint ExtraColorEndpointMode = (uint)BitStream.ReadBits((int)ExtraColorEndpointModeBits); - uint TempColorEndpointMode = (ExtraColorEndpointMode << 6) | BaseColorEndpointMode; - TempColorEndpointMode >>= 2; - - bool[] C = new bool[4]; - - for (int i = 0; i < NumberPartitions; i++) - { - C[i] = (TempColorEndpointMode & 1) != 0; - TempColorEndpointMode >>= 1; - } - - byte[] M = new byte[4]; - - for (int i = 0; i < NumberPartitions; i++) - { - M[i] = (byte)(TempColorEndpointMode & 3); - TempColorEndpointMode >>= 2; - Debug.Assert(M[i] <= 3); - } - - for (int i = 0; i < NumberPartitions; i++) - { - ColorEndpointMode[i] = BaseMode; - if (!(C[i])) ColorEndpointMode[i] -= 1; - ColorEndpointMode[i] <<= 2; - ColorEndpointMode[i] |= M[i]; - } - } - else if (NumberPartitions > 1) - { - uint TempColorEndpointMode = BaseColorEndpointMode >> 2; - - for (uint i = 0; i < NumberPartitions; i++) - { - ColorEndpointMode[i] = TempColorEndpointMode; - } - } - - // Make sure everything up till here is sane. - for (int i = 0; i < NumberPartitions; i++) - { - Debug.Assert(ColorEndpointMode[i] < 16); - } - Debug.Assert(BitStream.Position + TexelParams.GetPackedBitSize() == 128); - - // Decode both color data and texel weight data - int[] ColorValues = new int[32]; // Four values * two endpoints * four maximum partitions - DecodeColorValues(ColorValues, ColorEndpointStream.ToByteArray(), ColorEndpointMode, NumberPartitions, ColorDataBits); - - ASTCPixel[][] EndPoints = new ASTCPixel[4][]; - EndPoints[0] = new ASTCPixel[2]; - EndPoints[1] = new ASTCPixel[2]; - EndPoints[2] = new ASTCPixel[2]; - EndPoints[3] = new ASTCPixel[2]; - - int ColorValuesPosition = 0; - - for (int i = 0; i < NumberPartitions; i++) - { - ComputeEndpoints(EndPoints[i], ColorValues, ColorEndpointMode[i], ref ColorValuesPosition); - } - - // Read the texel weight data. - byte[] TexelWeightData = (byte[])InputBuffer.Clone(); - - // Reverse everything - for (int i = 0; i < 8; i++) - { - byte a = ReverseByte(TexelWeightData[i]); - byte b = ReverseByte(TexelWeightData[15 - i]); - - TexelWeightData[i] = b; - TexelWeightData[15 - i] = a; - } - - // Make sure that higher non-texel bits are set to zero - int ClearByteStart = (TexelParams.GetPackedBitSize() >> 3) + 1; - TexelWeightData[ClearByteStart - 1] &= (byte)((1 << (TexelParams.GetPackedBitSize() % 8)) - 1); - - int cLen = 16 - ClearByteStart; - for (int i = ClearByteStart; i < ClearByteStart + cLen; i++) TexelWeightData[i] = 0; - - List TexelWeightValues = new List(); - BitArrayStream WeightBitStream = new BitArrayStream(new BitArray(TexelWeightData)); - - IntegerEncoded.DecodeIntegerSequence(TexelWeightValues, WeightBitStream, TexelParams.MaxWeight, TexelParams.GetNumWeightValues()); - - // Blocks can be at most 12x12, so we can have as many as 144 weights - int[][] Weights = new int[2][]; - Weights[0] = new int[144]; - Weights[1] = new int[144]; - - UnquantizeTexelWeights(Weights, TexelWeightValues, TexelParams, BlockWidth, BlockHeight); - - // Now that we have endpoints and weights, we can interpolate and generate - // the proper decoding... - for (int j = 0; j < BlockHeight; j++) - { - for (int i = 0; i < BlockWidth; i++) - { - int Partition = Select2DPartition(PartitionIndex, i, j, NumberPartitions, ((BlockHeight * BlockWidth) < 32)); - Debug.Assert(Partition < NumberPartitions); - - ASTCPixel Pixel = new ASTCPixel(0, 0, 0, 0); - for (int Component = 0; Component < 4; Component++) - { - int Component0 = EndPoints[Partition][0].GetComponent(Component); - Component0 = BitArrayStream.Replicate(Component0, 8, 16); - int Component1 = EndPoints[Partition][1].GetComponent(Component); - Component1 = BitArrayStream.Replicate(Component1, 8, 16); - - int Plane = 0; - - if (TexelParams.DualPlane && (((PlaneIndices + 1) & 3) == Component)) - { - Plane = 1; - } - - int Weight = Weights[Plane][j * BlockWidth + i]; - int FinalComponent = (Component0 * (64 - Weight) + Component1 * Weight + 32) / 64; - - if (FinalComponent == 65535) - { - Pixel.SetComponent(Component, 255); - } - else - { - double FinalComponentFloat = FinalComponent; - Pixel.SetComponent(Component, (int)(255.0 * (FinalComponentFloat / 65536.0) + 0.5)); - } - } - - OutputBuffer[j * BlockWidth + i] = Pixel.Pack(); - } - } - - return true; - } - - private static int Select2DPartition(int Seed, int X, int Y, int PartitionCount, bool IsSmallBlock) - { - return SelectPartition(Seed, X, Y, 0, PartitionCount, IsSmallBlock); - } - - private static int SelectPartition(int Seed, int X, int Y, int Z, int PartitionCount, bool IsSmallBlock) - { - if (PartitionCount == 1) - { - return 0; - } - - if (IsSmallBlock) - { - X <<= 1; - Y <<= 1; - Z <<= 1; - } - - Seed += (PartitionCount - 1) * 1024; - - int RightNum = Hash52((uint)Seed); - byte Seed01 = (byte)(RightNum & 0xF); - byte Seed02 = (byte)((RightNum >> 4) & 0xF); - byte Seed03 = (byte)((RightNum >> 8) & 0xF); - byte Seed04 = (byte)((RightNum >> 12) & 0xF); - byte Seed05 = (byte)((RightNum >> 16) & 0xF); - byte Seed06 = (byte)((RightNum >> 20) & 0xF); - byte Seed07 = (byte)((RightNum >> 24) & 0xF); - byte Seed08 = (byte)((RightNum >> 28) & 0xF); - byte Seed09 = (byte)((RightNum >> 18) & 0xF); - byte Seed10 = (byte)((RightNum >> 22) & 0xF); - byte Seed11 = (byte)((RightNum >> 26) & 0xF); - byte Seed12 = (byte)(((RightNum >> 30) | (RightNum << 2)) & 0xF); - - Seed01 *= Seed01; Seed02 *= Seed02; - Seed03 *= Seed03; Seed04 *= Seed04; - Seed05 *= Seed05; Seed06 *= Seed06; - Seed07 *= Seed07; Seed08 *= Seed08; - Seed09 *= Seed09; Seed10 *= Seed10; - Seed11 *= Seed11; Seed12 *= Seed12; - - int SeedHash1, SeedHash2, SeedHash3; - - if ((Seed & 1) != 0) - { - SeedHash1 = (Seed & 2) != 0 ? 4 : 5; - SeedHash2 = (PartitionCount == 3) ? 6 : 5; - } - else - { - SeedHash1 = (PartitionCount == 3) ? 6 : 5; - SeedHash2 = (Seed & 2) != 0 ? 4 : 5; - } - - SeedHash3 = (Seed & 0x10) != 0 ? SeedHash1 : SeedHash2; - - Seed01 >>= SeedHash1; Seed02 >>= SeedHash2; Seed03 >>= SeedHash1; Seed04 >>= SeedHash2; - Seed05 >>= SeedHash1; Seed06 >>= SeedHash2; Seed07 >>= SeedHash1; Seed08 >>= SeedHash2; - Seed09 >>= SeedHash3; Seed10 >>= SeedHash3; Seed11 >>= SeedHash3; Seed12 >>= SeedHash3; - - int a = Seed01 * X + Seed02 * Y + Seed11 * Z + (RightNum >> 14); - int b = Seed03 * X + Seed04 * Y + Seed12 * Z + (RightNum >> 10); - int c = Seed05 * X + Seed06 * Y + Seed09 * Z + (RightNum >> 6); - int d = Seed07 * X + Seed08 * Y + Seed10 * Z + (RightNum >> 2); - - a &= 0x3F; b &= 0x3F; c &= 0x3F; d &= 0x3F; - - if (PartitionCount < 4) d = 0; - if (PartitionCount < 3) c = 0; - - if (a >= b && a >= c && a >= d) return 0; - else if (b >= c && b >= d) return 1; - else if (c >= d) return 2; - return 3; - } - - static int Hash52(uint Val) - { - Val ^= Val >> 15; Val -= Val << 17; Val += Val << 7; Val += Val << 4; - Val ^= Val >> 5; Val += Val << 16; Val ^= Val >> 7; Val ^= Val >> 3; - Val ^= Val << 6; Val ^= Val >> 17; - - return (int)Val; - } - - static void UnquantizeTexelWeights( - int[][] OutputBuffer, - List Weights, - TexelWeightParams TexelParams, - int BlockWidth, - int BlockHeight) - { - int WeightIndices = 0; - int[][] Unquantized = new int[2][]; - Unquantized[0] = new int[144]; - Unquantized[1] = new int[144]; - - for (int i = 0; i < Weights.Count; i++) - { - Unquantized[0][WeightIndices] = UnquantizeTexelWeight(Weights[i]); - - if (TexelParams.DualPlane) - { - i++; - Unquantized[1][WeightIndices] = UnquantizeTexelWeight(Weights[i]); - - if (i == Weights.Count) - { - break; - } - } - - if (++WeightIndices >= (TexelParams.Width * TexelParams.Height)) break; - } - - // Do infill if necessary (Section C.2.18) ... - int Ds = (1024 + (BlockWidth / 2)) / (BlockWidth - 1); - int Dt = (1024 + (BlockHeight / 2)) / (BlockHeight - 1); - - int PlaneScale = TexelParams.DualPlane ? 2 : 1; - - for (int Plane = 0; Plane < PlaneScale; Plane++) - { - for (int t = 0; t < BlockHeight; t++) - { - for (int s = 0; s < BlockWidth; s++) - { - int cs = Ds * s; - int ct = Dt * t; - - int gs = (cs * (TexelParams.Width - 1) + 32) >> 6; - int gt = (ct * (TexelParams.Height - 1) + 32) >> 6; - - int js = gs >> 4; - int fs = gs & 0xF; - - int jt = gt >> 4; - int ft = gt & 0x0F; - - int w11 = (fs * ft + 8) >> 4; - int w10 = ft - w11; - int w01 = fs - w11; - int w00 = 16 - fs - ft + w11; - - int v0 = js + jt * TexelParams.Width; - - int p00 = 0; - int p01 = 0; - int p10 = 0; - int p11 = 0; - - if (v0 < (TexelParams.Width * TexelParams.Height)) - { - p00 = Unquantized[Plane][v0]; - } - - if (v0 + 1 < (TexelParams.Width * TexelParams.Height)) - { - p01 = Unquantized[Plane][v0 + 1]; - } - - if (v0 + TexelParams.Width < (TexelParams.Width * TexelParams.Height)) - { - p10 = Unquantized[Plane][v0 + TexelParams.Width]; - } - - if (v0 + TexelParams.Width + 1 < (TexelParams.Width * TexelParams.Height)) - { - p11 = Unquantized[Plane][v0 + TexelParams.Width + 1]; - } - - OutputBuffer[Plane][t * BlockWidth + s] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4; - } - } - } - } - - static int UnquantizeTexelWeight(IntegerEncoded IntEncoded) - { - int BitValue = IntEncoded.BitValue; - int BitLength = IntEncoded.NumberBits; - - int A = BitArrayStream.Replicate(BitValue & 1, 1, 7); - int B = 0, C = 0, D = 0; - - int Result = 0; - - switch (IntEncoded.GetEncoding()) - { - case IntegerEncoded.EIntegerEncoding.JustBits: - Result = BitArrayStream.Replicate(BitValue, BitLength, 6); - break; - - case IntegerEncoded.EIntegerEncoding.Trit: - { - D = IntEncoded.TritValue; - Debug.Assert(D < 3); - - switch (BitLength) - { - case 0: - { - int[] Results = { 0, 32, 63 }; - Result = Results[D]; - - break; - } - - case 1: - { - C = 50; - break; - } - - case 2: - { - C = 23; - int b = (BitValue >> 1) & 1; - B = (b << 6) | (b << 2) | b; - - break; - } - - case 3: - { - C = 11; - int cb = (BitValue >> 1) & 3; - B = (cb << 5) | cb; - - break; - } - - default: - throw new ASTCDecoderException("Invalid trit encoding for texel weight"); - } - - break; - } - - case IntegerEncoded.EIntegerEncoding.Quint: - { - D = IntEncoded.QuintValue; - Debug.Assert(D < 5); - - switch (BitLength) - { - case 0: - { - int[] Results = { 0, 16, 32, 47, 63 }; - Result = Results[D]; - - break; - } - - case 1: - { - C = 28; - - break; - } - - case 2: - { - C = 13; - int b = (BitValue >> 1) & 1; - B = (b << 6) | (b << 1); - - break; - } - - default: - throw new ASTCDecoderException("Invalid quint encoding for texel weight"); - } - - break; - } - } - - if (IntEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits && BitLength > 0) - { - // Decode the value... - Result = D * C + B; - Result ^= A; - Result = (A & 0x20) | (Result >> 2); - } - - Debug.Assert(Result < 64); - - // Change from [0,63] to [0,64] - if (Result > 32) - { - Result += 1; - } - - return Result; - } - - static byte ReverseByte(byte b) - { - // Taken from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits - return (byte)((((b) * 0x80200802L) & 0x0884422110L) * 0x0101010101L >> 32); - } - - static uint[] ReadUintColorValues(int Number, int[] ColorValues, ref int ColorValuesPosition) - { - uint[] Ret = new uint[Number]; - - for (int i = 0; i < Number; i++) - { - Ret[i] = (uint)ColorValues[ColorValuesPosition++]; - } - - return Ret; - } - - static int[] ReadIntColorValues(int Number, int[] ColorValues, ref int ColorValuesPosition) - { - int[] Ret = new int[Number]; - - for (int i = 0; i < Number; i++) - { - Ret[i] = ColorValues[ColorValuesPosition++]; - } - - return Ret; - } - - static void ComputeEndpoints( - ASTCPixel[] EndPoints, - int[] ColorValues, - uint ColorEndpointMode, - ref int ColorValuesPosition) - { - switch (ColorEndpointMode) - { - case 0: - { - uint[] Val = ReadUintColorValues(2, ColorValues, ref ColorValuesPosition); - - EndPoints[0] = new ASTCPixel(0xFF, (short)Val[0], (short)Val[0], (short)Val[0]); - EndPoints[1] = new ASTCPixel(0xFF, (short)Val[1], (short)Val[1], (short)Val[1]); - - break; - } - - - case 1: - { - uint[] Val = ReadUintColorValues(2, ColorValues, ref ColorValuesPosition); - int L0 = (int)((Val[0] >> 2) | (Val[1] & 0xC0)); - int L1 = (int)Math.Max(L0 + (Val[1] & 0x3F), 0xFFU); - - EndPoints[0] = new ASTCPixel(0xFF, (short)L0, (short)L0, (short)L0); - EndPoints[1] = new ASTCPixel(0xFF, (short)L1, (short)L1, (short)L1); - - break; - } - - case 4: - { - uint[] Val = ReadUintColorValues(4, ColorValues, ref ColorValuesPosition); - - EndPoints[0] = new ASTCPixel((short)Val[2], (short)Val[0], (short)Val[0], (short)Val[0]); - EndPoints[1] = new ASTCPixel((short)Val[3], (short)Val[1], (short)Val[1], (short)Val[1]); - - break; - } - - case 5: - { - int[] Val = ReadIntColorValues(4, ColorValues, ref ColorValuesPosition); - - BitArrayStream.BitTransferSigned(ref Val[1], ref Val[0]); - BitArrayStream.BitTransferSigned(ref Val[3], ref Val[2]); - - EndPoints[0] = new ASTCPixel((short)Val[2], (short)Val[0], (short)Val[0], (short)Val[0]); - EndPoints[1] = new ASTCPixel((short)(Val[2] + Val[3]), (short)(Val[0] + Val[1]), (short)(Val[0] + Val[1]), (short)(Val[0] + Val[1])); - - EndPoints[0].ClampByte(); - EndPoints[1].ClampByte(); - - break; - } - - case 6: - { - uint[] Val = ReadUintColorValues(4, ColorValues, ref ColorValuesPosition); - - EndPoints[0] = new ASTCPixel(0xFF, (short)(Val[0] * Val[3] >> 8), (short)(Val[1] * Val[3] >> 8), (short)(Val[2] * Val[3] >> 8)); - EndPoints[1] = new ASTCPixel(0xFF, (short)Val[0], (short)Val[1], (short)Val[2]); - - break; - } - - case 8: - { - uint[] Val = ReadUintColorValues(6, ColorValues, ref ColorValuesPosition); - - if (Val[1] + Val[3] + Val[5] >= Val[0] + Val[2] + Val[4]) - { - EndPoints[0] = new ASTCPixel(0xFF, (short)Val[0], (short)Val[2], (short)Val[4]); - EndPoints[1] = new ASTCPixel(0xFF, (short)Val[1], (short)Val[3], (short)Val[5]); - } - else - { - EndPoints[0] = ASTCPixel.BlueContract(0xFF, (short)Val[1], (short)Val[3], (short)Val[5]); - EndPoints[1] = ASTCPixel.BlueContract(0xFF, (short)Val[0], (short)Val[2], (short)Val[4]); - } - - break; - } - - case 9: - { - int[] Val = ReadIntColorValues(6, ColorValues, ref ColorValuesPosition); - - BitArrayStream.BitTransferSigned(ref Val[1], ref Val[0]); - BitArrayStream.BitTransferSigned(ref Val[3], ref Val[2]); - BitArrayStream.BitTransferSigned(ref Val[5], ref Val[4]); - - if (Val[1] + Val[3] + Val[5] >= 0) - { - EndPoints[0] = new ASTCPixel(0xFF, (short)Val[0], (short)Val[2], (short)Val[4]); - EndPoints[1] = new ASTCPixel(0xFF, (short)(Val[0] + Val[1]), (short)(Val[2] + Val[3]), (short)(Val[4] + Val[5])); - } - else - { - EndPoints[0] = ASTCPixel.BlueContract(0xFF, Val[0] + Val[1], Val[2] + Val[3], Val[4] + Val[5]); - EndPoints[1] = ASTCPixel.BlueContract(0xFF, Val[0], Val[2], Val[4]); - } - - EndPoints[0].ClampByte(); - EndPoints[1].ClampByte(); - - break; - } - - case 10: - { - uint[] Val = ReadUintColorValues(6, ColorValues, ref ColorValuesPosition); - - EndPoints[0] = new ASTCPixel((short)Val[4], (short)(Val[0] * Val[3] >> 8), (short)(Val[1] * Val[3] >> 8), (short)(Val[2] * Val[3] >> 8)); - EndPoints[1] = new ASTCPixel((short)Val[5], (short)Val[0], (short)Val[1], (short)Val[2]); - - break; - } - - case 12: - { - uint[] Val = ReadUintColorValues(8, ColorValues, ref ColorValuesPosition); - - if (Val[1] + Val[3] + Val[5] >= Val[0] + Val[2] + Val[4]) - { - EndPoints[0] = new ASTCPixel((short)Val[6], (short)Val[0], (short)Val[2], (short)Val[4]); - EndPoints[1] = new ASTCPixel((short)Val[7], (short)Val[1], (short)Val[3], (short)Val[5]); - } - else - { - EndPoints[0] = ASTCPixel.BlueContract((short)Val[7], (short)Val[1], (short)Val[3], (short)Val[5]); - EndPoints[1] = ASTCPixel.BlueContract((short)Val[6], (short)Val[0], (short)Val[2], (short)Val[4]); - } - - break; - } - - case 13: - { - int[] Val = ReadIntColorValues(8, ColorValues, ref ColorValuesPosition); - - BitArrayStream.BitTransferSigned(ref Val[1], ref Val[0]); - BitArrayStream.BitTransferSigned(ref Val[3], ref Val[2]); - BitArrayStream.BitTransferSigned(ref Val[5], ref Val[4]); - BitArrayStream.BitTransferSigned(ref Val[7], ref Val[6]); - - if (Val[1] + Val[3] + Val[5] >= 0) - { - EndPoints[0] = new ASTCPixel((short)Val[6], (short)Val[0], (short)Val[2], (short)Val[4]); - EndPoints[1] = new ASTCPixel((short)(Val[7] + Val[6]), (short)(Val[0] + Val[1]), (short)(Val[2] + Val[3]), (short)(Val[4] + Val[5])); - } - else - { - EndPoints[0] = ASTCPixel.BlueContract(Val[6] + Val[7], Val[0] + Val[1], Val[2] + Val[3], Val[4] + Val[5]); - EndPoints[1] = ASTCPixel.BlueContract(Val[6], Val[0], Val[2], Val[4]); - } - - EndPoints[0].ClampByte(); - EndPoints[1].ClampByte(); - - break; - } - - default: - throw new ASTCDecoderException("Unsupported color endpoint mode (is it HDR?)"); - } - } - - static void DecodeColorValues( - int[] OutputValues, - byte[] InputData, - uint[] Modes, - int NumberPartitions, - int NumberBitsForColorData) - { - // First figure out how many color values we have - int NumberValues = 0; - - for (int i = 0; i < NumberPartitions; i++) - { - NumberValues += (int)((Modes[i] >> 2) + 1) << 1; - } - - // Then based on the number of values and the remaining number of bits, - // figure out the max value for each of them... - int Range = 256; - - while (--Range > 0) - { - IntegerEncoded IntEncoded = IntegerEncoded.CreateEncoding(Range); - int BitLength = IntEncoded.GetBitLength(NumberValues); - - if (BitLength <= NumberBitsForColorData) - { - // Find the smallest possible range that matches the given encoding - while (--Range > 0) - { - IntegerEncoded NewIntEncoded = IntegerEncoded.CreateEncoding(Range); - if (!NewIntEncoded.MatchesEncoding(IntEncoded)) - { - break; - } - } - - // Return to last matching range. - Range++; - break; - } - } - - // We now have enough to decode our integer sequence. - List IntegerEncodedSequence = new List(); - BitArrayStream ColorBitStream = new BitArrayStream(new BitArray(InputData)); - - IntegerEncoded.DecodeIntegerSequence(IntegerEncodedSequence, ColorBitStream, Range, NumberValues); - - // Once we have the decoded values, we need to dequantize them to the 0-255 range - // This procedure is outlined in ASTC spec C.2.13 - int OutputIndices = 0; - - foreach (IntegerEncoded IntEncoded in IntegerEncodedSequence) - { - int BitLength = IntEncoded.NumberBits; - int BitValue = IntEncoded.BitValue; - - Debug.Assert(BitLength >= 1); - - int A = 0, B = 0, C = 0, D = 0; - // A is just the lsb replicated 9 times. - A = BitArrayStream.Replicate(BitValue & 1, 1, 9); - - switch (IntEncoded.GetEncoding()) - { - case IntegerEncoded.EIntegerEncoding.JustBits: - { - OutputValues[OutputIndices++] = BitArrayStream.Replicate(BitValue, BitLength, 8); - - break; - } - - case IntegerEncoded.EIntegerEncoding.Trit: - { - D = IntEncoded.TritValue; - - switch (BitLength) - { - case 1: - { - C = 204; - - break; - } - - case 2: - { - C = 93; - // B = b000b0bb0 - int b = (BitValue >> 1) & 1; - B = (b << 8) | (b << 4) | (b << 2) | (b << 1); - - break; - } - - case 3: - { - C = 44; - // B = cb000cbcb - int cb = (BitValue >> 1) & 3; - B = (cb << 7) | (cb << 2) | cb; - - break; - } - - - case 4: - { - C = 22; - // B = dcb000dcb - int dcb = (BitValue >> 1) & 7; - B = (dcb << 6) | dcb; - - break; - } - - case 5: - { - C = 11; - // B = edcb000ed - int edcb = (BitValue >> 1) & 0xF; - B = (edcb << 5) | (edcb >> 2); - - break; - } - - case 6: - { - C = 5; - // B = fedcb000f - int fedcb = (BitValue >> 1) & 0x1F; - B = (fedcb << 4) | (fedcb >> 4); - - break; - } - - default: - throw new ASTCDecoderException("Unsupported trit encoding for color values!"); - } - - break; - } - - case IntegerEncoded.EIntegerEncoding.Quint: - { - D = IntEncoded.QuintValue; - - switch (BitLength) - { - case 1: - { - C = 113; - - break; - } - - case 2: - { - C = 54; - // B = b0000bb00 - int b = (BitValue >> 1) & 1; - B = (b << 8) | (b << 3) | (b << 2); - - break; - } - - case 3: - { - C = 26; - // B = cb0000cbc - int cb = (BitValue >> 1) & 3; - B = (cb << 7) | (cb << 1) | (cb >> 1); - - break; - } - - case 4: - { - C = 13; - // B = dcb0000dc - int dcb = (BitValue >> 1) & 7; - B = (dcb << 6) | (dcb >> 1); - - break; - } - - case 5: - { - C = 6; - // B = edcb0000e - int edcb = (BitValue >> 1) & 0xF; - B = (edcb << 5) | (edcb >> 3); - - break; - } - - default: - throw new ASTCDecoderException("Unsupported quint encoding for color values!"); - } - break; - } - } - - if (IntEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits) - { - int T = D * C + B; - T ^= A; - T = (A & 0x80) | (T >> 2); - - OutputValues[OutputIndices++] = T; - } - } - - // Make sure that each of our values is in the proper range... - for (int i = 0; i < NumberValues; i++) - { - Debug.Assert(OutputValues[i] <= 255); - } - } - - static void FillVoidExtentLDR(BitArrayStream BitStream, int[] OutputBuffer, int BlockWidth, int BlockHeight) - { - // Don't actually care about the void extent, just read the bits... - for (int i = 0; i < 4; ++i) - { - BitStream.ReadBits(13); - } - - // Decode the RGBA components and renormalize them to the range [0, 255] - ushort R = (ushort)BitStream.ReadBits(16); - ushort G = (ushort)BitStream.ReadBits(16); - ushort B = (ushort)BitStream.ReadBits(16); - ushort A = (ushort)BitStream.ReadBits(16); - - int RGBA = (R >> 8) | (G & 0xFF00) | ((B) & 0xFF00) << 8 | ((A) & 0xFF00) << 16; - - for (int j = 0; j < BlockHeight; j++) - { - for (int i = 0; i < BlockWidth; i++) - { - OutputBuffer[j * BlockWidth + i] = RGBA; - } - } - } - - static TexelWeightParams DecodeBlockInfo(BitArrayStream BitStream) - { - TexelWeightParams TexelParams = new TexelWeightParams(); - - // Read the entire block mode all at once - ushort ModeBits = (ushort)BitStream.ReadBits(11); - - // Does this match the void extent block mode? - if ((ModeBits & 0x01FF) == 0x1FC) - { - if ((ModeBits & 0x200) != 0) - { - TexelParams.VoidExtentHDR = true; - } - else - { - TexelParams.VoidExtentLDR = true; - } - - // Next two bits must be one. - if ((ModeBits & 0x400) == 0 || BitStream.ReadBits(1) == 0) - { - TexelParams.Error = true; - } - - return TexelParams; - } - - // First check if the last four bits are zero - if ((ModeBits & 0xF) == 0) - { - TexelParams.Error = true; - return TexelParams; - } - - // If the last two bits are zero, then if bits - // [6-8] are all ones, this is also reserved. - if ((ModeBits & 0x3) == 0 && (ModeBits & 0x1C0) == 0x1C0) - { - TexelParams.Error = true; - - return TexelParams; - } - - // Otherwise, there is no error... Figure out the layout - // of the block mode. Layout is determined by a number - // between 0 and 9 corresponding to table C.2.8 of the - // ASTC spec. - int Layout = 0; - - if ((ModeBits & 0x1) != 0 || (ModeBits & 0x2) != 0) - { - // layout is in [0-4] - if ((ModeBits & 0x8) != 0) - { - // layout is in [2-4] - if ((ModeBits & 0x4) != 0) - { - // layout is in [3-4] - if ((ModeBits & 0x100) != 0) - { - Layout = 4; - } - else - { - Layout = 3; - } - } - else - { - Layout = 2; - } - } - else - { - // layout is in [0-1] - if ((ModeBits & 0x4) != 0) - { - Layout = 1; - } - else - { - Layout = 0; - } - } - } - else - { - // layout is in [5-9] - if ((ModeBits & 0x100) != 0) - { - // layout is in [7-9] - if ((ModeBits & 0x80) != 0) - { - // layout is in [7-8] - Debug.Assert((ModeBits & 0x40) == 0); - - if ((ModeBits & 0x20) != 0) - { - Layout = 8; - } - else - { - Layout = 7; - } - } - else - { - Layout = 9; - } - } - else - { - // layout is in [5-6] - if ((ModeBits & 0x80) != 0) - { - Layout = 6; - } - else - { - Layout = 5; - } - } - } - - Debug.Assert(Layout < 10); - - // Determine R - int R = (ModeBits >> 4) & 1; - if (Layout < 5) - { - R |= (ModeBits & 0x3) << 1; - } - else - { - R |= (ModeBits & 0xC) >> 1; - } - - Debug.Assert(2 <= R && R <= 7); - - // Determine width & height - switch (Layout) - { - case 0: - { - int A = (ModeBits >> 5) & 0x3; - int B = (ModeBits >> 7) & 0x3; - - TexelParams.Width = B + 4; - TexelParams.Height = A + 2; - - break; - } - - case 1: - { - int A = (ModeBits >> 5) & 0x3; - int B = (ModeBits >> 7) & 0x3; - - TexelParams.Width = B + 8; - TexelParams.Height = A + 2; - - break; - } - - case 2: - { - int A = (ModeBits >> 5) & 0x3; - int B = (ModeBits >> 7) & 0x3; - - TexelParams.Width = A + 2; - TexelParams.Height = B + 8; - - break; - } - - case 3: - { - int A = (ModeBits >> 5) & 0x3; - int B = (ModeBits >> 7) & 0x1; - - TexelParams.Width = A + 2; - TexelParams.Height = B + 6; - - break; - } - - case 4: - { - int A = (ModeBits >> 5) & 0x3; - int B = (ModeBits >> 7) & 0x1; - - TexelParams.Width = B + 2; - TexelParams.Height = A + 2; - - break; - } - - case 5: - { - int A = (ModeBits >> 5) & 0x3; - - TexelParams.Width = 12; - TexelParams.Height = A + 2; - - break; - } - - case 6: - { - int A = (ModeBits >> 5) & 0x3; - - TexelParams.Width = A + 2; - TexelParams.Height = 12; - - break; - } - - case 7: - { - TexelParams.Width = 6; - TexelParams.Height = 10; - - break; - } - - case 8: - { - TexelParams.Width = 10; - TexelParams.Height = 6; - break; - } - - case 9: - { - int A = (ModeBits >> 5) & 0x3; - int B = (ModeBits >> 9) & 0x3; - - TexelParams.Width = A + 6; - TexelParams.Height = B + 6; - - break; - } - - default: - //Don't know this layout... - TexelParams.Error = true; - break; - } - - // Determine whether or not we're using dual planes - // and/or high precision layouts. - bool D = ((Layout != 9) && ((ModeBits & 0x400) != 0)); - bool H = (Layout != 9) && ((ModeBits & 0x200) != 0); - - if (H) - { - int[] MaxWeights = { 9, 11, 15, 19, 23, 31 }; - TexelParams.MaxWeight = MaxWeights[R - 2]; - } - else - { - int[] MaxWeights = { 1, 2, 3, 4, 5, 7 }; - TexelParams.MaxWeight = MaxWeights[R - 2]; - } - - TexelParams.DualPlane = D; - - return TexelParams; - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/ASTCPixel.cs b/Ryujinx.Graphics/Graphics3d/Texture/ASTCPixel.cs deleted file mode 100644 index c43eaf93..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/ASTCPixel.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; -using System.Diagnostics; - -namespace Ryujinx.Graphics.Texture -{ - class ASTCPixel - { - public short R { get; set; } - public short G { get; set; } - public short B { get; set; } - public short A { get; set; } - - byte[] BitDepth = new byte[4]; - - public ASTCPixel(short _A, short _R, short _G, short _B) - { - A = _A; - R = _R; - G = _G; - B = _B; - - for (int i = 0; i < 4; i++) - BitDepth[i] = 8; - } - - public void ClampByte() - { - R = Math.Min(Math.Max(R, (short)0), (short)255); - G = Math.Min(Math.Max(G, (short)0), (short)255); - B = Math.Min(Math.Max(B, (short)0), (short)255); - A = Math.Min(Math.Max(A, (short)0), (short)255); - } - - public short GetComponent(int Index) - { - switch(Index) - { - case 0: return A; - case 1: return R; - case 2: return G; - case 3: return B; - } - - return 0; - } - - public void SetComponent(int Index, int Value) - { - switch (Index) - { - case 0: - A = (short)Value; - break; - case 1: - R = (short)Value; - break; - case 2: - G = (short)Value; - break; - case 3: - B = (short)Value; - break; - } - } - - public void ChangeBitDepth(byte[] Depth) - { - for(int i = 0; i< 4; i++) - { - int Value = ChangeBitDepth(GetComponent(i), BitDepth[i], Depth[i]); - - SetComponent(i, Value); - BitDepth[i] = Depth[i]; - } - } - - short ChangeBitDepth(short Value, byte OldDepth, byte NewDepth) - { - Debug.Assert(NewDepth <= 8); - Debug.Assert(OldDepth <= 8); - - if (OldDepth == NewDepth) - { - // Do nothing - return Value; - } - else if (OldDepth == 0 && NewDepth != 0) - { - return (short)((1 << NewDepth) - 1); - } - else if (NewDepth > OldDepth) - { - return (short)BitArrayStream.Replicate(Value, OldDepth, NewDepth); - } - else - { - // oldDepth > newDepth - if (NewDepth == 0) - { - return 0xFF; - } - else - { - byte BitsWasted = (byte)(OldDepth - NewDepth); - short TempValue = Value; - - TempValue = (short)((TempValue + (1 << (BitsWasted - 1))) >> BitsWasted); - TempValue = Math.Min(Math.Max((short)0, TempValue), (short)((1 << NewDepth) - 1)); - - return (byte)(TempValue); - } - } - } - - public int Pack() - { - ASTCPixel NewPixel = new ASTCPixel(A, R, G, B); - byte[] eightBitDepth = { 8, 8, 8, 8 }; - - NewPixel.ChangeBitDepth(eightBitDepth); - - return (byte)NewPixel.A << 24 | - (byte)NewPixel.B << 16 | - (byte)NewPixel.G << 8 | - (byte)NewPixel.R << 0; - } - - // Adds more precision to the blue channel as described - // in C.2.14 - public static ASTCPixel BlueContract(int a, int r, int g, int b) - { - return new ASTCPixel((short)(a), - (short)((r + b) >> 1), - (short)((g + b) >> 1), - (short)(b)); - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs b/Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs new file mode 100644 index 00000000..99b166f3 --- /dev/null +++ b/Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs @@ -0,0 +1,1385 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; + +namespace Ryujinx.Graphics.Texture +{ + public class AstcDecoderException : Exception + { + public AstcDecoderException(string exMsg) : base(exMsg) { } + } + + //https://github.com/GammaUNC/FasTC/blob/master/ASTCEncoder/src/Decompressor.cpp + public static class AstcDecoder + { + struct TexelWeightParams + { + public int Width; + public int Height; + public bool DualPlane; + public int MaxWeight; + public bool Error; + public bool VoidExtentLdr; + public bool VoidExtentHdr; + + public int GetPackedBitSize() + { + // How many indices do we have? + int indices = Height * Width; + + if (DualPlane) + { + indices *= 2; + } + + IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(MaxWeight); + + return intEncoded.GetBitLength(indices); + } + + public int GetNumWeightValues() + { + int ret = Width * Height; + + if (DualPlane) + { + ret *= 2; + } + + return ret; + } + } + + public static byte[] DecodeToRgba8888( + byte[] inputBuffer, + int blockX, + int blockY, + int blockZ, + int x, + int y, + int z) + { + using (MemoryStream inputStream = new MemoryStream(inputBuffer)) + { + BinaryReader binReader = new BinaryReader(inputStream); + + if (blockX > 12 || blockY > 12) + { + throw new AstcDecoderException("Block size unsupported!"); + } + + if (blockZ != 1 || z != 1) + { + // TODO: Support 3D textures? + throw new AstcDecoderException("3D compressed textures unsupported!"); + } + + using (MemoryStream outputStream = new MemoryStream()) + { + int blockIndex = 0; + + for (int j = 0; j < y; j += blockY) + { + for (int i = 0; i < x; i += blockX) + { + int[] decompressedData = new int[144]; + + DecompressBlock(binReader.ReadBytes(0x10), decompressedData, blockX, blockY); + + int decompressedWidth = Math.Min(blockX, x - i); + int decompressedHeight = Math.Min(blockY, y - j); + int baseOffsets = (j * x + i) * 4; + + for (int jj = 0; jj < decompressedHeight; jj++) + { + outputStream.Seek(baseOffsets + jj * x * 4, SeekOrigin.Begin); + + byte[] outputBuffer = new byte[decompressedData.Length * sizeof(int)]; + Buffer.BlockCopy(decompressedData, 0, outputBuffer, 0, outputBuffer.Length); + + outputStream.Write(outputBuffer, jj * blockX * 4, decompressedWidth * 4); + } + + blockIndex++; + } + } + + return outputStream.ToArray(); + } + } + } + + public static bool DecompressBlock( + byte[] inputBuffer, + int[] outputBuffer, + int blockWidth, + int blockHeight) + { + BitArrayStream bitStream = new BitArrayStream(new BitArray(inputBuffer)); + TexelWeightParams texelParams = DecodeBlockInfo(bitStream); + + if (texelParams.Error) + { + throw new AstcDecoderException("Invalid block mode"); + } + + if (texelParams.VoidExtentLdr) + { + FillVoidExtentLdr(bitStream, outputBuffer, blockWidth, blockHeight); + + return true; + } + + if (texelParams.VoidExtentHdr) + { + throw new AstcDecoderException("HDR void extent blocks are unsupported!"); + } + + if (texelParams.Width > blockWidth) + { + throw new AstcDecoderException("Texel weight grid width should be smaller than block width"); + } + + if (texelParams.Height > blockHeight) + { + throw new AstcDecoderException("Texel weight grid height should be smaller than block height"); + } + + // Read num partitions + int numberPartitions = bitStream.ReadBits(2) + 1; + Debug.Assert(numberPartitions <= 4); + + if (numberPartitions == 4 && texelParams.DualPlane) + { + throw new AstcDecoderException("Dual plane mode is incompatible with four partition blocks"); + } + + // Based on the number of partitions, read the color endpoint mode for + // each partition. + + // Determine partitions, partition index, and color endpoint modes + int planeIndices = -1; + int partitionIndex; + uint[] colorEndpointMode = { 0, 0, 0, 0 }; + + BitArrayStream colorEndpointStream = new BitArrayStream(new BitArray(16 * 8)); + + // Read extra config data... + uint baseColorEndpointMode = 0; + + if (numberPartitions == 1) + { + colorEndpointMode[0] = (uint)bitStream.ReadBits(4); + partitionIndex = 0; + } + else + { + partitionIndex = bitStream.ReadBits(10); + baseColorEndpointMode = (uint)bitStream.ReadBits(6); + } + + uint baseMode = (baseColorEndpointMode & 3); + + // Remaining bits are color endpoint data... + int numberWeightBits = texelParams.GetPackedBitSize(); + int remainingBits = 128 - numberWeightBits - bitStream.Position; + + // Consider extra bits prior to texel data... + uint extraColorEndpointModeBits = 0; + + if (baseMode != 0) + { + switch (numberPartitions) + { + case 2: extraColorEndpointModeBits += 2; break; + case 3: extraColorEndpointModeBits += 5; break; + case 4: extraColorEndpointModeBits += 8; break; + default: Debug.Assert(false); break; + } + } + + remainingBits -= (int)extraColorEndpointModeBits; + + // Do we have a dual plane situation? + int planeSelectorBits = 0; + + if (texelParams.DualPlane) + { + planeSelectorBits = 2; + } + + remainingBits -= planeSelectorBits; + + // Read color data... + int colorDataBits = remainingBits; + + while (remainingBits > 0) + { + int numberBits = Math.Min(remainingBits, 8); + int bits = bitStream.ReadBits(numberBits); + colorEndpointStream.WriteBits(bits, numberBits); + remainingBits -= 8; + } + + // Read the plane selection bits + planeIndices = bitStream.ReadBits(planeSelectorBits); + + // Read the rest of the CEM + if (baseMode != 0) + { + uint extraColorEndpointMode = (uint)bitStream.ReadBits((int)extraColorEndpointModeBits); + uint tempColorEndpointMode = (extraColorEndpointMode << 6) | baseColorEndpointMode; + tempColorEndpointMode >>= 2; + + bool[] c = new bool[4]; + + for (int i = 0; i < numberPartitions; i++) + { + c[i] = (tempColorEndpointMode & 1) != 0; + tempColorEndpointMode >>= 1; + } + + byte[] m = new byte[4]; + + for (int i = 0; i < numberPartitions; i++) + { + m[i] = (byte)(tempColorEndpointMode & 3); + tempColorEndpointMode >>= 2; + Debug.Assert(m[i] <= 3); + } + + for (int i = 0; i < numberPartitions; i++) + { + colorEndpointMode[i] = baseMode; + if (!(c[i])) colorEndpointMode[i] -= 1; + colorEndpointMode[i] <<= 2; + colorEndpointMode[i] |= m[i]; + } + } + else if (numberPartitions > 1) + { + uint tempColorEndpointMode = baseColorEndpointMode >> 2; + + for (uint i = 0; i < numberPartitions; i++) + { + colorEndpointMode[i] = tempColorEndpointMode; + } + } + + // Make sure everything up till here is sane. + for (int i = 0; i < numberPartitions; i++) + { + Debug.Assert(colorEndpointMode[i] < 16); + } + Debug.Assert(bitStream.Position + texelParams.GetPackedBitSize() == 128); + + // Decode both color data and texel weight data + int[] colorValues = new int[32]; // Four values * two endpoints * four maximum partitions + DecodeColorValues(colorValues, colorEndpointStream.ToByteArray(), colorEndpointMode, numberPartitions, colorDataBits); + + AstcPixel[][] endPoints = new AstcPixel[4][]; + endPoints[0] = new AstcPixel[2]; + endPoints[1] = new AstcPixel[2]; + endPoints[2] = new AstcPixel[2]; + endPoints[3] = new AstcPixel[2]; + + int colorValuesPosition = 0; + + for (int i = 0; i < numberPartitions; i++) + { + ComputeEndpoints(endPoints[i], colorValues, colorEndpointMode[i], ref colorValuesPosition); + } + + // Read the texel weight data. + byte[] texelWeightData = (byte[])inputBuffer.Clone(); + + // Reverse everything + for (int i = 0; i < 8; i++) + { + byte a = ReverseByte(texelWeightData[i]); + byte b = ReverseByte(texelWeightData[15 - i]); + + texelWeightData[i] = b; + texelWeightData[15 - i] = a; + } + + // Make sure that higher non-texel bits are set to zero + int clearByteStart = (texelParams.GetPackedBitSize() >> 3) + 1; + texelWeightData[clearByteStart - 1] &= (byte)((1 << (texelParams.GetPackedBitSize() % 8)) - 1); + + int cLen = 16 - clearByteStart; + for (int i = clearByteStart; i < clearByteStart + cLen; i++) texelWeightData[i] = 0; + + List texelWeightValues = new List(); + BitArrayStream weightBitStream = new BitArrayStream(new BitArray(texelWeightData)); + + IntegerEncoded.DecodeIntegerSequence(texelWeightValues, weightBitStream, texelParams.MaxWeight, texelParams.GetNumWeightValues()); + + // Blocks can be at most 12x12, so we can have as many as 144 weights + int[][] weights = new int[2][]; + weights[0] = new int[144]; + weights[1] = new int[144]; + + UnquantizeTexelWeights(weights, texelWeightValues, texelParams, blockWidth, blockHeight); + + // Now that we have endpoints and weights, we can interpolate and generate + // the proper decoding... + for (int j = 0; j < blockHeight; j++) + { + for (int i = 0; i < blockWidth; i++) + { + int partition = Select2dPartition(partitionIndex, i, j, numberPartitions, ((blockHeight * blockWidth) < 32)); + Debug.Assert(partition < numberPartitions); + + AstcPixel pixel = new AstcPixel(0, 0, 0, 0); + for (int component = 0; component < 4; component++) + { + int component0 = endPoints[partition][0].GetComponent(component); + component0 = BitArrayStream.Replicate(component0, 8, 16); + int component1 = endPoints[partition][1].GetComponent(component); + component1 = BitArrayStream.Replicate(component1, 8, 16); + + int plane = 0; + + if (texelParams.DualPlane && (((planeIndices + 1) & 3) == component)) + { + plane = 1; + } + + int weight = weights[plane][j * blockWidth + i]; + int finalComponent = (component0 * (64 - weight) + component1 * weight + 32) / 64; + + if (finalComponent == 65535) + { + pixel.SetComponent(component, 255); + } + else + { + double finalComponentFloat = finalComponent; + pixel.SetComponent(component, (int)(255.0 * (finalComponentFloat / 65536.0) + 0.5)); + } + } + + outputBuffer[j * blockWidth + i] = pixel.Pack(); + } + } + + return true; + } + + private static int Select2dPartition(int seed, int x, int y, int partitionCount, bool isSmallBlock) + { + return SelectPartition(seed, x, y, 0, partitionCount, isSmallBlock); + } + + private static int SelectPartition(int seed, int x, int y, int z, int partitionCount, bool isSmallBlock) + { + if (partitionCount == 1) + { + return 0; + } + + if (isSmallBlock) + { + x <<= 1; + y <<= 1; + z <<= 1; + } + + seed += (partitionCount - 1) * 1024; + + int rightNum = Hash52((uint)seed); + byte seed01 = (byte)(rightNum & 0xF); + byte seed02 = (byte)((rightNum >> 4) & 0xF); + byte seed03 = (byte)((rightNum >> 8) & 0xF); + byte seed04 = (byte)((rightNum >> 12) & 0xF); + byte seed05 = (byte)((rightNum >> 16) & 0xF); + byte seed06 = (byte)((rightNum >> 20) & 0xF); + byte seed07 = (byte)((rightNum >> 24) & 0xF); + byte seed08 = (byte)((rightNum >> 28) & 0xF); + byte seed09 = (byte)((rightNum >> 18) & 0xF); + byte seed10 = (byte)((rightNum >> 22) & 0xF); + byte seed11 = (byte)((rightNum >> 26) & 0xF); + byte seed12 = (byte)(((rightNum >> 30) | (rightNum << 2)) & 0xF); + + seed01 *= seed01; seed02 *= seed02; + seed03 *= seed03; seed04 *= seed04; + seed05 *= seed05; seed06 *= seed06; + seed07 *= seed07; seed08 *= seed08; + seed09 *= seed09; seed10 *= seed10; + seed11 *= seed11; seed12 *= seed12; + + int seedHash1, seedHash2, seedHash3; + + if ((seed & 1) != 0) + { + seedHash1 = (seed & 2) != 0 ? 4 : 5; + seedHash2 = (partitionCount == 3) ? 6 : 5; + } + else + { + seedHash1 = (partitionCount == 3) ? 6 : 5; + seedHash2 = (seed & 2) != 0 ? 4 : 5; + } + + seedHash3 = (seed & 0x10) != 0 ? seedHash1 : seedHash2; + + seed01 >>= seedHash1; seed02 >>= seedHash2; seed03 >>= seedHash1; seed04 >>= seedHash2; + seed05 >>= seedHash1; seed06 >>= seedHash2; seed07 >>= seedHash1; seed08 >>= seedHash2; + seed09 >>= seedHash3; seed10 >>= seedHash3; seed11 >>= seedHash3; seed12 >>= seedHash3; + + int a = seed01 * x + seed02 * y + seed11 * z + (rightNum >> 14); + int b = seed03 * x + seed04 * y + seed12 * z + (rightNum >> 10); + int c = seed05 * x + seed06 * y + seed09 * z + (rightNum >> 6); + int d = seed07 * x + seed08 * y + seed10 * z + (rightNum >> 2); + + a &= 0x3F; b &= 0x3F; c &= 0x3F; d &= 0x3F; + + if (partitionCount < 4) d = 0; + if (partitionCount < 3) c = 0; + + if (a >= b && a >= c && a >= d) return 0; + else if (b >= c && b >= d) return 1; + else if (c >= d) return 2; + return 3; + } + + static int Hash52(uint val) + { + val ^= val >> 15; val -= val << 17; val += val << 7; val += val << 4; + val ^= val >> 5; val += val << 16; val ^= val >> 7; val ^= val >> 3; + val ^= val << 6; val ^= val >> 17; + + return (int)val; + } + + static void UnquantizeTexelWeights( + int[][] outputBuffer, + List weights, + TexelWeightParams texelParams, + int blockWidth, + int blockHeight) + { + int weightIndices = 0; + int[][] unquantized = new int[2][]; + unquantized[0] = new int[144]; + unquantized[1] = new int[144]; + + for (int i = 0; i < weights.Count; i++) + { + unquantized[0][weightIndices] = UnquantizeTexelWeight(weights[i]); + + if (texelParams.DualPlane) + { + i++; + unquantized[1][weightIndices] = UnquantizeTexelWeight(weights[i]); + + if (i == weights.Count) + { + break; + } + } + + if (++weightIndices >= (texelParams.Width * texelParams.Height)) break; + } + + // Do infill if necessary (Section C.2.18) ... + int ds = (1024 + (blockWidth / 2)) / (blockWidth - 1); + int dt = (1024 + (blockHeight / 2)) / (blockHeight - 1); + + int planeScale = texelParams.DualPlane ? 2 : 1; + + for (int plane = 0; plane < planeScale; plane++) + { + for (int t = 0; t < blockHeight; t++) + { + for (int s = 0; s < blockWidth; s++) + { + int cs = ds * s; + int ct = dt * t; + + int gs = (cs * (texelParams.Width - 1) + 32) >> 6; + int gt = (ct * (texelParams.Height - 1) + 32) >> 6; + + int js = gs >> 4; + int fs = gs & 0xF; + + int jt = gt >> 4; + int ft = gt & 0x0F; + + int w11 = (fs * ft + 8) >> 4; + int w10 = ft - w11; + int w01 = fs - w11; + int w00 = 16 - fs - ft + w11; + + int v0 = js + jt * texelParams.Width; + + int p00 = 0; + int p01 = 0; + int p10 = 0; + int p11 = 0; + + if (v0 < (texelParams.Width * texelParams.Height)) + { + p00 = unquantized[plane][v0]; + } + + if (v0 + 1 < (texelParams.Width * texelParams.Height)) + { + p01 = unquantized[plane][v0 + 1]; + } + + if (v0 + texelParams.Width < (texelParams.Width * texelParams.Height)) + { + p10 = unquantized[plane][v0 + texelParams.Width]; + } + + if (v0 + texelParams.Width + 1 < (texelParams.Width * texelParams.Height)) + { + p11 = unquantized[plane][v0 + texelParams.Width + 1]; + } + + outputBuffer[plane][t * blockWidth + s] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4; + } + } + } + } + + static int UnquantizeTexelWeight(IntegerEncoded intEncoded) + { + int bitValue = intEncoded.BitValue; + int bitLength = intEncoded.NumberBits; + + int a = BitArrayStream.Replicate(bitValue & 1, 1, 7); + int b = 0, c = 0, d = 0; + + int result = 0; + + switch (intEncoded.GetEncoding()) + { + case IntegerEncoded.EIntegerEncoding.JustBits: + result = BitArrayStream.Replicate(bitValue, bitLength, 6); + break; + + case IntegerEncoded.EIntegerEncoding.Trit: + { + d = intEncoded.TritValue; + Debug.Assert(d < 3); + + switch (bitLength) + { + case 0: + { + int[] results = { 0, 32, 63 }; + result = results[d]; + + break; + } + + case 1: + { + c = 50; + break; + } + + case 2: + { + c = 23; + int b2 = (bitValue >> 1) & 1; + b = (b2 << 6) | (b2 << 2) | b2; + + break; + } + + case 3: + { + c = 11; + int cb = (bitValue >> 1) & 3; + b = (cb << 5) | cb; + + break; + } + + default: + throw new AstcDecoderException("Invalid trit encoding for texel weight"); + } + + break; + } + + case IntegerEncoded.EIntegerEncoding.Quint: + { + d = intEncoded.QuintValue; + Debug.Assert(d < 5); + + switch (bitLength) + { + case 0: + { + int[] results = { 0, 16, 32, 47, 63 }; + result = results[d]; + + break; + } + + case 1: + { + c = 28; + + break; + } + + case 2: + { + c = 13; + int b2 = (bitValue >> 1) & 1; + b = (b2 << 6) | (b2 << 1); + + break; + } + + default: + throw new AstcDecoderException("Invalid quint encoding for texel weight"); + } + + break; + } + } + + if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits && bitLength > 0) + { + // Decode the value... + result = d * c + b; + result ^= a; + result = (a & 0x20) | (result >> 2); + } + + Debug.Assert(result < 64); + + // Change from [0,63] to [0,64] + if (result > 32) + { + result += 1; + } + + return result; + } + + static byte ReverseByte(byte b) + { + // Taken from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits + return (byte)((((b) * 0x80200802L) & 0x0884422110L) * 0x0101010101L >> 32); + } + + static uint[] ReadUintColorValues(int number, int[] colorValues, ref int colorValuesPosition) + { + uint[] ret = new uint[number]; + + for (int i = 0; i < number; i++) + { + ret[i] = (uint)colorValues[colorValuesPosition++]; + } + + return ret; + } + + static int[] ReadIntColorValues(int number, int[] colorValues, ref int colorValuesPosition) + { + int[] ret = new int[number]; + + for (int i = 0; i < number; i++) + { + ret[i] = colorValues[colorValuesPosition++]; + } + + return ret; + } + + static void ComputeEndpoints( + AstcPixel[] endPoints, + int[] colorValues, + uint colorEndpointMode, + ref int colorValuesPosition) + { + switch (colorEndpointMode) + { + case 0: + { + uint[] val = ReadUintColorValues(2, colorValues, ref colorValuesPosition); + + endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[0], (short)val[0]); + endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[1], (short)val[1]); + + break; + } + + + case 1: + { + uint[] val = ReadUintColorValues(2, colorValues, ref colorValuesPosition); + int l0 = (int)((val[0] >> 2) | (val[1] & 0xC0)); + int l1 = (int)Math.Max(l0 + (val[1] & 0x3F), 0xFFU); + + endPoints[0] = new AstcPixel(0xFF, (short)l0, (short)l0, (short)l0); + endPoints[1] = new AstcPixel(0xFF, (short)l1, (short)l1, (short)l1); + + break; + } + + case 4: + { + uint[] val = ReadUintColorValues(4, colorValues, ref colorValuesPosition); + + endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]); + endPoints[1] = new AstcPixel((short)val[3], (short)val[1], (short)val[1], (short)val[1]); + + break; + } + + case 5: + { + int[] val = ReadIntColorValues(4, colorValues, ref colorValuesPosition); + + BitArrayStream.BitTransferSigned(ref val[1], ref val[0]); + BitArrayStream.BitTransferSigned(ref val[3], ref val[2]); + + endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]); + endPoints[1] = new AstcPixel((short)(val[2] + val[3]), (short)(val[0] + val[1]), (short)(val[0] + val[1]), (short)(val[0] + val[1])); + + endPoints[0].ClampByte(); + endPoints[1].ClampByte(); + + break; + } + + case 6: + { + uint[] val = ReadUintColorValues(4, colorValues, ref colorValuesPosition); + + endPoints[0] = new AstcPixel(0xFF, (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8)); + endPoints[1] = new AstcPixel(0xFF, (short)val[0], (short)val[1], (short)val[2]); + + break; + } + + case 8: + { + uint[] val = ReadUintColorValues(6, colorValues, ref colorValuesPosition); + + if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4]) + { + endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]); + endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[3], (short)val[5]); + } + else + { + endPoints[0] = AstcPixel.BlueContract(0xFF, (short)val[1], (short)val[3], (short)val[5]); + endPoints[1] = AstcPixel.BlueContract(0xFF, (short)val[0], (short)val[2], (short)val[4]); + } + + break; + } + + case 9: + { + int[] val = ReadIntColorValues(6, colorValues, ref colorValuesPosition); + + BitArrayStream.BitTransferSigned(ref val[1], ref val[0]); + BitArrayStream.BitTransferSigned(ref val[3], ref val[2]); + BitArrayStream.BitTransferSigned(ref val[5], ref val[4]); + + if (val[1] + val[3] + val[5] >= 0) + { + endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]); + endPoints[1] = new AstcPixel(0xFF, (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5])); + } + else + { + endPoints[0] = AstcPixel.BlueContract(0xFF, val[0] + val[1], val[2] + val[3], val[4] + val[5]); + endPoints[1] = AstcPixel.BlueContract(0xFF, val[0], val[2], val[4]); + } + + endPoints[0].ClampByte(); + endPoints[1].ClampByte(); + + break; + } + + case 10: + { + uint[] val = ReadUintColorValues(6, colorValues, ref colorValuesPosition); + + endPoints[0] = new AstcPixel((short)val[4], (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8)); + endPoints[1] = new AstcPixel((short)val[5], (short)val[0], (short)val[1], (short)val[2]); + + break; + } + + case 12: + { + uint[] val = ReadUintColorValues(8, colorValues, ref colorValuesPosition); + + if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4]) + { + endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]); + endPoints[1] = new AstcPixel((short)val[7], (short)val[1], (short)val[3], (short)val[5]); + } + else + { + endPoints[0] = AstcPixel.BlueContract((short)val[7], (short)val[1], (short)val[3], (short)val[5]); + endPoints[1] = AstcPixel.BlueContract((short)val[6], (short)val[0], (short)val[2], (short)val[4]); + } + + break; + } + + case 13: + { + int[] val = ReadIntColorValues(8, colorValues, ref colorValuesPosition); + + BitArrayStream.BitTransferSigned(ref val[1], ref val[0]); + BitArrayStream.BitTransferSigned(ref val[3], ref val[2]); + BitArrayStream.BitTransferSigned(ref val[5], ref val[4]); + BitArrayStream.BitTransferSigned(ref val[7], ref val[6]); + + if (val[1] + val[3] + val[5] >= 0) + { + endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]); + endPoints[1] = new AstcPixel((short)(val[7] + val[6]), (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5])); + } + else + { + endPoints[0] = AstcPixel.BlueContract(val[6] + val[7], val[0] + val[1], val[2] + val[3], val[4] + val[5]); + endPoints[1] = AstcPixel.BlueContract(val[6], val[0], val[2], val[4]); + } + + endPoints[0].ClampByte(); + endPoints[1].ClampByte(); + + break; + } + + default: + throw new AstcDecoderException("Unsupported color endpoint mode (is it HDR?)"); + } + } + + static void DecodeColorValues( + int[] outputValues, + byte[] inputData, + uint[] modes, + int numberPartitions, + int numberBitsForColorData) + { + // First figure out how many color values we have + int numberValues = 0; + + for (int i = 0; i < numberPartitions; i++) + { + numberValues += (int)((modes[i] >> 2) + 1) << 1; + } + + // Then based on the number of values and the remaining number of bits, + // figure out the max value for each of them... + int range = 256; + + while (--range > 0) + { + IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(range); + int bitLength = intEncoded.GetBitLength(numberValues); + + if (bitLength <= numberBitsForColorData) + { + // Find the smallest possible range that matches the given encoding + while (--range > 0) + { + IntegerEncoded newIntEncoded = IntegerEncoded.CreateEncoding(range); + if (!newIntEncoded.MatchesEncoding(intEncoded)) + { + break; + } + } + + // Return to last matching range. + range++; + break; + } + } + + // We now have enough to decode our integer sequence. + List integerEncodedSequence = new List(); + BitArrayStream colorBitStream = new BitArrayStream(new BitArray(inputData)); + + IntegerEncoded.DecodeIntegerSequence(integerEncodedSequence, colorBitStream, range, numberValues); + + // Once we have the decoded values, we need to dequantize them to the 0-255 range + // This procedure is outlined in ASTC spec C.2.13 + int outputIndices = 0; + + foreach (IntegerEncoded intEncoded in integerEncodedSequence) + { + int bitLength = intEncoded.NumberBits; + int bitValue = intEncoded.BitValue; + + Debug.Assert(bitLength >= 1); + + int a = 0, b = 0, c = 0, d = 0; + // A is just the lsb replicated 9 times. + a = BitArrayStream.Replicate(bitValue & 1, 1, 9); + + switch (intEncoded.GetEncoding()) + { + case IntegerEncoded.EIntegerEncoding.JustBits: + { + outputValues[outputIndices++] = BitArrayStream.Replicate(bitValue, bitLength, 8); + + break; + } + + case IntegerEncoded.EIntegerEncoding.Trit: + { + d = intEncoded.TritValue; + + switch (bitLength) + { + case 1: + { + c = 204; + + break; + } + + case 2: + { + c = 93; + // B = b000b0bb0 + int b2 = (bitValue >> 1) & 1; + b = (b2 << 8) | (b2 << 4) | (b2 << 2) | (b2 << 1); + + break; + } + + case 3: + { + c = 44; + // B = cb000cbcb + int cb = (bitValue >> 1) & 3; + b = (cb << 7) | (cb << 2) | cb; + + break; + } + + + case 4: + { + c = 22; + // B = dcb000dcb + int dcb = (bitValue >> 1) & 7; + b = (dcb << 6) | dcb; + + break; + } + + case 5: + { + c = 11; + // B = edcb000ed + int edcb = (bitValue >> 1) & 0xF; + b = (edcb << 5) | (edcb >> 2); + + break; + } + + case 6: + { + c = 5; + // B = fedcb000f + int fedcb = (bitValue >> 1) & 0x1F; + b = (fedcb << 4) | (fedcb >> 4); + + break; + } + + default: + throw new AstcDecoderException("Unsupported trit encoding for color values!"); + } + + break; + } + + case IntegerEncoded.EIntegerEncoding.Quint: + { + d = intEncoded.QuintValue; + + switch (bitLength) + { + case 1: + { + c = 113; + + break; + } + + case 2: + { + c = 54; + // B = b0000bb00 + int b2 = (bitValue >> 1) & 1; + b = (b2 << 8) | (b2 << 3) | (b2 << 2); + + break; + } + + case 3: + { + c = 26; + // B = cb0000cbc + int cb = (bitValue >> 1) & 3; + b = (cb << 7) | (cb << 1) | (cb >> 1); + + break; + } + + case 4: + { + c = 13; + // B = dcb0000dc + int dcb = (bitValue >> 1) & 7; + b = (dcb << 6) | (dcb >> 1); + + break; + } + + case 5: + { + c = 6; + // B = edcb0000e + int edcb = (bitValue >> 1) & 0xF; + b = (edcb << 5) | (edcb >> 3); + + break; + } + + default: + throw new AstcDecoderException("Unsupported quint encoding for color values!"); + } + break; + } + } + + if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits) + { + int T = d * c + b; + T ^= a; + T = (a & 0x80) | (T >> 2); + + outputValues[outputIndices++] = T; + } + } + + // Make sure that each of our values is in the proper range... + for (int i = 0; i < numberValues; i++) + { + Debug.Assert(outputValues[i] <= 255); + } + } + + static void FillVoidExtentLdr(BitArrayStream bitStream, int[] outputBuffer, int blockWidth, int blockHeight) + { + // Don't actually care about the void extent, just read the bits... + for (int i = 0; i < 4; ++i) + { + bitStream.ReadBits(13); + } + + // Decode the RGBA components and renormalize them to the range [0, 255] + ushort r = (ushort)bitStream.ReadBits(16); + ushort g = (ushort)bitStream.ReadBits(16); + ushort b = (ushort)bitStream.ReadBits(16); + ushort a = (ushort)bitStream.ReadBits(16); + + int rgba = (r >> 8) | (g & 0xFF00) | ((b) & 0xFF00) << 8 | ((a) & 0xFF00) << 16; + + for (int j = 0; j < blockHeight; j++) + { + for (int i = 0; i < blockWidth; i++) + { + outputBuffer[j * blockWidth + i] = rgba; + } + } + } + + static TexelWeightParams DecodeBlockInfo(BitArrayStream bitStream) + { + TexelWeightParams texelParams = new TexelWeightParams(); + + // Read the entire block mode all at once + ushort modeBits = (ushort)bitStream.ReadBits(11); + + // Does this match the void extent block mode? + if ((modeBits & 0x01FF) == 0x1FC) + { + if ((modeBits & 0x200) != 0) + { + texelParams.VoidExtentHdr = true; + } + else + { + texelParams.VoidExtentLdr = true; + } + + // Next two bits must be one. + if ((modeBits & 0x400) == 0 || bitStream.ReadBits(1) == 0) + { + texelParams.Error = true; + } + + return texelParams; + } + + // First check if the last four bits are zero + if ((modeBits & 0xF) == 0) + { + texelParams.Error = true; + return texelParams; + } + + // If the last two bits are zero, then if bits + // [6-8] are all ones, this is also reserved. + if ((modeBits & 0x3) == 0 && (modeBits & 0x1C0) == 0x1C0) + { + texelParams.Error = true; + + return texelParams; + } + + // Otherwise, there is no error... Figure out the layout + // of the block mode. Layout is determined by a number + // between 0 and 9 corresponding to table C.2.8 of the + // ASTC spec. + int layout = 0; + + if ((modeBits & 0x1) != 0 || (modeBits & 0x2) != 0) + { + // layout is in [0-4] + if ((modeBits & 0x8) != 0) + { + // layout is in [2-4] + if ((modeBits & 0x4) != 0) + { + // layout is in [3-4] + if ((modeBits & 0x100) != 0) + { + layout = 4; + } + else + { + layout = 3; + } + } + else + { + layout = 2; + } + } + else + { + // layout is in [0-1] + if ((modeBits & 0x4) != 0) + { + layout = 1; + } + else + { + layout = 0; + } + } + } + else + { + // layout is in [5-9] + if ((modeBits & 0x100) != 0) + { + // layout is in [7-9] + if ((modeBits & 0x80) != 0) + { + // layout is in [7-8] + Debug.Assert((modeBits & 0x40) == 0); + + if ((modeBits & 0x20) != 0) + { + layout = 8; + } + else + { + layout = 7; + } + } + else + { + layout = 9; + } + } + else + { + // layout is in [5-6] + if ((modeBits & 0x80) != 0) + { + layout = 6; + } + else + { + layout = 5; + } + } + } + + Debug.Assert(layout < 10); + + // Determine R + int r = (modeBits >> 4) & 1; + if (layout < 5) + { + r |= (modeBits & 0x3) << 1; + } + else + { + r |= (modeBits & 0xC) >> 1; + } + + Debug.Assert(2 <= r && r <= 7); + + // Determine width & height + switch (layout) + { + case 0: + { + int a = (modeBits >> 5) & 0x3; + int b = (modeBits >> 7) & 0x3; + + texelParams.Width = b + 4; + texelParams.Height = a + 2; + + break; + } + + case 1: + { + int a = (modeBits >> 5) & 0x3; + int b = (modeBits >> 7) & 0x3; + + texelParams.Width = b + 8; + texelParams.Height = a + 2; + + break; + } + + case 2: + { + int a = (modeBits >> 5) & 0x3; + int b = (modeBits >> 7) & 0x3; + + texelParams.Width = a + 2; + texelParams.Height = b + 8; + + break; + } + + case 3: + { + int a = (modeBits >> 5) & 0x3; + int b = (modeBits >> 7) & 0x1; + + texelParams.Width = a + 2; + texelParams.Height = b + 6; + + break; + } + + case 4: + { + int a = (modeBits >> 5) & 0x3; + int b = (modeBits >> 7) & 0x1; + + texelParams.Width = b + 2; + texelParams.Height = a + 2; + + break; + } + + case 5: + { + int a = (modeBits >> 5) & 0x3; + + texelParams.Width = 12; + texelParams.Height = a + 2; + + break; + } + + case 6: + { + int a = (modeBits >> 5) & 0x3; + + texelParams.Width = a + 2; + texelParams.Height = 12; + + break; + } + + case 7: + { + texelParams.Width = 6; + texelParams.Height = 10; + + break; + } + + case 8: + { + texelParams.Width = 10; + texelParams.Height = 6; + break; + } + + case 9: + { + int a = (modeBits >> 5) & 0x3; + int b = (modeBits >> 9) & 0x3; + + texelParams.Width = a + 6; + texelParams.Height = b + 6; + + break; + } + + default: + //Don't know this layout... + texelParams.Error = true; + break; + } + + // Determine whether or not we're using dual planes + // and/or high precision layouts. + bool d = ((layout != 9) && ((modeBits & 0x400) != 0)); + bool h = (layout != 9) && ((modeBits & 0x200) != 0); + + if (h) + { + int[] maxWeights = { 9, 11, 15, 19, 23, 31 }; + texelParams.MaxWeight = maxWeights[r - 2]; + } + else + { + int[] maxWeights = { 1, 2, 3, 4, 5, 7 }; + texelParams.MaxWeight = maxWeights[r - 2]; + } + + texelParams.DualPlane = d; + + return texelParams; + } + } +} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs b/Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs new file mode 100644 index 00000000..cd30acca --- /dev/null +++ b/Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs @@ -0,0 +1,138 @@ +using System; +using System.Diagnostics; + +namespace Ryujinx.Graphics.Texture +{ + class AstcPixel + { + public short R { get; set; } + public short G { get; set; } + public short B { get; set; } + public short A { get; set; } + + byte[] _bitDepth = new byte[4]; + + public AstcPixel(short a, short r, short g, short b) + { + A = a; + R = r; + G = g; + B = b; + + for (int i = 0; i < 4; i++) + _bitDepth[i] = 8; + } + + public void ClampByte() + { + R = Math.Min(Math.Max(R, (short)0), (short)255); + G = Math.Min(Math.Max(G, (short)0), (short)255); + B = Math.Min(Math.Max(B, (short)0), (short)255); + A = Math.Min(Math.Max(A, (short)0), (short)255); + } + + public short GetComponent(int index) + { + switch(index) + { + case 0: return A; + case 1: return R; + case 2: return G; + case 3: return B; + } + + return 0; + } + + public void SetComponent(int index, int value) + { + switch (index) + { + case 0: + A = (short)value; + break; + case 1: + R = (short)value; + break; + case 2: + G = (short)value; + break; + case 3: + B = (short)value; + break; + } + } + + public void ChangeBitDepth(byte[] depth) + { + for(int i = 0; i< 4; i++) + { + int value = ChangeBitDepth(GetComponent(i), _bitDepth[i], depth[i]); + + SetComponent(i, value); + _bitDepth[i] = depth[i]; + } + } + + short ChangeBitDepth(short value, byte oldDepth, byte newDepth) + { + Debug.Assert(newDepth <= 8); + Debug.Assert(oldDepth <= 8); + + if (oldDepth == newDepth) + { + // Do nothing + return value; + } + else if (oldDepth == 0 && newDepth != 0) + { + return (short)((1 << newDepth) - 1); + } + else if (newDepth > oldDepth) + { + return (short)BitArrayStream.Replicate(value, oldDepth, newDepth); + } + else + { + // oldDepth > newDepth + if (newDepth == 0) + { + return 0xFF; + } + else + { + byte bitsWasted = (byte)(oldDepth - newDepth); + short tempValue = value; + + tempValue = (short)((tempValue + (1 << (bitsWasted - 1))) >> bitsWasted); + tempValue = Math.Min(Math.Max((short)0, tempValue), (short)((1 << newDepth) - 1)); + + return (byte)(tempValue); + } + } + } + + public int Pack() + { + AstcPixel newPixel = new AstcPixel(A, R, G, B); + byte[] eightBitDepth = { 8, 8, 8, 8 }; + + newPixel.ChangeBitDepth(eightBitDepth); + + return (byte)newPixel.A << 24 | + (byte)newPixel.B << 16 | + (byte)newPixel.G << 8 | + (byte)newPixel.R << 0; + } + + // Adds more precision to the blue channel as described + // in C.2.14 + public static AstcPixel BlueContract(int a, int r, int g, int b) + { + return new AstcPixel((short)(a), + (short)((r + b) >> 1), + (short)((g + b) >> 1), + (short)(b)); + } + } +} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs b/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs index 2a8ed091..24069d72 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs @@ -9,103 +9,103 @@ namespace Ryujinx.Graphics.Texture public int Position { get; private set; } - public BitArrayStream(BitArray BitArray) + public BitArrayStream(BitArray bitArray) { - BitsArray = BitArray; + BitsArray = bitArray; Position = 0; } - public short ReadBits(int Length) + public short ReadBits(int length) { - int RetValue = 0; - for (int i = Position; i < Position + Length; i++) + int retValue = 0; + for (int i = Position; i < Position + length; i++) { if (BitsArray[i]) { - RetValue |= 1 << (i - Position); + retValue |= 1 << (i - Position); } } - Position += Length; - return (short)RetValue; + Position += length; + return (short)retValue; } - public int ReadBits(int Start, int End) + public int ReadBits(int start, int end) { - int RetValue = 0; - for (int i = Start; i <= End; i++) + int retValue = 0; + for (int i = start; i <= end; i++) { if (BitsArray[i]) { - RetValue |= 1 << (i - Start); + retValue |= 1 << (i - start); } } - return RetValue; + return retValue; } - public int ReadBit(int Index) + public int ReadBit(int index) { - return Convert.ToInt32(BitsArray[Index]); + return Convert.ToInt32(BitsArray[index]); } - public void WriteBits(int Value, int Length) + public void WriteBits(int value, int length) { - for (int i = Position; i < Position + Length; i++) + for (int i = Position; i < Position + length; i++) { - BitsArray[i] = ((Value >> (i - Position)) & 1) != 0; + BitsArray[i] = ((value >> (i - Position)) & 1) != 0; } - Position += Length; + Position += length; } public byte[] ToByteArray() { - byte[] RetArray = new byte[(BitsArray.Length + 7) / 8]; - BitsArray.CopyTo(RetArray, 0); - return RetArray; + byte[] retArray = new byte[(BitsArray.Length + 7) / 8]; + BitsArray.CopyTo(retArray, 0); + return retArray; } - public static int Replicate(int Value, int NumberBits, int ToBit) + public static int Replicate(int value, int numberBits, int toBit) { - if (NumberBits == 0) return 0; - if (ToBit == 0) return 0; + if (numberBits == 0) return 0; + if (toBit == 0) return 0; - int TempValue = Value & ((1 << NumberBits) - 1); - int RetValue = TempValue; - int ResLength = NumberBits; + int tempValue = value & ((1 << numberBits) - 1); + int retValue = tempValue; + int resLength = numberBits; - while (ResLength < ToBit) + while (resLength < toBit) { - int Comp = 0; - if (NumberBits > ToBit - ResLength) + int comp = 0; + if (numberBits > toBit - resLength) { - int NewShift = ToBit - ResLength; - Comp = NumberBits - NewShift; - NumberBits = NewShift; + int newShift = toBit - resLength; + comp = numberBits - newShift; + numberBits = newShift; } - RetValue <<= NumberBits; - RetValue |= TempValue >> Comp; - ResLength += NumberBits; + retValue <<= numberBits; + retValue |= tempValue >> comp; + resLength += numberBits; } - return RetValue; + return retValue; } - public static int PopCnt(int Number) + public static int PopCnt(int number) { - int Counter; - for (Counter = 0; Number != 0; Counter++) + int counter; + for (counter = 0; number != 0; counter++) { - Number &= Number - 1; + number &= number - 1; } - return Counter; + return counter; } public static void Swap(ref T lhs, ref T rhs) { - T Temp = lhs; + T temp = lhs; lhs = rhs; - rhs = Temp; + rhs = temp; } // Transfers a bit as described in C.2.14 diff --git a/Ryujinx.Graphics/Graphics3d/Texture/BlockLinearSwizzle.cs b/Ryujinx.Graphics/Graphics3d/Texture/BlockLinearSwizzle.cs index 1be06442..682f7d67 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/BlockLinearSwizzle.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/BlockLinearSwizzle.cs @@ -10,98 +10,98 @@ namespace Ryujinx.Graphics.Texture private const int GobSize = GobWidth * GobHeight; - private int TexWidth; - private int TexHeight; - private int TexDepth; - private int TexGobBlockHeight; - private int TexGobBlockDepth; - private int TexBpp; + private int _texWidth; + private int _texHeight; + private int _texDepth; + private int _texGobBlockHeight; + private int _texGobBlockDepth; + private int _texBpp; - private int BhMask; - private int BdMask; + private int _bhMask; + private int _bdMask; - private int BhShift; - private int BdShift; - private int BppShift; + private int _bhShift; + private int _bdShift; + private int _bppShift; - private int XShift; + private int _xShift; - private int RobSize; - private int SliceSize; + private int _robSize; + private int _sliceSize; - private int BaseOffset; + private int _baseOffset; public BlockLinearSwizzle( - int Width, - int Height, - int Depth, - int GobBlockHeight, - int GobBlockDepth, - int Bpp) + int width, + int height, + int depth, + int gobBlockHeight, + int gobBlockDepth, + int bpp) { - TexWidth = Width; - TexHeight = Height; - TexDepth = Depth; - TexGobBlockHeight = GobBlockHeight; - TexGobBlockDepth = GobBlockDepth; - TexBpp = Bpp; + _texWidth = width; + _texHeight = height; + _texDepth = depth; + _texGobBlockHeight = gobBlockHeight; + _texGobBlockDepth = gobBlockDepth; + _texBpp = bpp; - BppShift = BitUtils.CountTrailingZeros32(Bpp); + _bppShift = BitUtils.CountTrailingZeros32(bpp); SetMipLevel(0); } - public void SetMipLevel(int Level) + public void SetMipLevel(int level) { - BaseOffset = GetMipOffset(Level); + _baseOffset = GetMipOffset(level); - int Width = Math.Max(1, TexWidth >> Level); - int Height = Math.Max(1, TexHeight >> Level); - int Depth = Math.Max(1, TexDepth >> Level); + int width = Math.Max(1, _texWidth >> level); + int height = Math.Max(1, _texHeight >> level); + int depth = Math.Max(1, _texDepth >> level); - GobBlockSizes GbSizes = AdjustGobBlockSizes(Height, Depth); + GobBlockSizes gbSizes = AdjustGobBlockSizes(height, depth); - BhMask = GbSizes.Height - 1; - BdMask = GbSizes.Depth - 1; + _bhMask = gbSizes.Height - 1; + _bdMask = gbSizes.Depth - 1; - BhShift = BitUtils.CountTrailingZeros32(GbSizes.Height); - BdShift = BitUtils.CountTrailingZeros32(GbSizes.Depth); + _bhShift = BitUtils.CountTrailingZeros32(gbSizes.Height); + _bdShift = BitUtils.CountTrailingZeros32(gbSizes.Depth); - XShift = BitUtils.CountTrailingZeros32(GobSize * GbSizes.Height * GbSizes.Depth); + _xShift = BitUtils.CountTrailingZeros32(GobSize * gbSizes.Height * gbSizes.Depth); - RobAndSliceSizes GsSizes = GetRobAndSliceSizes(Width, Height, GbSizes); + RobAndSliceSizes gsSizes = GetRobAndSliceSizes(width, height, gbSizes); - RobSize = GsSizes.RobSize; - SliceSize = GsSizes.SliceSize; + _robSize = gsSizes.RobSize; + _sliceSize = gsSizes.SliceSize; } - public int GetImageSize(int MipsCount) + public int GetImageSize(int mipsCount) { - int Size = GetMipOffset(MipsCount); + int size = GetMipOffset(mipsCount); - Size = (Size + 0x1fff) & ~0x1fff; + size = (size + 0x1fff) & ~0x1fff; - return Size; + return size; } - public int GetMipOffset(int Level) + public int GetMipOffset(int level) { - int TotalSize = 0; + int totalSize = 0; - for (int Index = 0; Index < Level; Index++) + for (int index = 0; index < level; index++) { - int Width = Math.Max(1, TexWidth >> Index); - int Height = Math.Max(1, TexHeight >> Index); - int Depth = Math.Max(1, TexDepth >> Index); + int width = Math.Max(1, _texWidth >> index); + int height = Math.Max(1, _texHeight >> index); + int depth = Math.Max(1, _texDepth >> index); - GobBlockSizes GbSizes = AdjustGobBlockSizes(Height, Depth); + GobBlockSizes gbSizes = AdjustGobBlockSizes(height, depth); - RobAndSliceSizes RsSizes = GetRobAndSliceSizes(Width, Height, GbSizes); + RobAndSliceSizes rsSizes = GetRobAndSliceSizes(width, height, gbSizes); - TotalSize += BitUtils.DivRoundUp(Depth, GbSizes.Depth) * RsSizes.SliceSize; + totalSize += BitUtils.DivRoundUp(depth, gbSizes.Depth) * rsSizes.SliceSize; } - return TotalSize; + return totalSize; } private struct GobBlockSizes @@ -109,32 +109,32 @@ namespace Ryujinx.Graphics.Texture public int Height; public int Depth; - public GobBlockSizes(int GobBlockHeight, int GobBlockDepth) + public GobBlockSizes(int gobBlockHeight, int gobBlockDepth) { - this.Height = GobBlockHeight; - this.Depth = GobBlockDepth; + Height = gobBlockHeight; + Depth = gobBlockDepth; } } - private GobBlockSizes AdjustGobBlockSizes(int Height, int Depth) + private GobBlockSizes AdjustGobBlockSizes(int height, int depth) { - int GobBlockHeight = TexGobBlockHeight; - int GobBlockDepth = TexGobBlockDepth; + int gobBlockHeight = _texGobBlockHeight; + int gobBlockDepth = _texGobBlockDepth; - int Pow2Height = BitUtils.Pow2RoundUp(Height); - int Pow2Depth = BitUtils.Pow2RoundUp(Depth); + int pow2Height = BitUtils.Pow2RoundUp(height); + int pow2Depth = BitUtils.Pow2RoundUp(depth); - while (GobBlockHeight * GobHeight > Pow2Height && GobBlockHeight > 1) + while (gobBlockHeight * GobHeight > pow2Height && gobBlockHeight > 1) { - GobBlockHeight >>= 1; + gobBlockHeight >>= 1; } - while (GobBlockDepth > Pow2Depth && GobBlockDepth > 1) + while (gobBlockDepth > pow2Depth && gobBlockDepth > 1) { - GobBlockDepth >>= 1; + gobBlockDepth >>= 1; } - return new GobBlockSizes(GobBlockHeight, GobBlockDepth); + return new GobBlockSizes(gobBlockHeight, gobBlockDepth); } private struct RobAndSliceSizes @@ -142,45 +142,45 @@ namespace Ryujinx.Graphics.Texture public int RobSize; public int SliceSize; - public RobAndSliceSizes(int RobSize, int SliceSize) + public RobAndSliceSizes(int robSize, int sliceSize) { - this.RobSize = RobSize; - this.SliceSize = SliceSize; + RobSize = robSize; + SliceSize = sliceSize; } } - private RobAndSliceSizes GetRobAndSliceSizes(int Width, int Height, GobBlockSizes GbSizes) + private RobAndSliceSizes GetRobAndSliceSizes(int width, int height, GobBlockSizes gbSizes) { - int WidthInGobs = BitUtils.DivRoundUp(Width * TexBpp, GobWidth); + int widthInGobs = BitUtils.DivRoundUp(width * _texBpp, GobWidth); - int RobSize = GobSize * GbSizes.Height * GbSizes.Depth * WidthInGobs; + int robSize = GobSize * gbSizes.Height * gbSizes.Depth * widthInGobs; - int SliceSize = BitUtils.DivRoundUp(Height, GbSizes.Height * GobHeight) * RobSize; + int sliceSize = BitUtils.DivRoundUp(height, gbSizes.Height * GobHeight) * robSize; - return new RobAndSliceSizes(RobSize, SliceSize); + return new RobAndSliceSizes(robSize, sliceSize); } - public int GetSwizzleOffset(int X, int Y, int Z) + public int GetSwizzleOffset(int x, int y, int z) { - X <<= BppShift; + x <<= _bppShift; - int YH = Y / GobHeight; + int yh = y / GobHeight; - int Position = (Z >> BdShift) * SliceSize + (YH >> BhShift) * RobSize; + int position = (z >> _bdShift) * _sliceSize + (yh >> _bhShift) * _robSize; - Position += (X / GobWidth) << XShift; + position += (x / GobWidth) << _xShift; - Position += (YH & BhMask) * GobSize; + position += (yh & _bhMask) * GobSize; - Position += ((Z & BdMask) * GobSize) << BhShift; + position += ((z & _bdMask) * GobSize) << _bhShift; - Position += ((X & 0x3f) >> 5) << 8; - Position += ((Y & 0x07) >> 1) << 6; - Position += ((X & 0x1f) >> 4) << 5; - Position += ((Y & 0x01) >> 0) << 4; - Position += ((X & 0x0f) >> 0) << 0; + position += ((x & 0x3f) >> 5) << 8; + position += ((y & 0x07) >> 1) << 6; + position += ((x & 0x1f) >> 4) << 5; + position += ((y & 0x01) >> 0) << 4; + position += ((x & 0x0f) >> 0) << 0; - return BaseOffset + Position; + return _baseOffset + position; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/ISwizzle.cs b/Ryujinx.Graphics/Graphics3d/Texture/ISwizzle.cs index 2e0e8aed..fae3eada 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/ISwizzle.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/ISwizzle.cs @@ -2,12 +2,12 @@ namespace Ryujinx.Graphics.Texture { interface ISwizzle { - int GetSwizzleOffset(int X, int Y, int Z); + int GetSwizzleOffset(int x, int y, int z); - void SetMipLevel(int Level); + void SetMipLevel(int level); - int GetMipOffset(int Level); + int GetMipOffset(int level); - int GetImageSize(int MipsCount); + int GetImageSize(int mipsCount); } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/ImageUtils.cs b/Ryujinx.Graphics/Graphics3d/Texture/ImageUtils.cs index c4208935..bd9b4327 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/ImageUtils.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/ImageUtils.cs @@ -1,6 +1,5 @@ using ChocolArm64.Memory; using OpenTK.Graphics.OpenGL; -using Ryujinx.Common; using Ryujinx.Graphics.Gal; using Ryujinx.Graphics.Memory; using System; @@ -29,13 +28,13 @@ namespace Ryujinx.Graphics.Texture public TargetBuffer Target { get; private set; } - public ImageDescriptor(int BytesPerPixel, int BlockWidth, int BlockHeight, int BlockDepth, TargetBuffer Target) + public ImageDescriptor(int bytesPerPixel, int blockWidth, int blockHeight, int blockDepth, TargetBuffer target) { - this.BytesPerPixel = BytesPerPixel; - this.BlockWidth = BlockWidth; - this.BlockHeight = BlockHeight; - this.BlockDepth = BlockDepth; - this.Target = Target; + BytesPerPixel = bytesPerPixel; + BlockWidth = blockWidth; + BlockHeight = blockHeight; + BlockDepth = blockDepth; + Target = target; } } @@ -46,26 +45,26 @@ namespace Ryujinx.Graphics.Texture private const GalImageFormat Float = GalImageFormat.Float; private const GalImageFormat Srgb = GalImageFormat.Srgb; - private static readonly Dictionary s_TextureTable = + private static readonly Dictionary TextureTable = new Dictionary() { - { GalTextureFormat.RGBA32, GalImageFormat.RGBA32 | Sint | Uint | Float }, - { GalTextureFormat.RGBA16, GalImageFormat.RGBA16 | Snorm | Unorm | Sint | Uint | Float }, - { GalTextureFormat.RG32, GalImageFormat.RG32 | Sint | Uint | Float }, - { GalTextureFormat.RGBA8, GalImageFormat.RGBA8 | Snorm | Unorm | Sint | Uint | Srgb }, - { GalTextureFormat.RGB10A2, GalImageFormat.RGB10A2 | Snorm | Unorm | Sint | Uint }, - { GalTextureFormat.RG8, GalImageFormat.RG8 | Snorm | Unorm | Sint | Uint }, + { GalTextureFormat.Rgba32, GalImageFormat.Rgba32 | Sint | Uint | Float }, + { GalTextureFormat.Rgba16, GalImageFormat.Rgba16 | Snorm | Unorm | Sint | Uint | Float }, + { GalTextureFormat.Rg32, GalImageFormat.Rg32 | Sint | Uint | Float }, + { GalTextureFormat.Rgba8, GalImageFormat.Rgba8 | Snorm | Unorm | Sint | Uint | Srgb }, + { GalTextureFormat.Rgb10A2, GalImageFormat.Rgb10A2 | Snorm | Unorm | Sint | Uint }, + { GalTextureFormat.Rg8, GalImageFormat.Rg8 | Snorm | Unorm | Sint | Uint }, { GalTextureFormat.R16, GalImageFormat.R16 | Snorm | Unorm | Sint | Uint | Float }, { GalTextureFormat.R8, GalImageFormat.R8 | Snorm | Unorm | Sint | Uint }, - { GalTextureFormat.RG16, GalImageFormat.RG16 | Snorm | Unorm | Sint | Float }, + { GalTextureFormat.Rg16, GalImageFormat.Rg16 | Snorm | Unorm | Sint | Float }, { GalTextureFormat.R32, GalImageFormat.R32 | Sint | Uint | Float }, - { GalTextureFormat.RGBA4, GalImageFormat.RGBA4 | Unorm }, - { GalTextureFormat.RGB5A1, GalImageFormat.RGB5A1 | Unorm }, - { GalTextureFormat.RGB565, GalImageFormat.RGB565 | Unorm }, + { GalTextureFormat.Rgba4, GalImageFormat.Rgba4 | Unorm }, + { GalTextureFormat.Rgb5A1, GalImageFormat.Rgb5A1 | Unorm }, + { GalTextureFormat.Rgb565, GalImageFormat.Rgb565 | Unorm }, { GalTextureFormat.R11G11B10F, GalImageFormat.R11G11B10 | Float }, { GalTextureFormat.D24S8, GalImageFormat.D24S8 | Unorm | Uint }, { GalTextureFormat.D32F, GalImageFormat.D32 | Float }, - { GalTextureFormat.D32FX24S8, GalImageFormat.D32S8 | Float }, + { GalTextureFormat.D32Fx24S8, GalImageFormat.D32S8 | Float }, { GalTextureFormat.D16, GalImageFormat.D16 | Unorm }, //Compressed formats @@ -93,27 +92,27 @@ namespace Ryujinx.Graphics.Texture { GalTextureFormat.Astc2D10x6, GalImageFormat.Astc2D10x6 | Unorm | Srgb } }; - private static readonly Dictionary s_ImageTable = + private static readonly Dictionary ImageTable = new Dictionary() { - { GalImageFormat.RGBA32, new ImageDescriptor(16, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RGBA16, new ImageDescriptor(8, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RG32, new ImageDescriptor(8, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RGBX8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RGBA8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.BGRA8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RGB10A2, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rgba32, new ImageDescriptor(16, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rgba16, new ImageDescriptor(8, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rg32, new ImageDescriptor(8, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rgbx8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rgba8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Bgra8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rgb10A2, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, { GalImageFormat.R32, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RGBA4, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rgba4, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, { GalImageFormat.BptcSfloat, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, { GalImageFormat.BptcUfloat, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.BGR5A1, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RGB5A1, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RGB565, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.BGR565, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Bgr5A1, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rgb5A1, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rgb565, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Bgr565, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, { GalImageFormat.BptcUnorm, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.RG16, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.RG8, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rg16, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, + { GalImageFormat.Rg8, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, { GalImageFormat.R16, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, { GalImageFormat.R8, new ImageDescriptor(1, 1, 1, 1, TargetBuffer.Color) }, { GalImageFormat.R11G11B10, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, @@ -145,77 +144,77 @@ namespace Ryujinx.Graphics.Texture }; public static GalImageFormat ConvertTexture( - GalTextureFormat Format, - GalTextureType RType, - GalTextureType GType, - GalTextureType BType, - GalTextureType AType, - bool ConvSrgb) + GalTextureFormat format, + GalTextureType rType, + GalTextureType gType, + GalTextureType bType, + GalTextureType aType, + bool convSrgb) { - if (!s_TextureTable.TryGetValue(Format, out GalImageFormat ImageFormat)) + if (!TextureTable.TryGetValue(format, out GalImageFormat imageFormat)) { - throw new NotImplementedException($"Format 0x{((int)Format):x} not implemented!"); + throw new NotImplementedException($"Format 0x{((int)format):x} not implemented!"); } - if (!HasDepth(ImageFormat) && (RType != GType || RType != BType || RType != AType)) + if (!HasDepth(imageFormat) && (rType != gType || rType != bType || rType != aType)) { - throw new NotImplementedException($"Per component types are not implemented!"); + throw new NotImplementedException("Per component types are not implemented!"); } - GalImageFormat FormatType = ConvSrgb ? Srgb : GetFormatType(RType); + GalImageFormat formatType = convSrgb ? Srgb : GetFormatType(rType); - GalImageFormat CombinedFormat = (ImageFormat & GalImageFormat.FormatMask) | FormatType; + GalImageFormat combinedFormat = (imageFormat & GalImageFormat.FormatMask) | formatType; - if (!ImageFormat.HasFlag(FormatType)) + if (!imageFormat.HasFlag(formatType)) { - throw new NotImplementedException($"Format \"{CombinedFormat}\" not implemented!"); + throw new NotImplementedException($"Format \"{combinedFormat}\" not implemented!"); } - return CombinedFormat; + return combinedFormat; } - public static GalImageFormat ConvertSurface(GalSurfaceFormat Format) + public static GalImageFormat ConvertSurface(GalSurfaceFormat format) { - switch (Format) + switch (format) { - case GalSurfaceFormat.RGBA32Float: return GalImageFormat.RGBA32 | Float; - case GalSurfaceFormat.RGBA32Uint: return GalImageFormat.RGBA32 | Uint; - case GalSurfaceFormat.RGBA16Float: return GalImageFormat.RGBA16 | Float; - case GalSurfaceFormat.RGBA16Unorm: return GalImageFormat.RGBA16 | Unorm; - case GalSurfaceFormat.RG32Float: return GalImageFormat.RG32 | Float; - case GalSurfaceFormat.RG32Sint: return GalImageFormat.RG32 | Sint; - case GalSurfaceFormat.RG32Uint: return GalImageFormat.RG32 | Uint; - case GalSurfaceFormat.BGRA8Unorm: return GalImageFormat.BGRA8 | Unorm; - case GalSurfaceFormat.BGRA8Srgb: return GalImageFormat.BGRA8 | Srgb; - case GalSurfaceFormat.RGB10A2Unorm: return GalImageFormat.RGB10A2 | Unorm; - case GalSurfaceFormat.RGBA8Unorm: return GalImageFormat.RGBA8 | Unorm; - case GalSurfaceFormat.RGBA8Srgb: return GalImageFormat.RGBA8 | Srgb; - case GalSurfaceFormat.RGBA8Snorm: return GalImageFormat.RGBA8 | Snorm; - case GalSurfaceFormat.RG16Snorm: return GalImageFormat.RG16 | Snorm; - case GalSurfaceFormat.RG16Unorm: return GalImageFormat.RG16 | Unorm; - case GalSurfaceFormat.RG16Sint: return GalImageFormat.RG16 | Sint; - case GalSurfaceFormat.RG16Float: return GalImageFormat.RG16 | Float; + case GalSurfaceFormat.Rgba32Float: return GalImageFormat.Rgba32 | Float; + case GalSurfaceFormat.Rgba32Uint: return GalImageFormat.Rgba32 | Uint; + case GalSurfaceFormat.Rgba16Float: return GalImageFormat.Rgba16 | Float; + case GalSurfaceFormat.Rgba16Unorm: return GalImageFormat.Rgba16 | Unorm; + case GalSurfaceFormat.Rg32Float: return GalImageFormat.Rg32 | Float; + case GalSurfaceFormat.Rg32Sint: return GalImageFormat.Rg32 | Sint; + case GalSurfaceFormat.Rg32Uint: return GalImageFormat.Rg32 | Uint; + case GalSurfaceFormat.Bgra8Unorm: return GalImageFormat.Bgra8 | Unorm; + case GalSurfaceFormat.Bgra8Srgb: return GalImageFormat.Bgra8 | Srgb; + case GalSurfaceFormat.Rgb10A2Unorm: return GalImageFormat.Rgb10A2 | Unorm; + case GalSurfaceFormat.Rgba8Unorm: return GalImageFormat.Rgba8 | Unorm; + case GalSurfaceFormat.Rgba8Srgb: return GalImageFormat.Rgba8 | Srgb; + case GalSurfaceFormat.Rgba8Snorm: return GalImageFormat.Rgba8 | Snorm; + case GalSurfaceFormat.Rg16Snorm: return GalImageFormat.Rg16 | Snorm; + case GalSurfaceFormat.Rg16Unorm: return GalImageFormat.Rg16 | Unorm; + case GalSurfaceFormat.Rg16Sint: return GalImageFormat.Rg16 | Sint; + case GalSurfaceFormat.Rg16Float: return GalImageFormat.Rg16 | Float; case GalSurfaceFormat.R11G11B10Float: return GalImageFormat.R11G11B10 | Float; case GalSurfaceFormat.R32Float: return GalImageFormat.R32 | Float; case GalSurfaceFormat.R32Uint: return GalImageFormat.R32 | Uint; - case GalSurfaceFormat.RG8Unorm: return GalImageFormat.RG8 | Unorm; - case GalSurfaceFormat.RG8Snorm: return GalImageFormat.RG8 | Snorm; + case GalSurfaceFormat.Rg8Unorm: return GalImageFormat.Rg8 | Unorm; + case GalSurfaceFormat.Rg8Snorm: return GalImageFormat.Rg8 | Snorm; case GalSurfaceFormat.R16Float: return GalImageFormat.R16 | Float; case GalSurfaceFormat.R16Unorm: return GalImageFormat.R16 | Unorm; case GalSurfaceFormat.R16Uint: return GalImageFormat.R16 | Uint; case GalSurfaceFormat.R8Unorm: return GalImageFormat.R8 | Unorm; case GalSurfaceFormat.R8Uint: return GalImageFormat.R8 | Uint; - case GalSurfaceFormat.B5G6R5Unorm: return GalImageFormat.RGB565 | Unorm; - case GalSurfaceFormat.BGR5A1Unorm: return GalImageFormat.BGR5A1 | Unorm; - case GalSurfaceFormat.RGBX8Unorm: return GalImageFormat.RGBX8 | Unorm; + case GalSurfaceFormat.B5G6R5Unorm: return GalImageFormat.Rgb565 | Unorm; + case GalSurfaceFormat.Bgr5A1Unorm: return GalImageFormat.Bgr5A1 | Unorm; + case GalSurfaceFormat.Rgbx8Unorm: return GalImageFormat.Rgbx8 | Unorm; } - throw new NotImplementedException(Format.ToString()); + throw new NotImplementedException(format.ToString()); } - public static GalImageFormat ConvertZeta(GalZetaFormat Format) + public static GalImageFormat ConvertZeta(GalZetaFormat format) { - switch (Format) + switch (format) { case GalZetaFormat.D32Float: return GalImageFormat.D32 | Float; case GalZetaFormat.S8D24Unorm: return GalImageFormat.D24S8 | Unorm; @@ -225,268 +224,268 @@ namespace Ryujinx.Graphics.Texture case GalZetaFormat.D32S8X24Float: return GalImageFormat.D32S8 | Float; } - throw new NotImplementedException(Format.ToString()); + throw new NotImplementedException(format.ToString()); } - public static byte[] ReadTexture(IMemory Memory, GalImage Image, long Position) + public static byte[] ReadTexture(IMemory memory, GalImage image, long position) { - MemoryManager CpuMemory; + MemoryManager cpuMemory; - if (Memory is NvGpuVmm Vmm) + if (memory is NvGpuVmm vmm) { - CpuMemory = Vmm.Memory; + cpuMemory = vmm.Memory; } else { - CpuMemory = (MemoryManager)Memory; + cpuMemory = (MemoryManager)memory; } - ISwizzle Swizzle = TextureHelper.GetSwizzle(Image); + ISwizzle swizzle = TextureHelper.GetSwizzle(image); - ImageDescriptor Desc = GetImageDescriptor(Image.Format); + ImageDescriptor desc = GetImageDescriptor(image.Format); - (int Width, int Height, int Depth) = GetImageSizeInBlocks(Image); + (int width, int height, int depth) = GetImageSizeInBlocks(image); - int BytesPerPixel = Desc.BytesPerPixel; + int bytesPerPixel = desc.BytesPerPixel; //Note: Each row of the texture needs to be aligned to 4 bytes. - int Pitch = (Width * BytesPerPixel + 3) & ~3; + int pitch = (width * bytesPerPixel + 3) & ~3; - int DataLayerSize = Height * Pitch * Depth; - byte[] Data = new byte[DataLayerSize * Image.LayerCount]; + int dataLayerSize = height * pitch * depth; + byte[] data = new byte[dataLayerSize * image.LayerCount]; - int TargetMipLevel = Image.MaxMipmapLevel <= 1 ? 1 : Image.MaxMipmapLevel - 1; - int LayerOffset = ImageUtils.GetLayerOffset(Image, TargetMipLevel); + int targetMipLevel = image.MaxMipmapLevel <= 1 ? 1 : image.MaxMipmapLevel - 1; + int layerOffset = GetLayerOffset(image, targetMipLevel); - for (int Layer = 0; Layer < Image.LayerCount; Layer++) + for (int layer = 0; layer < image.LayerCount; layer++) { - for (int Z = 0; Z < Depth; Z++) + for (int z = 0; z < depth; z++) { - for (int Y = 0; Y < Height; Y++) + for (int y = 0; y < height; y++) { - int OutOffs = (DataLayerSize * Layer) + Y * Pitch + (Z * Width * Height * BytesPerPixel); + int outOffs = (dataLayerSize * layer) + y * pitch + (z * width * height * bytesPerPixel); - for (int X = 0; X < Width; X++) + for (int x = 0; x < width; x++) { - long Offset = (uint)Swizzle.GetSwizzleOffset(X, Y, Z); + long offset = (uint)swizzle.GetSwizzleOffset(x, y, z); - CpuMemory.ReadBytes(Position + (LayerOffset * Layer) + Offset, Data, OutOffs, BytesPerPixel); + cpuMemory.ReadBytes(position + (layerOffset * layer) + offset, data, outOffs, bytesPerPixel); - OutOffs += BytesPerPixel; + outOffs += bytesPerPixel; } } } } - return Data; + return data; } - public static void WriteTexture(NvGpuVmm Vmm, GalImage Image, long Position, byte[] Data) + public static void WriteTexture(NvGpuVmm vmm, GalImage image, long position, byte[] data) { - ISwizzle Swizzle = TextureHelper.GetSwizzle(Image); + ISwizzle swizzle = TextureHelper.GetSwizzle(image); - ImageDescriptor Desc = GetImageDescriptor(Image.Format); + ImageDescriptor desc = GetImageDescriptor(image.Format); - (int Width, int Height, int Depth) = ImageUtils.GetImageSizeInBlocks(Image); + (int width, int height, int depth) = GetImageSizeInBlocks(image); - int BytesPerPixel = Desc.BytesPerPixel; + int bytesPerPixel = desc.BytesPerPixel; - int InOffs = 0; + int inOffs = 0; - for (int Z = 0; Z < Depth; Z++) - for (int Y = 0; Y < Height; Y++) - for (int X = 0; X < Width; X++) + for (int z = 0; z < depth; z++) + for (int y = 0; y < height; y++) + for (int x = 0; x < width; x++) { - long Offset = (uint)Swizzle.GetSwizzleOffset(X, Y, Z); + long offset = (uint)swizzle.GetSwizzleOffset(x, y, z); - Vmm.Memory.WriteBytes(Position + Offset, Data, InOffs, BytesPerPixel); + vmm.Memory.WriteBytes(position + offset, data, inOffs, bytesPerPixel); - InOffs += BytesPerPixel; + inOffs += bytesPerPixel; } } // TODO: Support non 2D public static bool CopyTexture( - NvGpuVmm Vmm, - GalImage SrcImage, - GalImage DstImage, - long SrcAddress, - long DstAddress, - int SrcX, - int SrcY, - int DstX, - int DstY, - int Width, - int Height) + NvGpuVmm vmm, + GalImage srcImage, + GalImage dstImage, + long srcAddress, + long dstAddress, + int srcX, + int srcY, + int dstX, + int dstY, + int width, + int height) { - ISwizzle SrcSwizzle = TextureHelper.GetSwizzle(SrcImage); - ISwizzle DstSwizzle = TextureHelper.GetSwizzle(DstImage); + ISwizzle srcSwizzle = TextureHelper.GetSwizzle(srcImage); + ISwizzle dstSwizzle = TextureHelper.GetSwizzle(dstImage); - ImageDescriptor Desc = GetImageDescriptor(SrcImage.Format); + ImageDescriptor desc = GetImageDescriptor(srcImage.Format); - if (GetImageDescriptor(DstImage.Format).BytesPerPixel != Desc.BytesPerPixel) + if (GetImageDescriptor(dstImage.Format).BytesPerPixel != desc.BytesPerPixel) { return false; } - int BytesPerPixel = Desc.BytesPerPixel; + int bytesPerPixel = desc.BytesPerPixel; - for (int Y = 0; Y < Height; Y++) - for (int X = 0; X < Width; X++) + for (int y = 0; y < height; y++) + for (int x = 0; x < width; x++) { - long SrcOffset = (uint)SrcSwizzle.GetSwizzleOffset(SrcX + X, SrcY + Y, 0); - long DstOffset = (uint)DstSwizzle.GetSwizzleOffset(DstX + X, DstY + Y, 0); + long srcOffset = (uint)srcSwizzle.GetSwizzleOffset(srcX + x, srcY + y, 0); + long dstOffset = (uint)dstSwizzle.GetSwizzleOffset(dstX + x, dstY + y, 0); - byte[] Texel = Vmm.ReadBytes(SrcAddress + SrcOffset, BytesPerPixel); + byte[] texel = vmm.ReadBytes(srcAddress + srcOffset, bytesPerPixel); - Vmm.WriteBytes(DstAddress + DstOffset, Texel); + vmm.WriteBytes(dstAddress + dstOffset, texel); } return true; } - public static int GetSize(GalImage Image) + public static int GetSize(GalImage image) { - ImageDescriptor Desc = GetImageDescriptor(Image.Format); + ImageDescriptor desc = GetImageDescriptor(image.Format); - int ComponentCount = GetCoordsCountTextureTarget(Image.TextureTarget); + int componentCount = GetCoordsCountTextureTarget(image.TextureTarget); - if (IsArray(Image.TextureTarget)) - ComponentCount--; + if (IsArray(image.TextureTarget)) + componentCount--; - int Width = DivRoundUp(Image.Width, Desc.BlockWidth); - int Height = DivRoundUp(Image.Height, Desc.BlockHeight); - int Depth = DivRoundUp(Image.Depth, Desc.BlockDepth); + int width = DivRoundUp(image.Width, desc.BlockWidth); + int height = DivRoundUp(image.Height, desc.BlockHeight); + int depth = DivRoundUp(image.Depth, desc.BlockDepth); - switch (ComponentCount) + switch (componentCount) { case 1: - return Desc.BytesPerPixel * Width * Image.LayerCount; + return desc.BytesPerPixel * width * image.LayerCount; case 2: - return Desc.BytesPerPixel * Width * Height * Image.LayerCount; + return desc.BytesPerPixel * width * height * image.LayerCount; case 3: - return Desc.BytesPerPixel * Width * Height * Depth * Image.LayerCount; + return desc.BytesPerPixel * width * height * depth * image.LayerCount; default: - throw new InvalidOperationException($"Invalid component count: {ComponentCount}"); + throw new InvalidOperationException($"Invalid component count: {componentCount}"); } } - public static int GetGpuSize(GalImage Image, bool forcePitch = false) + public static int GetGpuSize(GalImage image, bool forcePitch = false) { - return TextureHelper.GetSwizzle(Image).GetImageSize(Image.MaxMipmapLevel) * Image.LayerCount; + return TextureHelper.GetSwizzle(image).GetImageSize(image.MaxMipmapLevel) * image.LayerCount; } - public static int GetLayerOffset(GalImage Image, int MipLevel) + public static int GetLayerOffset(GalImage image, int mipLevel) { - if (MipLevel <= 0) + if (mipLevel <= 0) { - MipLevel = 1; + mipLevel = 1; } - return TextureHelper.GetSwizzle(Image).GetMipOffset(MipLevel); + return TextureHelper.GetSwizzle(image).GetMipOffset(mipLevel); } - public static int GetPitch(GalImageFormat Format, int Width) + public static int GetPitch(GalImageFormat format, int width) { - ImageDescriptor Desc = GetImageDescriptor(Format); + ImageDescriptor desc = GetImageDescriptor(format); - int Pitch = Desc.BytesPerPixel * DivRoundUp(Width, Desc.BlockWidth); + int pitch = desc.BytesPerPixel * DivRoundUp(width, desc.BlockWidth); - Pitch = (Pitch + 0x1f) & ~0x1f; + pitch = (pitch + 0x1f) & ~0x1f; - return Pitch; + return pitch; } - public static int GetBlockWidth(GalImageFormat Format) + public static int GetBlockWidth(GalImageFormat format) { - return GetImageDescriptor(Format).BlockWidth; + return GetImageDescriptor(format).BlockWidth; } - public static int GetBlockHeight(GalImageFormat Format) + public static int GetBlockHeight(GalImageFormat format) { - return GetImageDescriptor(Format).BlockHeight; + return GetImageDescriptor(format).BlockHeight; } - public static int GetBlockDepth(GalImageFormat Format) + public static int GetBlockDepth(GalImageFormat format) { - return GetImageDescriptor(Format).BlockDepth; + return GetImageDescriptor(format).BlockDepth; } - public static int GetAlignedWidth(GalImage Image) + public static int GetAlignedWidth(GalImage image) { - ImageDescriptor Desc = GetImageDescriptor(Image.Format); + ImageDescriptor desc = GetImageDescriptor(image.Format); - int AlignMask; + int alignMask; - if (Image.Layout == GalMemoryLayout.BlockLinear) + if (image.Layout == GalMemoryLayout.BlockLinear) { - AlignMask = Image.TileWidth * (64 / Desc.BytesPerPixel) - 1; + alignMask = image.TileWidth * (64 / desc.BytesPerPixel) - 1; } else { - AlignMask = (32 / Desc.BytesPerPixel) - 1; + alignMask = (32 / desc.BytesPerPixel) - 1; } - return (Image.Width + AlignMask) & ~AlignMask; + return (image.Width + alignMask) & ~alignMask; } - public static (int Width, int Height, int Depth) GetImageSizeInBlocks(GalImage Image) + public static (int Width, int Height, int Depth) GetImageSizeInBlocks(GalImage image) { - ImageDescriptor Desc = GetImageDescriptor(Image.Format); + ImageDescriptor desc = GetImageDescriptor(image.Format); - return (DivRoundUp(Image.Width, Desc.BlockWidth), - DivRoundUp(Image.Height, Desc.BlockHeight), - DivRoundUp(Image.Depth, Desc.BlockDepth)); + return (DivRoundUp(image.Width, desc.BlockWidth), + DivRoundUp(image.Height, desc.BlockHeight), + DivRoundUp(image.Depth, desc.BlockDepth)); } - public static int GetBytesPerPixel(GalImageFormat Format) + public static int GetBytesPerPixel(GalImageFormat format) { - return GetImageDescriptor(Format).BytesPerPixel; + return GetImageDescriptor(format).BytesPerPixel; } - private static int DivRoundUp(int LHS, int RHS) + private static int DivRoundUp(int lhs, int rhs) { - return (LHS + (RHS - 1)) / RHS; + return (lhs + (rhs - 1)) / rhs; } - public static bool HasColor(GalImageFormat Format) + public static bool HasColor(GalImageFormat format) { - return (GetImageDescriptor(Format).Target & TargetBuffer.Color) != 0; + return (GetImageDescriptor(format).Target & TargetBuffer.Color) != 0; } - public static bool HasDepth(GalImageFormat Format) + public static bool HasDepth(GalImageFormat format) { - return (GetImageDescriptor(Format).Target & TargetBuffer.Depth) != 0; + return (GetImageDescriptor(format).Target & TargetBuffer.Depth) != 0; } - public static bool HasStencil(GalImageFormat Format) + public static bool HasStencil(GalImageFormat format) { - return (GetImageDescriptor(Format).Target & TargetBuffer.Stencil) != 0; + return (GetImageDescriptor(format).Target & TargetBuffer.Stencil) != 0; } - public static bool IsCompressed(GalImageFormat Format) + public static bool IsCompressed(GalImageFormat format) { - ImageDescriptor Desc = GetImageDescriptor(Format); + ImageDescriptor desc = GetImageDescriptor(format); - return (Desc.BlockWidth | Desc.BlockHeight) != 1; + return (desc.BlockWidth | desc.BlockHeight) != 1; } - private static ImageDescriptor GetImageDescriptor(GalImageFormat Format) + private static ImageDescriptor GetImageDescriptor(GalImageFormat format) { - GalImageFormat PixelFormat = Format & GalImageFormat.FormatMask; + GalImageFormat pixelFormat = format & GalImageFormat.FormatMask; - if (s_ImageTable.TryGetValue(PixelFormat, out ImageDescriptor Descriptor)) + if (ImageTable.TryGetValue(pixelFormat, out ImageDescriptor descriptor)) { - return Descriptor; + return descriptor; } - throw new NotImplementedException($"Format \"{PixelFormat}\" not implemented!"); + throw new NotImplementedException($"Format \"{pixelFormat}\" not implemented!"); } - private static GalImageFormat GetFormatType(GalTextureType Type) + private static GalImageFormat GetFormatType(GalTextureType type) { - switch (Type) + switch (type) { case GalTextureType.Snorm: return Snorm; case GalTextureType.Unorm: return Unorm; @@ -494,13 +493,13 @@ namespace Ryujinx.Graphics.Texture case GalTextureType.Uint: return Uint; case GalTextureType.Float: return Float; - default: throw new NotImplementedException(((int)Type).ToString()); + default: throw new NotImplementedException(((int)type).ToString()); } } - public static TextureTarget GetTextureTarget(GalTextureTarget GalTextureTarget) + public static TextureTarget GetTextureTarget(GalTextureTarget galTextureTarget) { - switch (GalTextureTarget) + switch (galTextureTarget) { case GalTextureTarget.OneD: return TextureTarget.Texture1D; @@ -520,13 +519,13 @@ namespace Ryujinx.Graphics.Texture case GalTextureTarget.CubeArray: return TextureTarget.TextureCubeMapArray; default: - throw new NotSupportedException($"Texture target {GalTextureTarget} currently not supported!"); + throw new NotSupportedException($"Texture target {galTextureTarget} currently not supported!"); } } - public static bool IsArray(GalTextureTarget TextureTarget) + public static bool IsArray(GalTextureTarget textureTarget) { - switch (TextureTarget) + switch (textureTarget) { case GalTextureTarget.OneDArray: case GalTextureTarget.TwoDArray: @@ -537,9 +536,9 @@ namespace Ryujinx.Graphics.Texture } } - public static int GetCoordsCountTextureTarget(GalTextureTarget TextureTarget) + public static int GetCoordsCountTextureTarget(GalTextureTarget textureTarget) { - switch (TextureTarget) + switch (textureTarget) { case GalTextureTarget.OneD: return 1; @@ -555,7 +554,7 @@ namespace Ryujinx.Graphics.Texture case GalTextureTarget.CubeArray: return 4; default: - throw new NotImplementedException($"TextureTarget.{TextureTarget} not implemented yet."); + throw new NotImplementedException($"TextureTarget.{textureTarget} not implemented yet."); } } } diff --git a/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs b/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs index 683cb770..e6d67058 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs @@ -12,81 +12,81 @@ namespace Ryujinx.Graphics.Texture Trit } - EIntegerEncoding Encoding; + EIntegerEncoding _encoding; public int NumberBits { get; private set; } public int BitValue { get; private set; } public int TritValue { get; private set; } public int QuintValue { get; private set; } - public IntegerEncoded(EIntegerEncoding _Encoding, int NumBits) + public IntegerEncoded(EIntegerEncoding encoding, int numBits) { - Encoding = _Encoding; - NumberBits = NumBits; + _encoding = encoding; + NumberBits = numBits; BitValue = 0; TritValue = 0; QuintValue = 0; } - public bool MatchesEncoding(IntegerEncoded Other) + public bool MatchesEncoding(IntegerEncoded other) { - return Encoding == Other.Encoding && NumberBits == Other.NumberBits; + return _encoding == other._encoding && NumberBits == other.NumberBits; } public EIntegerEncoding GetEncoding() { - return Encoding; + return _encoding; } - public int GetBitLength(int NumberVals) + public int GetBitLength(int numberVals) { - int TotalBits = NumberBits * NumberVals; - if (Encoding == EIntegerEncoding.Trit) + int totalBits = NumberBits * numberVals; + if (_encoding == EIntegerEncoding.Trit) { - TotalBits += (NumberVals * 8 + 4) / 5; + totalBits += (numberVals * 8 + 4) / 5; } - else if (Encoding == EIntegerEncoding.Quint) + else if (_encoding == EIntegerEncoding.Quint) { - TotalBits += (NumberVals * 7 + 2) / 3; + totalBits += (numberVals * 7 + 2) / 3; } - return TotalBits; + return totalBits; } - public static IntegerEncoded CreateEncoding(int MaxVal) + public static IntegerEncoded CreateEncoding(int maxVal) { - while (MaxVal > 0) + while (maxVal > 0) { - int Check = MaxVal + 1; + int check = maxVal + 1; // Is maxVal a power of two? - if ((Check & (Check - 1)) == 0) + if ((check & (check - 1)) == 0) { - return new IntegerEncoded(EIntegerEncoding.JustBits, BitArrayStream.PopCnt(MaxVal)); + return new IntegerEncoded(EIntegerEncoding.JustBits, BitArrayStream.PopCnt(maxVal)); } // Is maxVal of the type 3*2^n - 1? - if ((Check % 3 == 0) && ((Check / 3) & ((Check / 3) - 1)) == 0) + if ((check % 3 == 0) && ((check / 3) & ((check / 3) - 1)) == 0) { - return new IntegerEncoded(EIntegerEncoding.Trit, BitArrayStream.PopCnt(Check / 3 - 1)); + return new IntegerEncoded(EIntegerEncoding.Trit, BitArrayStream.PopCnt(check / 3 - 1)); } // Is maxVal of the type 5*2^n - 1? - if ((Check % 5 == 0) && ((Check / 5) & ((Check / 5) - 1)) == 0) + if ((check % 5 == 0) && ((check / 5) & ((check / 5) - 1)) == 0) { - return new IntegerEncoded(EIntegerEncoding.Quint, BitArrayStream.PopCnt(Check / 5 - 1)); + return new IntegerEncoded(EIntegerEncoding.Quint, BitArrayStream.PopCnt(check / 5 - 1)); } // Apparently it can't be represented with a bounded integer sequence... // just iterate. - MaxVal--; + maxVal--; } return new IntegerEncoded(EIntegerEncoding.JustBits, 0); } public static void DecodeTritBlock( - BitArrayStream BitStream, - List ListIntegerEncoded, - int NumberBitsPerValue) + BitArrayStream bitStream, + List listIntegerEncoded, + int numberBitsPerValue) { // Implement the algorithm in section C.2.12 int[] m = new int[5]; @@ -95,170 +95,170 @@ namespace Ryujinx.Graphics.Texture // Read the trit encoded block according to // table C.2.14 - m[0] = BitStream.ReadBits(NumberBitsPerValue); - T = BitStream.ReadBits(2); - m[1] = BitStream.ReadBits(NumberBitsPerValue); - T |= BitStream.ReadBits(2) << 2; - m[2] = BitStream.ReadBits(NumberBitsPerValue); - T |= BitStream.ReadBits(1) << 4; - m[3] = BitStream.ReadBits(NumberBitsPerValue); - T |= BitStream.ReadBits(2) << 5; - m[4] = BitStream.ReadBits(NumberBitsPerValue); - T |= BitStream.ReadBits(1) << 7; + m[0] = bitStream.ReadBits(numberBitsPerValue); + T = bitStream.ReadBits(2); + m[1] = bitStream.ReadBits(numberBitsPerValue); + T |= bitStream.ReadBits(2) << 2; + m[2] = bitStream.ReadBits(numberBitsPerValue); + T |= bitStream.ReadBits(1) << 4; + m[3] = bitStream.ReadBits(numberBitsPerValue); + T |= bitStream.ReadBits(2) << 5; + m[4] = bitStream.ReadBits(numberBitsPerValue); + T |= bitStream.ReadBits(1) << 7; - int C = 0; + int c = 0; - BitArrayStream Tb = new BitArrayStream(new BitArray(new int[] { T })); - if (Tb.ReadBits(2, 4) == 7) + BitArrayStream tb = new BitArrayStream(new BitArray(new int[] { T })); + if (tb.ReadBits(2, 4) == 7) { - C = (Tb.ReadBits(5, 7) << 2) | Tb.ReadBits(0, 1); + c = (tb.ReadBits(5, 7) << 2) | tb.ReadBits(0, 1); t[4] = t[3] = 2; } else { - C = Tb.ReadBits(0, 4); - if (Tb.ReadBits(5, 6) == 3) + c = tb.ReadBits(0, 4); + if (tb.ReadBits(5, 6) == 3) { t[4] = 2; - t[3] = Tb.ReadBit(7); + t[3] = tb.ReadBit(7); } else { - t[4] = Tb.ReadBit(7); - t[3] = Tb.ReadBits(5, 6); + t[4] = tb.ReadBit(7); + t[3] = tb.ReadBits(5, 6); } } - BitArrayStream Cb = new BitArrayStream(new BitArray(new int[] { C })); - if (Cb.ReadBits(0, 1) == 3) + BitArrayStream cb = new BitArrayStream(new BitArray(new int[] { c })); + if (cb.ReadBits(0, 1) == 3) { t[2] = 2; - t[1] = Cb.ReadBit(4); - t[0] = (Cb.ReadBit(3) << 1) | (Cb.ReadBit(2) & ~Cb.ReadBit(3)); + t[1] = cb.ReadBit(4); + t[0] = (cb.ReadBit(3) << 1) | (cb.ReadBit(2) & ~cb.ReadBit(3)); } - else if (Cb.ReadBits(2, 3) == 3) + else if (cb.ReadBits(2, 3) == 3) { t[2] = 2; t[1] = 2; - t[0] = Cb.ReadBits(0, 1); + t[0] = cb.ReadBits(0, 1); } else { - t[2] = Cb.ReadBit(4); - t[1] = Cb.ReadBits(2, 3); - t[0] = (Cb.ReadBit(1) << 1) | (Cb.ReadBit(0) & ~Cb.ReadBit(1)); + t[2] = cb.ReadBit(4); + t[1] = cb.ReadBits(2, 3); + t[0] = (cb.ReadBit(1) << 1) | (cb.ReadBit(0) & ~cb.ReadBit(1)); } for (int i = 0; i < 5; i++) { - IntegerEncoded IntEncoded = new IntegerEncoded(EIntegerEncoding.Trit, NumberBitsPerValue) + IntegerEncoded intEncoded = new IntegerEncoded(EIntegerEncoding.Trit, numberBitsPerValue) { BitValue = m[i], TritValue = t[i] }; - ListIntegerEncoded.Add(IntEncoded); + listIntegerEncoded.Add(intEncoded); } } public static void DecodeQuintBlock( - BitArrayStream BitStream, - List ListIntegerEncoded, - int NumberBitsPerValue) + BitArrayStream bitStream, + List listIntegerEncoded, + int numberBitsPerValue) { // Implement the algorithm in section C.2.12 int[] m = new int[3]; - int[] q = new int[3]; - int Q; + int[] qa = new int[3]; + int q; // Read the trit encoded block according to // table C.2.15 - m[0] = BitStream.ReadBits(NumberBitsPerValue); - Q = BitStream.ReadBits(3); - m[1] = BitStream.ReadBits(NumberBitsPerValue); - Q |= BitStream.ReadBits(2) << 3; - m[2] = BitStream.ReadBits(NumberBitsPerValue); - Q |= BitStream.ReadBits(2) << 5; + m[0] = bitStream.ReadBits(numberBitsPerValue); + q = bitStream.ReadBits(3); + m[1] = bitStream.ReadBits(numberBitsPerValue); + q |= bitStream.ReadBits(2) << 3; + m[2] = bitStream.ReadBits(numberBitsPerValue); + q |= bitStream.ReadBits(2) << 5; - BitArrayStream Qb = new BitArrayStream(new BitArray(new int[] { Q })); - if (Qb.ReadBits(1, 2) == 3 && Qb.ReadBits(5, 6) == 0) + BitArrayStream qb = new BitArrayStream(new BitArray(new int[] { q })); + if (qb.ReadBits(1, 2) == 3 && qb.ReadBits(5, 6) == 0) { - q[0] = q[1] = 4; - q[2] = (Qb.ReadBit(0) << 2) | ((Qb.ReadBit(4) & ~Qb.ReadBit(0)) << 1) | (Qb.ReadBit(3) & ~Qb.ReadBit(0)); + qa[0] = qa[1] = 4; + qa[2] = (qb.ReadBit(0) << 2) | ((qb.ReadBit(4) & ~qb.ReadBit(0)) << 1) | (qb.ReadBit(3) & ~qb.ReadBit(0)); } else { - int C = 0; - if (Qb.ReadBits(1, 2) == 3) + int c = 0; + if (qb.ReadBits(1, 2) == 3) { - q[2] = 4; - C = (Qb.ReadBits(3, 4) << 3) | ((~Qb.ReadBits(5, 6) & 3) << 1) | Qb.ReadBit(0); + qa[2] = 4; + c = (qb.ReadBits(3, 4) << 3) | ((~qb.ReadBits(5, 6) & 3) << 1) | qb.ReadBit(0); } else { - q[2] = Qb.ReadBits(5, 6); - C = Qb.ReadBits(0, 4); + qa[2] = qb.ReadBits(5, 6); + c = qb.ReadBits(0, 4); } - BitArrayStream Cb = new BitArrayStream(new BitArray(new int[] { C })); - if (Cb.ReadBits(0, 2) == 5) + BitArrayStream cb = new BitArrayStream(new BitArray(new int[] { c })); + if (cb.ReadBits(0, 2) == 5) { - q[1] = 4; - q[0] = Cb.ReadBits(3, 4); + qa[1] = 4; + qa[0] = cb.ReadBits(3, 4); } else { - q[1] = Cb.ReadBits(3, 4); - q[0] = Cb.ReadBits(0, 2); + qa[1] = cb.ReadBits(3, 4); + qa[0] = cb.ReadBits(0, 2); } } for (int i = 0; i < 3; i++) { - IntegerEncoded IntEncoded = new IntegerEncoded(EIntegerEncoding.Quint, NumberBitsPerValue) + IntegerEncoded intEncoded = new IntegerEncoded(EIntegerEncoding.Quint, numberBitsPerValue) { BitValue = m[i], - QuintValue = q[i] + QuintValue = qa[i] }; - ListIntegerEncoded.Add(IntEncoded); + listIntegerEncoded.Add(intEncoded); } } public static void DecodeIntegerSequence( - List DecodeIntegerSequence, - BitArrayStream BitStream, - int MaxRange, - int NumberValues) + List decodeIntegerSequence, + BitArrayStream bitStream, + int maxRange, + int numberValues) { // Determine encoding parameters - IntegerEncoded IntEncoded = CreateEncoding(MaxRange); + IntegerEncoded intEncoded = CreateEncoding(maxRange); // Start decoding - int NumberValuesDecoded = 0; - while (NumberValuesDecoded < NumberValues) + int numberValuesDecoded = 0; + while (numberValuesDecoded < numberValues) { - switch (IntEncoded.GetEncoding()) + switch (intEncoded.GetEncoding()) { case EIntegerEncoding.Quint: { - DecodeQuintBlock(BitStream, DecodeIntegerSequence, IntEncoded.NumberBits); - NumberValuesDecoded += 3; + DecodeQuintBlock(bitStream, decodeIntegerSequence, intEncoded.NumberBits); + numberValuesDecoded += 3; break; } case EIntegerEncoding.Trit: { - DecodeTritBlock(BitStream, DecodeIntegerSequence, IntEncoded.NumberBits); - NumberValuesDecoded += 5; + DecodeTritBlock(bitStream, decodeIntegerSequence, intEncoded.NumberBits); + numberValuesDecoded += 5; break; } case EIntegerEncoding.JustBits: { - IntEncoded.BitValue = BitStream.ReadBits(IntEncoded.NumberBits); - DecodeIntegerSequence.Add(IntEncoded); - NumberValuesDecoded++; + intEncoded.BitValue = bitStream.ReadBits(intEncoded.NumberBits); + decodeIntegerSequence.Add(intEncoded); + numberValuesDecoded++; break; } diff --git a/Ryujinx.Graphics/Graphics3d/Texture/LinearSwizzle.cs b/Ryujinx.Graphics/Graphics3d/Texture/LinearSwizzle.cs index e6509baa..fb1bd098 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/LinearSwizzle.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/LinearSwizzle.cs @@ -4,42 +4,42 @@ namespace Ryujinx.Graphics.Texture { class LinearSwizzle : ISwizzle { - private int Pitch; - private int Bpp; + private int _pitch; + private int _bpp; - private int SliceSize; + private int _sliceSize; - public LinearSwizzle(int Pitch, int Bpp, int Width, int Height) + public LinearSwizzle(int pitch, int bpp, int width, int height) { - this.Pitch = Pitch; - this.Bpp = Bpp; - SliceSize = Width * Height * Bpp; + _pitch = pitch; + _bpp = bpp; + _sliceSize = width * height * bpp; } - public void SetMipLevel(int Level) + public void SetMipLevel(int level) { throw new NotImplementedException(); } - public int GetMipOffset(int Level) + public int GetMipOffset(int level) { - if (Level == 1) - return SliceSize; + if (level == 1) + return _sliceSize; throw new NotImplementedException(); } - public int GetImageSize(int MipsCount) + public int GetImageSize(int mipsCount) { - int Size = GetMipOffset(MipsCount); + int size = GetMipOffset(mipsCount); - Size = (Size + 0x1fff) & ~0x1fff; + size = (size + 0x1fff) & ~0x1fff; - return Size; + return size; } - public int GetSwizzleOffset(int X, int Y, int Z) + public int GetSwizzleOffset(int x, int y, int z) { - return Z * SliceSize + X * Bpp + Y * Pitch; + return z * _sliceSize + x * _bpp + y * _pitch; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/TextureFactory.cs b/Ryujinx.Graphics/Graphics3d/Texture/TextureFactory.cs index a2ce86f5..28c90502 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/TextureFactory.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/TextureFactory.cs @@ -6,161 +6,161 @@ namespace Ryujinx.Graphics.Texture { static class TextureFactory { - public static GalImage MakeTexture(NvGpuVmm Vmm, long TicPosition) + public static GalImage MakeTexture(NvGpuVmm vmm, long ticPosition) { - int[] Tic = ReadWords(Vmm, TicPosition, 8); + int[] tic = ReadWords(vmm, ticPosition, 8); - GalImageFormat Format = GetImageFormat(Tic); + GalImageFormat format = GetImageFormat(tic); - GalTextureTarget TextureTarget = (GalTextureTarget)((Tic[4] >> 23) & 0xF); + GalTextureTarget textureTarget = (GalTextureTarget)((tic[4] >> 23) & 0xF); - GalTextureSource XSource = (GalTextureSource)((Tic[0] >> 19) & 7); - GalTextureSource YSource = (GalTextureSource)((Tic[0] >> 22) & 7); - GalTextureSource ZSource = (GalTextureSource)((Tic[0] >> 25) & 7); - GalTextureSource WSource = (GalTextureSource)((Tic[0] >> 28) & 7); + GalTextureSource xSource = (GalTextureSource)((tic[0] >> 19) & 7); + GalTextureSource ySource = (GalTextureSource)((tic[0] >> 22) & 7); + GalTextureSource zSource = (GalTextureSource)((tic[0] >> 25) & 7); + GalTextureSource wSource = (GalTextureSource)((tic[0] >> 28) & 7); - TextureSwizzle Swizzle = (TextureSwizzle)((Tic[2] >> 21) & 7); + TextureSwizzle swizzle = (TextureSwizzle)((tic[2] >> 21) & 7); - int MaxMipmapLevel = (Tic[3] >> 28) & 0xF + 1; + int maxMipmapLevel = (tic[3] >> 28) & 0xF + 1; - GalMemoryLayout Layout; + GalMemoryLayout layout; - if (Swizzle == TextureSwizzle.BlockLinear || - Swizzle == TextureSwizzle.BlockLinearColorKey) + if (swizzle == TextureSwizzle.BlockLinear || + swizzle == TextureSwizzle.BlockLinearColorKey) { - Layout = GalMemoryLayout.BlockLinear; + layout = GalMemoryLayout.BlockLinear; } else { - Layout = GalMemoryLayout.Pitch; + layout = GalMemoryLayout.Pitch; } - int GobBlockHeightLog2 = (Tic[3] >> 3) & 7; - int GobBlockDepthLog2 = (Tic[3] >> 6) & 7; - int TileWidthLog2 = (Tic[3] >> 10) & 7; + int gobBlockHeightLog2 = (tic[3] >> 3) & 7; + int gobBlockDepthLog2 = (tic[3] >> 6) & 7; + int tileWidthLog2 = (tic[3] >> 10) & 7; - int GobBlockHeight = 1 << GobBlockHeightLog2; - int GobBlockDepth = 1 << GobBlockDepthLog2; - int TileWidth = 1 << TileWidthLog2; + int gobBlockHeight = 1 << gobBlockHeightLog2; + int gobBlockDepth = 1 << gobBlockDepthLog2; + int tileWidth = 1 << tileWidthLog2; - int Width = ((Tic[4] >> 0) & 0xffff) + 1; - int Height = ((Tic[5] >> 0) & 0xffff) + 1; - int Depth = ((Tic[5] >> 16) & 0x3fff) + 1; + int width = ((tic[4] >> 0) & 0xffff) + 1; + int height = ((tic[5] >> 0) & 0xffff) + 1; + int depth = ((tic[5] >> 16) & 0x3fff) + 1; - int LayoutCount = 1; + int layoutCount = 1; // TODO: check this - if (ImageUtils.IsArray(TextureTarget)) + if (ImageUtils.IsArray(textureTarget)) { - LayoutCount = Depth; - Depth = 1; + layoutCount = depth; + depth = 1; } - if (TextureTarget == GalTextureTarget.OneD) + if (textureTarget == GalTextureTarget.OneD) { - Height = 1; + height = 1; } - if (TextureTarget == GalTextureTarget.TwoD || TextureTarget == GalTextureTarget.OneD) + if (textureTarget == GalTextureTarget.TwoD || textureTarget == GalTextureTarget.OneD) { - Depth = 1; + depth = 1; } - else if (TextureTarget == GalTextureTarget.CubeMap) + else if (textureTarget == GalTextureTarget.CubeMap) { // FIXME: This is a bit hacky but I guess it's fine for now - LayoutCount = 6; - Depth = 1; + layoutCount = 6; + depth = 1; } - else if (TextureTarget == GalTextureTarget.CubeArray) + else if (textureTarget == GalTextureTarget.CubeArray) { // FIXME: This is a really really hacky but I guess it's fine for now - LayoutCount *= 6; - Depth = 1; + layoutCount *= 6; + depth = 1; } - GalImage Image = new GalImage( - Width, - Height, - Depth, - LayoutCount, - TileWidth, - GobBlockHeight, - GobBlockDepth, - Layout, - Format, - TextureTarget, - MaxMipmapLevel, - XSource, - YSource, - ZSource, - WSource); + GalImage image = new GalImage( + width, + height, + depth, + layoutCount, + tileWidth, + gobBlockHeight, + gobBlockDepth, + layout, + format, + textureTarget, + maxMipmapLevel, + xSource, + ySource, + zSource, + wSource); - if (Layout == GalMemoryLayout.Pitch) + if (layout == GalMemoryLayout.Pitch) { - Image.Pitch = (Tic[3] & 0xffff) << 5; + image.Pitch = (tic[3] & 0xffff) << 5; } - return Image; + return image; } - public static GalTextureSampler MakeSampler(NvGpu Gpu, NvGpuVmm Vmm, long TscPosition) + public static GalTextureSampler MakeSampler(NvGpu gpu, NvGpuVmm vmm, long tscPosition) { - int[] Tsc = ReadWords(Vmm, TscPosition, 8); + int[] tsc = ReadWords(vmm, tscPosition, 8); - GalTextureWrap AddressU = (GalTextureWrap)((Tsc[0] >> 0) & 7); - GalTextureWrap AddressV = (GalTextureWrap)((Tsc[0] >> 3) & 7); - GalTextureWrap AddressP = (GalTextureWrap)((Tsc[0] >> 6) & 7); + GalTextureWrap addressU = (GalTextureWrap)((tsc[0] >> 0) & 7); + GalTextureWrap addressV = (GalTextureWrap)((tsc[0] >> 3) & 7); + GalTextureWrap addressP = (GalTextureWrap)((tsc[0] >> 6) & 7); - bool DepthCompare = ((Tsc[0] >> 9) & 1) == 1; + bool depthCompare = ((tsc[0] >> 9) & 1) == 1; - DepthCompareFunc DepthCompareFunc = (DepthCompareFunc)((Tsc[0] >> 10) & 7); + DepthCompareFunc depthCompareFunc = (DepthCompareFunc)((tsc[0] >> 10) & 7); - GalTextureFilter MagFilter = (GalTextureFilter) ((Tsc[1] >> 0) & 3); - GalTextureFilter MinFilter = (GalTextureFilter) ((Tsc[1] >> 4) & 3); - GalTextureMipFilter MipFilter = (GalTextureMipFilter)((Tsc[1] >> 6) & 3); + GalTextureFilter magFilter = (GalTextureFilter) ((tsc[1] >> 0) & 3); + GalTextureFilter minFilter = (GalTextureFilter) ((tsc[1] >> 4) & 3); + GalTextureMipFilter mipFilter = (GalTextureMipFilter)((tsc[1] >> 6) & 3); - GalColorF BorderColor = new GalColorF( - BitConverter.Int32BitsToSingle(Tsc[4]), - BitConverter.Int32BitsToSingle(Tsc[5]), - BitConverter.Int32BitsToSingle(Tsc[6]), - BitConverter.Int32BitsToSingle(Tsc[7])); + GalColorF borderColor = new GalColorF( + BitConverter.Int32BitsToSingle(tsc[4]), + BitConverter.Int32BitsToSingle(tsc[5]), + BitConverter.Int32BitsToSingle(tsc[6]), + BitConverter.Int32BitsToSingle(tsc[7])); return new GalTextureSampler( - AddressU, - AddressV, - AddressP, - MinFilter, - MagFilter, - MipFilter, - BorderColor, - DepthCompare, - DepthCompareFunc); + addressU, + addressV, + addressP, + minFilter, + magFilter, + mipFilter, + borderColor, + depthCompare, + depthCompareFunc); } - private static GalImageFormat GetImageFormat(int[] Tic) + private static GalImageFormat GetImageFormat(int[] tic) { - GalTextureType RType = (GalTextureType)((Tic[0] >> 7) & 7); - GalTextureType GType = (GalTextureType)((Tic[0] >> 10) & 7); - GalTextureType BType = (GalTextureType)((Tic[0] >> 13) & 7); - GalTextureType AType = (GalTextureType)((Tic[0] >> 16) & 7); + GalTextureType rType = (GalTextureType)((tic[0] >> 7) & 7); + GalTextureType gType = (GalTextureType)((tic[0] >> 10) & 7); + GalTextureType bType = (GalTextureType)((tic[0] >> 13) & 7); + GalTextureType aType = (GalTextureType)((tic[0] >> 16) & 7); - GalTextureFormat Format = (GalTextureFormat)(Tic[0] & 0x7f); + GalTextureFormat format = (GalTextureFormat)(tic[0] & 0x7f); - bool ConvSrgb = ((Tic[4] >> 22) & 1) != 0; + bool convSrgb = ((tic[4] >> 22) & 1) != 0; - return ImageUtils.ConvertTexture(Format, RType, GType, BType, AType, ConvSrgb); + return ImageUtils.ConvertTexture(format, rType, gType, bType, aType, convSrgb); } - private static int[] ReadWords(NvGpuVmm Vmm, long Position, int Count) + private static int[] ReadWords(NvGpuVmm vmm, long position, int count) { - int[] Words = new int[Count]; + int[] words = new int[count]; - for (int Index = 0; Index < Count; Index++, Position += 4) + for (int index = 0; index < count; index++, position += 4) { - Words[Index] = Vmm.ReadInt32(Position); + words[index] = vmm.ReadInt32(position); } - return Words; + return words; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/TextureHelper.cs b/Ryujinx.Graphics/Graphics3d/Texture/TextureHelper.cs index 33ccb0aa..1de81008 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/TextureHelper.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/TextureHelper.cs @@ -7,47 +7,47 @@ namespace Ryujinx.Graphics.Texture { static class TextureHelper { - public static ISwizzle GetSwizzle(GalImage Image) + public static ISwizzle GetSwizzle(GalImage image) { - int BlockWidth = ImageUtils.GetBlockWidth (Image.Format); - int BlockHeight = ImageUtils.GetBlockHeight (Image.Format); - int BlockDepth = ImageUtils.GetBlockDepth (Image.Format); - int BytesPerPixel = ImageUtils.GetBytesPerPixel(Image.Format); + int blockWidth = ImageUtils.GetBlockWidth (image.Format); + int blockHeight = ImageUtils.GetBlockHeight (image.Format); + int blockDepth = ImageUtils.GetBlockDepth (image.Format); + int bytesPerPixel = ImageUtils.GetBytesPerPixel(image.Format); - int Width = BitUtils.DivRoundUp(Image.Width, BlockWidth); - int Height = BitUtils.DivRoundUp(Image.Height, BlockHeight); - int Depth = BitUtils.DivRoundUp(Image.Depth, BlockDepth); + int width = BitUtils.DivRoundUp(image.Width, blockWidth); + int height = BitUtils.DivRoundUp(image.Height, blockHeight); + int depth = BitUtils.DivRoundUp(image.Depth, blockDepth); - if (Image.Layout == GalMemoryLayout.BlockLinear) + if (image.Layout == GalMemoryLayout.BlockLinear) { - int AlignMask = Image.TileWidth * (64 / BytesPerPixel) - 1; + int alignMask = image.TileWidth * (64 / bytesPerPixel) - 1; - Width = (Width + AlignMask) & ~AlignMask; + width = (width + alignMask) & ~alignMask; return new BlockLinearSwizzle( - Width, - Height, - Depth, - Image.GobBlockHeight, - Image.GobBlockDepth, - BytesPerPixel); + width, + height, + depth, + image.GobBlockHeight, + image.GobBlockDepth, + bytesPerPixel); } else { - return new LinearSwizzle(Image.Pitch, BytesPerPixel, Width, Height); + return new LinearSwizzle(image.Pitch, bytesPerPixel, width, height); } } public static (MemoryManager Memory, long Position) GetMemoryAndPosition( - IMemory Memory, - long Position) + IMemory memory, + long position) { - if (Memory is NvGpuVmm Vmm) + if (memory is NvGpuVmm vmm) { - return (Vmm.Memory, Vmm.GetPhysicalAddress(Position)); + return (vmm.Memory, vmm.GetPhysicalAddress(position)); } - return ((MemoryManager)Memory, Position); + return ((MemoryManager)memory, position); } } } diff --git a/Ryujinx.Graphics/Graphics3d/Texture/TextureSwizzle.cs b/Ryujinx.Graphics/Graphics3d/Texture/TextureSwizzle.cs index c67a5367..2cc426ab 100644 --- a/Ryujinx.Graphics/Graphics3d/Texture/TextureSwizzle.cs +++ b/Ryujinx.Graphics/Graphics3d/Texture/TextureSwizzle.cs @@ -2,7 +2,7 @@ namespace Ryujinx.Graphics.Texture { public enum TextureSwizzle { - _1dBuffer = 0, + _1DBuffer = 0, PitchColorKey = 1, Pitch = 2, BlockLinear = 3, diff --git a/Ryujinx.Graphics/Memory/NvGpuVmm.cs b/Ryujinx.Graphics/Memory/NvGpuVmm.cs index 7fdef473..ac1b765a 100644 --- a/Ryujinx.Graphics/Memory/NvGpuVmm.cs +++ b/Ryujinx.Graphics/Memory/NvGpuVmm.cs @@ -8,177 +8,177 @@ namespace Ryujinx.Graphics.Memory { public const long AddrSize = 1L << 40; - private const int PTLvl0Bits = 14; - private const int PTLvl1Bits = 14; - private const int PTPageBits = 12; + private const int PtLvl0Bits = 14; + private const int PtLvl1Bits = 14; + private const int PtPageBits = 12; - private const int PTLvl0Size = 1 << PTLvl0Bits; - private const int PTLvl1Size = 1 << PTLvl1Bits; - public const int PageSize = 1 << PTPageBits; + private const int PtLvl0Size = 1 << PtLvl0Bits; + private const int PtLvl1Size = 1 << PtLvl1Bits; + public const int PageSize = 1 << PtPageBits; - private const int PTLvl0Mask = PTLvl0Size - 1; - private const int PTLvl1Mask = PTLvl1Size - 1; + private const int PtLvl0Mask = PtLvl0Size - 1; + private const int PtLvl1Mask = PtLvl1Size - 1; public const int PageMask = PageSize - 1; - private const int PTLvl0Bit = PTPageBits + PTLvl1Bits; - private const int PTLvl1Bit = PTPageBits; + private const int PtLvl0Bit = PtPageBits + PtLvl1Bits; + private const int PtLvl1Bit = PtPageBits; public MemoryManager Memory { get; private set; } - private NvGpuVmmCache Cache; + private NvGpuVmmCache _cache; private const long PteUnmapped = -1; private const long PteReserved = -2; - private long[][] PageTable; + private long[][] _pageTable; - public NvGpuVmm(MemoryManager Memory) + public NvGpuVmm(MemoryManager memory) { - this.Memory = Memory; + Memory = memory; - Cache = new NvGpuVmmCache(Memory); + _cache = new NvGpuVmmCache(memory); - PageTable = new long[PTLvl0Size][]; + _pageTable = new long[PtLvl0Size][]; } - public long Map(long PA, long VA, long Size) + public long Map(long pa, long va, long size) { - lock (PageTable) + lock (_pageTable) { - for (long Offset = 0; Offset < Size; Offset += PageSize) + for (long offset = 0; offset < size; offset += PageSize) { - SetPte(VA + Offset, PA + Offset); + SetPte(va + offset, pa + offset); } } - return VA; + return va; } - public long Map(long PA, long Size) + public long Map(long pa, long size) { - lock (PageTable) + lock (_pageTable) { - long VA = GetFreePosition(Size); + long va = GetFreePosition(size); - if (VA != -1) + if (va != -1) { - for (long Offset = 0; Offset < Size; Offset += PageSize) + for (long offset = 0; offset < size; offset += PageSize) { - SetPte(VA + Offset, PA + Offset); + SetPte(va + offset, pa + offset); } } - return VA; + return va; } } - public long MapLow(long PA, long Size) + public long MapLow(long pa, long size) { - lock (PageTable) + lock (_pageTable) { - long VA = GetFreePosition(Size, 1, PageSize); + long va = GetFreePosition(size, 1, PageSize); - if (VA != -1 && (ulong)VA <= uint.MaxValue && (ulong)(VA + Size) <= uint.MaxValue) + if (va != -1 && (ulong)va <= uint.MaxValue && (ulong)(va + size) <= uint.MaxValue) { - for (long Offset = 0; Offset < Size; Offset += PageSize) + for (long offset = 0; offset < size; offset += PageSize) { - SetPte(VA + Offset, PA + Offset); + SetPte(va + offset, pa + offset); } } else { - VA = -1; + va = -1; } - return VA; + return va; } } - public long ReserveFixed(long VA, long Size) + public long ReserveFixed(long va, long size) { - lock (PageTable) + lock (_pageTable) { - for (long Offset = 0; Offset < Size; Offset += PageSize) + for (long offset = 0; offset < size; offset += PageSize) { - if (IsPageInUse(VA + Offset)) + if (IsPageInUse(va + offset)) { return -1; } } - for (long Offset = 0; Offset < Size; Offset += PageSize) + for (long offset = 0; offset < size; offset += PageSize) { - SetPte(VA + Offset, PteReserved); + SetPte(va + offset, PteReserved); } } - return VA; + return va; } - public long Reserve(long Size, long Align) + public long Reserve(long size, long align) { - lock (PageTable) + lock (_pageTable) { - long Position = GetFreePosition(Size, Align); + long position = GetFreePosition(size, align); - if (Position != -1) + if (position != -1) { - for (long Offset = 0; Offset < Size; Offset += PageSize) + for (long offset = 0; offset < size; offset += PageSize) { - SetPte(Position + Offset, PteReserved); + SetPte(position + offset, PteReserved); } } - return Position; + return position; } } - public void Free(long VA, long Size) + public void Free(long va, long size) { - lock (PageTable) + lock (_pageTable) { - for (long Offset = 0; Offset < Size; Offset += PageSize) + for (long offset = 0; offset < size; offset += PageSize) { - SetPte(VA + Offset, PteUnmapped); + SetPte(va + offset, PteUnmapped); } } } - private long GetFreePosition(long Size, long Align = 1, long Start = 1L << 32) + private long GetFreePosition(long size, long align = 1, long start = 1L << 32) { //Note: Address 0 is not considered valid by the driver, //when 0 is returned it's considered a mapping error. - long Position = Start; - long FreeSize = 0; + long position = start; + long freeSize = 0; - if (Align < 1) + if (align < 1) { - Align = 1; + align = 1; } - Align = (Align + PageMask) & ~PageMask; + align = (align + PageMask) & ~PageMask; - while (Position + FreeSize < AddrSize) + while (position + freeSize < AddrSize) { - if (!IsPageInUse(Position + FreeSize)) + if (!IsPageInUse(position + freeSize)) { - FreeSize += PageSize; + freeSize += PageSize; - if (FreeSize >= Size) + if (freeSize >= size) { - return Position; + return position; } } else { - Position += FreeSize + PageSize; - FreeSize = 0; + position += freeSize + PageSize; + freeSize = 0; - long Remainder = Position % Align; + long remainder = position % align; - if (Remainder != 0) + if (remainder != 0) { - Position = (Position - Remainder) + Align; + position = (position - remainder) + align; } } } @@ -186,23 +186,23 @@ namespace Ryujinx.Graphics.Memory return -1; } - public long GetPhysicalAddress(long VA) + public long GetPhysicalAddress(long va) { - long BasePos = GetPte(VA); + long basePos = GetPte(va); - if (BasePos < 0) + if (basePos < 0) { return -1; } - return BasePos + (VA & PageMask); + return basePos + (va & PageMask); } - public bool IsRegionFree(long VA, long Size) + public bool IsRegionFree(long va, long size) { - for (long Offset = 0; Offset < Size; Offset += PageSize) + for (long offset = 0; offset < size; offset += PageSize) { - if (IsPageInUse(VA + Offset)) + if (IsPageInUse(va + offset)) { return false; } @@ -211,189 +211,189 @@ namespace Ryujinx.Graphics.Memory return true; } - private bool IsPageInUse(long VA) + private bool IsPageInUse(long va) { - if (VA >> PTLvl0Bits + PTLvl1Bits + PTPageBits != 0) + if (va >> PtLvl0Bits + PtLvl1Bits + PtPageBits != 0) { return false; } - long L0 = (VA >> PTLvl0Bit) & PTLvl0Mask; - long L1 = (VA >> PTLvl1Bit) & PTLvl1Mask; + long l0 = (va >> PtLvl0Bit) & PtLvl0Mask; + long l1 = (va >> PtLvl1Bit) & PtLvl1Mask; - if (PageTable[L0] == null) + if (_pageTable[l0] == null) { return false; } - return PageTable[L0][L1] != PteUnmapped; + return _pageTable[l0][l1] != PteUnmapped; } - private long GetPte(long Position) + private long GetPte(long position) { - long L0 = (Position >> PTLvl0Bit) & PTLvl0Mask; - long L1 = (Position >> PTLvl1Bit) & PTLvl1Mask; + long l0 = (position >> PtLvl0Bit) & PtLvl0Mask; + long l1 = (position >> PtLvl1Bit) & PtLvl1Mask; - if (PageTable[L0] == null) + if (_pageTable[l0] == null) { return -1; } - return PageTable[L0][L1]; + return _pageTable[l0][l1]; } - private void SetPte(long Position, long TgtAddr) + private void SetPte(long position, long tgtAddr) { - long L0 = (Position >> PTLvl0Bit) & PTLvl0Mask; - long L1 = (Position >> PTLvl1Bit) & PTLvl1Mask; + long l0 = (position >> PtLvl0Bit) & PtLvl0Mask; + long l1 = (position >> PtLvl1Bit) & PtLvl1Mask; - if (PageTable[L0] == null) + if (_pageTable[l0] == null) { - PageTable[L0] = new long[PTLvl1Size]; + _pageTable[l0] = new long[PtLvl1Size]; - for (int Index = 0; Index < PTLvl1Size; Index++) + for (int index = 0; index < PtLvl1Size; index++) { - PageTable[L0][Index] = PteUnmapped; + _pageTable[l0][index] = PteUnmapped; } } - PageTable[L0][L1] = TgtAddr; + _pageTable[l0][l1] = tgtAddr; } - public bool IsRegionModified(long PA, long Size, NvGpuBufferType BufferType) + public bool IsRegionModified(long pa, long size, NvGpuBufferType bufferType) { - return Cache.IsRegionModified(PA, Size, BufferType); + return _cache.IsRegionModified(pa, size, bufferType); } - public bool TryGetHostAddress(long Position, long Size, out IntPtr Ptr) + public bool TryGetHostAddress(long position, long size, out IntPtr ptr) { - return Memory.TryGetHostAddress(GetPhysicalAddress(Position), Size, out Ptr); + return Memory.TryGetHostAddress(GetPhysicalAddress(position), size, out ptr); } - public byte ReadByte(long Position) + public byte ReadByte(long position) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadByte(Position); + return Memory.ReadByte(position); } - public ushort ReadUInt16(long Position) + public ushort ReadUInt16(long position) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadUInt16(Position); + return Memory.ReadUInt16(position); } - public uint ReadUInt32(long Position) + public uint ReadUInt32(long position) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadUInt32(Position); + return Memory.ReadUInt32(position); } - public ulong ReadUInt64(long Position) + public ulong ReadUInt64(long position) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadUInt64(Position); + return Memory.ReadUInt64(position); } - public sbyte ReadSByte(long Position) + public sbyte ReadSByte(long position) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadSByte(Position); + return Memory.ReadSByte(position); } - public short ReadInt16(long Position) + public short ReadInt16(long position) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadInt16(Position); + return Memory.ReadInt16(position); } - public int ReadInt32(long Position) + public int ReadInt32(long position) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadInt32(Position); + return Memory.ReadInt32(position); } - public long ReadInt64(long Position) + public long ReadInt64(long position) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadInt64(Position); + return Memory.ReadInt64(position); } - public byte[] ReadBytes(long Position, long Size) + public byte[] ReadBytes(long position, long size) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - return Memory.ReadBytes(Position, Size); + return Memory.ReadBytes(position, size); } - public void WriteByte(long Position, byte Value) + public void WriteByte(long position, byte value) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteByte(Position, Value); + Memory.WriteByte(position, value); } - public void WriteUInt16(long Position, ushort Value) + public void WriteUInt16(long position, ushort value) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteUInt16(Position, Value); + Memory.WriteUInt16(position, value); } - public void WriteUInt32(long Position, uint Value) + public void WriteUInt32(long position, uint value) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteUInt32(Position, Value); + Memory.WriteUInt32(position, value); } - public void WriteUInt64(long Position, ulong Value) + public void WriteUInt64(long position, ulong value) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteUInt64(Position, Value); + Memory.WriteUInt64(position, value); } - public void WriteSByte(long Position, sbyte Value) + public void WriteSByte(long position, sbyte value) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteSByte(Position, Value); + Memory.WriteSByte(position, value); } - public void WriteInt16(long Position, short Value) + public void WriteInt16(long position, short value) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteInt16(Position, Value); + Memory.WriteInt16(position, value); } - public void WriteInt32(long Position, int Value) + public void WriteInt32(long position, int value) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteInt32(Position, Value); + Memory.WriteInt32(position, value); } - public void WriteInt64(long Position, long Value) + public void WriteInt64(long position, long value) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteInt64(Position, Value); + Memory.WriteInt64(position, value); } - public void WriteBytes(long Position, byte[] Data) + public void WriteBytes(long position, byte[] data) { - Position = GetPhysicalAddress(Position); + position = GetPhysicalAddress(position); - Memory.WriteBytes(Position, Data); + Memory.WriteBytes(position, data); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs b/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs index 053c2161..ab5ea288 100644 --- a/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs +++ b/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Graphics.Memory private const long PageSize = MemoryManager.PageSize; private const long PageMask = MemoryManager.PageMask; - private ConcurrentDictionary[] CachedPages; + private ConcurrentDictionary[] _cachedPages; private MemoryManager _memory; @@ -18,7 +18,7 @@ namespace Ryujinx.Graphics.Memory { _memory = memory; - CachedPages = new ConcurrentDictionary[1 << 20]; + _cachedPages = new ConcurrentDictionary[1 << 20]; } public bool IsRegionModified(long position, long size, NvGpuBufferType bufferType) @@ -41,17 +41,17 @@ namespace Ryujinx.Graphics.Memory { long page = _memory.GetPhysicalAddress(va) >> PageBits; - ConcurrentDictionary dictionary = CachedPages[page]; + ConcurrentDictionary dictionary = _cachedPages[page]; if (dictionary == null) { dictionary = new ConcurrentDictionary(); - CachedPages[page] = dictionary; + _cachedPages[page] = dictionary; } else if (modified) { - CachedPages[page].Clear(); + _cachedPages[page].Clear(); } if (dictionary.TryGetValue(pa, out int currBuffMask)) diff --git a/Ryujinx.Graphics/NvGpu.cs b/Ryujinx.Graphics/NvGpu.cs index 4669c899..baac0b2d 100644 --- a/Ryujinx.Graphics/NvGpu.cs +++ b/Ryujinx.Graphics/NvGpu.cs @@ -22,13 +22,13 @@ namespace Ryujinx.Graphics internal NvGpuEngineM2mf EngineM2mf { get; private set; } internal NvGpuEngineP2mf EngineP2mf { get; private set; } - private CdmaProcessor CdmaProcessor; + private CdmaProcessor _cdmaProcessor; internal VideoDecoder VideoDecoder { get; private set; } internal VideoImageComposer VideoImageComposer { get; private set; } - public NvGpu(IGalRenderer Renderer) + public NvGpu(IGalRenderer renderer) { - this.Renderer = Renderer; + Renderer = renderer; ResourceManager = new GpuResourceManager(this); @@ -40,22 +40,22 @@ namespace Ryujinx.Graphics EngineM2mf = new NvGpuEngineM2mf(this); EngineP2mf = new NvGpuEngineP2mf(this); - CdmaProcessor = new CdmaProcessor(this); + _cdmaProcessor = new CdmaProcessor(this); VideoDecoder = new VideoDecoder(this); VideoImageComposer = new VideoImageComposer(this); } - public void PushCommandBuffer(NvGpuVmm Vmm, int[] CmdBuffer) + public void PushCommandBuffer(NvGpuVmm vmm, int[] cmdBuffer) { - lock (CdmaProcessor) + lock (_cdmaProcessor) { - CdmaProcessor.PushCommands(Vmm, CmdBuffer); + _cdmaProcessor.PushCommands(vmm, cmdBuffer); } } public void UninitializeVideoDecoder() { - lock (CdmaProcessor) + lock (_cdmaProcessor) { FFmpegWrapper.Uninitialize(); } diff --git a/Ryujinx.Graphics/QuadHelper.cs b/Ryujinx.Graphics/QuadHelper.cs index d5fea9ab..49c679e3 100644 --- a/Ryujinx.Graphics/QuadHelper.cs +++ b/Ryujinx.Graphics/QuadHelper.cs @@ -4,33 +4,33 @@ namespace Ryujinx.Graphics { static class QuadHelper { - public static int ConvertSizeQuadsToTris(int Size) + public static int ConvertSizeQuadsToTris(int size) { - return Size <= 0 ? 0 : (Size / 4) * 6; + return size <= 0 ? 0 : (size / 4) * 6; } - public static int ConvertSizeQuadStripToTris(int Size) + public static int ConvertSizeQuadStripToTris(int size) { - return Size <= 1 ? 0 : ((Size - 2) / 2) * 6; + return size <= 1 ? 0 : ((size - 2) / 2) * 6; } - public static byte[] ConvertQuadsToTris(byte[] Data, int EntrySize, int Count) + public static byte[] ConvertQuadsToTris(byte[] data, int entrySize, int count) { - int PrimitivesCount = Count / 4; + int primitivesCount = count / 4; - int QuadPrimSize = 4 * EntrySize; - int TrisPrimSize = 6 * EntrySize; + int quadPrimSize = 4 * entrySize; + int trisPrimSize = 6 * entrySize; - byte[] Output = new byte[PrimitivesCount * 6 * EntrySize]; + byte[] output = new byte[primitivesCount * 6 * entrySize]; - for (int Prim = 0; Prim < PrimitivesCount; Prim++) + for (int prim = 0; prim < primitivesCount; prim++) { - void AssignIndex(int Src, int Dst, int CopyCount = 1) + void AssignIndex(int src, int dst, int copyCount = 1) { - Src = Prim * QuadPrimSize + Src * EntrySize; - Dst = Prim * TrisPrimSize + Dst * EntrySize; + src = prim * quadPrimSize + src * entrySize; + dst = prim * trisPrimSize + dst * entrySize; - Buffer.BlockCopy(Data, Src, Output, Dst, CopyCount * EntrySize); + Buffer.BlockCopy(data, src, output, dst, copyCount * entrySize); } //0 1 2 -> 0 1 2. @@ -43,26 +43,26 @@ namespace Ryujinx.Graphics AssignIndex(0, 5); } - return Output; + return output; } - public static byte[] ConvertQuadStripToTris(byte[] Data, int EntrySize, int Count) + public static byte[] ConvertQuadStripToTris(byte[] data, int entrySize, int count) { - int PrimitivesCount = (Count - 2) / 2; + int primitivesCount = (count - 2) / 2; - int QuadPrimSize = 2 * EntrySize; - int TrisPrimSize = 6 * EntrySize; + int quadPrimSize = 2 * entrySize; + int trisPrimSize = 6 * entrySize; - byte[] Output = new byte[PrimitivesCount * 6 * EntrySize]; + byte[] output = new byte[primitivesCount * 6 * entrySize]; - for (int Prim = 0; Prim < PrimitivesCount; Prim++) + for (int prim = 0; prim < primitivesCount; prim++) { - void AssignIndex(int Src, int Dst, int CopyCount = 1) + void AssignIndex(int src, int dst, int copyCount = 1) { - Src = Prim * QuadPrimSize + Src * EntrySize + 2 * EntrySize; - Dst = Prim * TrisPrimSize + Dst * EntrySize; + src = prim * quadPrimSize + src * entrySize + 2 * entrySize; + dst = prim * trisPrimSize + dst * entrySize; - Buffer.BlockCopy(Data, Src, Output, Dst, CopyCount * EntrySize); + Buffer.BlockCopy(data, src, output, dst, copyCount * entrySize); } //-2 -1 0 -> 0 1 2. @@ -75,7 +75,7 @@ namespace Ryujinx.Graphics AssignIndex(-2, 5); } - return Output; + return output; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Texture/TextureInstructionSuffix.cs b/Ryujinx.Graphics/Texture/TextureInstructionSuffix.cs index bcb64af0..65a8f356 100644 --- a/Ryujinx.Graphics/Texture/TextureInstructionSuffix.cs +++ b/Ryujinx.Graphics/Texture/TextureInstructionSuffix.cs @@ -6,14 +6,14 @@ namespace Ryujinx.Graphics.Texture public enum TextureInstructionSuffix { None = 0x00, // No Modifier - LZ = 0x02, // Load LOD Zero - LB = 0x08, // Load Bias - LL = 0x10, // Load LOD - LBA = 0x20, // Load Bias with OperA? Auto? - LLA = 0x40, // Load LOD with OperA? Auto? - DC = 0x80, // Depth Compare + Lz = 0x02, // Load LOD Zero + Lb = 0x08, // Load Bias + Ll = 0x10, // Load LOD + Lba = 0x20, // Load Bias with OperA? Auto? + Lla = 0x40, // Load LOD with OperA? Auto? + Dc = 0x80, // Depth Compare AOffI = 0x100, // Offset - MZ = 0x200, // Multisample Zero? - PTP = 0x400 // ??? + Mz = 0x200, // Multisample Zero? + Ptp = 0x400 // ??? } } diff --git a/Ryujinx.Graphics/VDec/BitStreamWriter.cs b/Ryujinx.Graphics/VDec/BitStreamWriter.cs index 44d07906..db2d39e5 100644 --- a/Ryujinx.Graphics/VDec/BitStreamWriter.cs +++ b/Ryujinx.Graphics/VDec/BitStreamWriter.cs @@ -6,69 +6,69 @@ namespace Ryujinx.Graphics.VDec { private const int BufferSize = 8; - private Stream BaseStream; + private Stream _baseStream; - private int Buffer; - private int BufferPos; + private int _buffer; + private int _bufferPos; - public BitStreamWriter(Stream BaseStream) + public BitStreamWriter(Stream baseStream) { - this.BaseStream = BaseStream; + _baseStream = baseStream; } - public void WriteBit(bool Value) + public void WriteBit(bool value) { - WriteBits(Value ? 1 : 0, 1); + WriteBits(value ? 1 : 0, 1); } - public void WriteBits(int Value, int ValueSize) + public void WriteBits(int value, int valueSize) { - int ValuePos = 0; + int valuePos = 0; - int Remaining = ValueSize; + int remaining = valueSize; - while (Remaining > 0) + while (remaining > 0) { - int CopySize = Remaining; + int copySize = remaining; - int Free = GetFreeBufferBits(); + int free = GetFreeBufferBits(); - if (CopySize > Free) + if (copySize > free) { - CopySize = Free; + copySize = free; } - int Mask = (1 << CopySize) - 1; + int mask = (1 << copySize) - 1; - int SrcShift = (ValueSize - ValuePos) - CopySize; - int DstShift = (BufferSize - BufferPos) - CopySize; + int srcShift = (valueSize - valuePos) - copySize; + int dstShift = (BufferSize - _bufferPos) - copySize; - Buffer |= ((Value >> SrcShift) & Mask) << DstShift; + _buffer |= ((value >> srcShift) & mask) << dstShift; - ValuePos += CopySize; - BufferPos += CopySize; - Remaining -= CopySize; + valuePos += copySize; + _bufferPos += copySize; + remaining -= copySize; } } private int GetFreeBufferBits() { - if (BufferPos == BufferSize) + if (_bufferPos == BufferSize) { Flush(); } - return BufferSize - BufferPos; + return BufferSize - _bufferPos; } public void Flush() { - if (BufferPos != 0) + if (_bufferPos != 0) { - BaseStream.WriteByte((byte)Buffer); + _baseStream.WriteByte((byte)_buffer); - Buffer = 0; - BufferPos = 0; + _buffer = 0; + _bufferPos = 0; } } } diff --git a/Ryujinx.Graphics/VDec/DecoderHelper.cs b/Ryujinx.Graphics/VDec/DecoderHelper.cs index 485bb42b..4f17d8d1 100644 --- a/Ryujinx.Graphics/VDec/DecoderHelper.cs +++ b/Ryujinx.Graphics/VDec/DecoderHelper.cs @@ -4,14 +4,14 @@ namespace Ryujinx.Graphics.VDec { static class DecoderHelper { - public static byte[] Combine(byte[] Arr0, byte[] Arr1) + public static byte[] Combine(byte[] arr0, byte[] arr1) { - byte[] Output = new byte[Arr0.Length + Arr1.Length]; + byte[] output = new byte[arr0.Length + arr1.Length]; - Buffer.BlockCopy(Arr0, 0, Output, 0, Arr0.Length); - Buffer.BlockCopy(Arr1, 0, Output, Arr0.Length, Arr1.Length); + Buffer.BlockCopy(arr0, 0, output, 0, arr0.Length); + Buffer.BlockCopy(arr1, 0, output, arr0.Length, arr1.Length); - return Output; + return output; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/VDec/FFmpeg.cs b/Ryujinx.Graphics/VDec/FFmpeg.cs index 183d0779..ccd01f0d 100644 --- a/Ryujinx.Graphics/VDec/FFmpeg.cs +++ b/Ryujinx.Graphics/VDec/FFmpeg.cs @@ -4,15 +4,15 @@ using System.Runtime.InteropServices; namespace Ryujinx.Graphics.VDec { - unsafe static class FFmpegWrapper + static unsafe class FFmpegWrapper { - private static AVCodec* Codec; - private static AVCodecContext* Context; - private static AVFrame* Frame; - private static SwsContext* ScalerCtx; + private static AVCodec* _codec; + private static AVCodecContext* _context; + private static AVFrame* _frame; + private static SwsContext* _scalerCtx; - private static int ScalerWidth; - private static int ScalerHeight; + private static int _scalerWidth; + private static int _scalerHeight; public static bool IsInitialized { get; private set; } @@ -26,42 +26,42 @@ namespace Ryujinx.Graphics.VDec EnsureCodecInitialized(AVCodecID.AV_CODEC_ID_VP9); } - private static void EnsureCodecInitialized(AVCodecID CodecId) + private static void EnsureCodecInitialized(AVCodecID codecId) { if (IsInitialized) { Uninitialize(); } - Codec = ffmpeg.avcodec_find_decoder(CodecId); - Context = ffmpeg.avcodec_alloc_context3(Codec); - Frame = ffmpeg.av_frame_alloc(); + _codec = ffmpeg.avcodec_find_decoder(codecId); + _context = ffmpeg.avcodec_alloc_context3(_codec); + _frame = ffmpeg.av_frame_alloc(); - ffmpeg.avcodec_open2(Context, Codec, null); + ffmpeg.avcodec_open2(_context, _codec, null); IsInitialized = true; } - public static int DecodeFrame(byte[] Data) + public static int DecodeFrame(byte[] data) { if (!IsInitialized) { throw new InvalidOperationException("Tried to use uninitialized codec!"); } - AVPacket Packet; + AVPacket packet; - ffmpeg.av_init_packet(&Packet); + ffmpeg.av_init_packet(&packet); - fixed (byte* Ptr = Data) + fixed (byte* ptr = data) { - Packet.data = Ptr; - Packet.size = Data.Length; + packet.data = ptr; + packet.size = data.Length; - ffmpeg.avcodec_send_packet(Context, &Packet); + ffmpeg.avcodec_send_packet(_context, &packet); } - return ffmpeg.avcodec_receive_frame(Context, Frame); + return ffmpeg.avcodec_receive_frame(_context, _frame); } public static FFmpegFrame GetFrame() @@ -71,18 +71,18 @@ namespace Ryujinx.Graphics.VDec throw new InvalidOperationException("Tried to use uninitialized codec!"); } - AVFrame ManagedFrame = Marshal.PtrToStructure((IntPtr)Frame); + AVFrame managedFrame = Marshal.PtrToStructure((IntPtr)_frame); - byte*[] Data = ManagedFrame.data.ToArray(); + byte*[] data = managedFrame.data.ToArray(); return new FFmpegFrame() { - Width = ManagedFrame.width, - Height = ManagedFrame.height, + Width = managedFrame.width, + Height = managedFrame.height, - LumaPtr = Data[0], - ChromaBPtr = Data[1], - ChromaRPtr = Data[2] + LumaPtr = data[0], + ChromaBPtr = data[1], + ChromaRPtr = data[2] }; } @@ -93,51 +93,51 @@ namespace Ryujinx.Graphics.VDec throw new InvalidOperationException("Tried to use uninitialized codec!"); } - AVFrame ManagedFrame = Marshal.PtrToStructure((IntPtr)Frame); + AVFrame managedFrame = Marshal.PtrToStructure((IntPtr)_frame); - EnsureScalerSetup(ManagedFrame.width, ManagedFrame.height); + EnsureScalerSetup(managedFrame.width, managedFrame.height); - byte*[] Data = ManagedFrame.data.ToArray(); + byte*[] data = managedFrame.data.ToArray(); - int[] LineSizes = ManagedFrame.linesize.ToArray(); + int[] lineSizes = managedFrame.linesize.ToArray(); - byte[] Dst = new byte[ManagedFrame.width * ManagedFrame.height * 4]; + byte[] dst = new byte[managedFrame.width * managedFrame.height * 4]; - fixed (byte* Ptr = Dst) + fixed (byte* ptr = dst) { - byte*[] DstData = new byte*[] { Ptr }; + byte*[] dstData = new byte*[] { ptr }; - int[] DstLineSizes = new int[] { ManagedFrame.width * 4 }; + int[] dstLineSizes = new int[] { managedFrame.width * 4 }; - ffmpeg.sws_scale(ScalerCtx, Data, LineSizes, 0, ManagedFrame.height, DstData, DstLineSizes); + ffmpeg.sws_scale(_scalerCtx, data, lineSizes, 0, managedFrame.height, dstData, dstLineSizes); } return new FFmpegFrame() { - Width = ManagedFrame.width, - Height = ManagedFrame.height, + Width = managedFrame.width, + Height = managedFrame.height, - Data = Dst + Data = dst }; } - private static void EnsureScalerSetup(int Width, int Height) + private static void EnsureScalerSetup(int width, int height) { - if (Width == 0 || Height == 0) + if (width == 0 || height == 0) { return; } - if (ScalerCtx == null || ScalerWidth != Width || ScalerHeight != Height) + if (_scalerCtx == null || _scalerWidth != width || _scalerHeight != height) { FreeScaler(); - ScalerCtx = ffmpeg.sws_getContext( - Width, Height, AVPixelFormat.AV_PIX_FMT_YUV420P, - Width, Height, AVPixelFormat.AV_PIX_FMT_RGBA, 0, null, null, null); + _scalerCtx = ffmpeg.sws_getContext( + width, height, AVPixelFormat.AV_PIX_FMT_YUV420P, + width, height, AVPixelFormat.AV_PIX_FMT_RGBA, 0, null, null, null); - ScalerWidth = Width; - ScalerHeight = Height; + _scalerWidth = width; + _scalerHeight = height; } } @@ -145,9 +145,9 @@ namespace Ryujinx.Graphics.VDec { if (IsInitialized) { - ffmpeg.av_frame_unref(Frame); - ffmpeg.av_free(Frame); - ffmpeg.avcodec_close(Context); + ffmpeg.av_frame_unref(_frame); + ffmpeg.av_free(_frame); + ffmpeg.avcodec_close(_context); FreeScaler(); @@ -157,11 +157,11 @@ namespace Ryujinx.Graphics.VDec private static void FreeScaler() { - if (ScalerCtx != null) + if (_scalerCtx != null) { - ffmpeg.sws_freeContext(ScalerCtx); + ffmpeg.sws_freeContext(_scalerCtx); - ScalerCtx = null; + _scalerCtx = null; } } } diff --git a/Ryujinx.Graphics/VDec/H264BitStreamWriter.cs b/Ryujinx.Graphics/VDec/H264BitStreamWriter.cs index b388a2aa..b4fad59b 100644 --- a/Ryujinx.Graphics/VDec/H264BitStreamWriter.cs +++ b/Ryujinx.Graphics/VDec/H264BitStreamWriter.cs @@ -4,21 +4,21 @@ namespace Ryujinx.Graphics.VDec { class H264BitStreamWriter : BitStreamWriter { - public H264BitStreamWriter(Stream BaseStream) : base(BaseStream) { } + public H264BitStreamWriter(Stream baseStream) : base(baseStream) { } - public void WriteU(int Value, int ValueSize) + public void WriteU(int value, int valueSize) { - WriteBits(Value, ValueSize); + WriteBits(value, valueSize); } - public void WriteSe(int Value) + public void WriteSe(int value) { - WriteExpGolombCodedInt(Value); + WriteExpGolombCodedInt(value); } - public void WriteUe(int Value) + public void WriteUe(int value) { - WriteExpGolombCodedUInt((uint)Value); + WriteExpGolombCodedUInt((uint)value); } public void End() @@ -28,52 +28,52 @@ namespace Ryujinx.Graphics.VDec Flush(); } - private void WriteExpGolombCodedInt(int Value) + private void WriteExpGolombCodedInt(int value) { - int Sign = Value <= 0 ? 0 : 1; + int sign = value <= 0 ? 0 : 1; - if (Value < 0) + if (value < 0) { - Value = -Value; + value = -value; } - Value = (Value << 1) - Sign; + value = (value << 1) - sign; - WriteExpGolombCodedUInt((uint)Value); + WriteExpGolombCodedUInt((uint)value); } - private void WriteExpGolombCodedUInt(uint Value) + private void WriteExpGolombCodedUInt(uint value) { - int Size = 32 - CountLeadingZeros((int)Value + 1); + int size = 32 - CountLeadingZeros((int)value + 1); - WriteBits(1, Size); + WriteBits(1, size); - Value -= (1u << (Size - 1)) - 1; + value -= (1u << (size - 1)) - 1; - WriteBits((int)Value, Size - 1); + WriteBits((int)value, size - 1); } private static readonly byte[] ClzNibbleTbl = { 4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }; - private static int CountLeadingZeros(int Value) + private static int CountLeadingZeros(int value) { - if (Value == 0) + if (value == 0) { return 32; } - int NibbleIdx = 32; - int PreCount, Count = 0; + int nibbleIdx = 32; + int preCount, count = 0; do { - NibbleIdx -= 4; - PreCount = ClzNibbleTbl[(Value >> NibbleIdx) & 0b1111]; - Count += PreCount; + nibbleIdx -= 4; + preCount = ClzNibbleTbl[(value >> nibbleIdx) & 0b1111]; + count += preCount; } - while (PreCount == 4); + while (preCount == 4); - return Count; + return count; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/VDec/H264Decoder.cs b/Ryujinx.Graphics/VDec/H264Decoder.cs index d5d46713..01085a73 100644 --- a/Ryujinx.Graphics/VDec/H264Decoder.cs +++ b/Ryujinx.Graphics/VDec/H264Decoder.cs @@ -4,195 +4,195 @@ namespace Ryujinx.Graphics.VDec { class H264Decoder { - private int Log2MaxPicOrderCntLsbMinus4; - private bool DeltaPicOrderAlwaysZeroFlag; - private bool FrameMbsOnlyFlag; - private int PicWidthInMbs; - private int PicHeightInMapUnits; - private bool EntropyCodingModeFlag; - private bool BottomFieldPicOrderInFramePresentFlag; - private int NumRefIdxL0DefaultActiveMinus1; - private int NumRefIdxL1DefaultActiveMinus1; - private bool DeblockingFilterControlPresentFlag; - private bool RedundantPicCntPresentFlag; - private bool Transform8x8ModeFlag; - private bool MbAdaptiveFrameFieldFlag; - private bool Direct8x8InferenceFlag; - private bool WeightedPredFlag; - private bool ConstrainedIntraPredFlag; - private bool FieldPicFlag; - private bool BottomFieldFlag; - private int Log2MaxFrameNumMinus4; - private int ChromaFormatIdc; - private int PicOrderCntType; - private int PicInitQpMinus26; - private int ChromaQpIndexOffset; - private int ChromaQpIndexOffset2; - private int WeightedBipredIdc; - private int FrameNumber; - private byte[] ScalingMatrix4; - private byte[] ScalingMatrix8; + private int _log2MaxPicOrderCntLsbMinus4; + private bool _deltaPicOrderAlwaysZeroFlag; + private bool _frameMbsOnlyFlag; + private int _picWidthInMbs; + private int _picHeightInMapUnits; + private bool _entropyCodingModeFlag; + private bool _bottomFieldPicOrderInFramePresentFlag; + private int _numRefIdxL0DefaultActiveMinus1; + private int _numRefIdxL1DefaultActiveMinus1; + private bool _deblockingFilterControlPresentFlag; + private bool _redundantPicCntPresentFlag; + private bool _transform8x8ModeFlag; + private bool _mbAdaptiveFrameFieldFlag; + private bool _direct8x8InferenceFlag; + private bool _weightedPredFlag; + private bool _constrainedIntraPredFlag; + private bool _fieldPicFlag; + private bool _bottomFieldFlag; + private int _log2MaxFrameNumMinus4; + private int _chromaFormatIdc; + private int _picOrderCntType; + private int _picInitQpMinus26; + private int _chromaQpIndexOffset; + private int _chromaQpIndexOffset2; + private int _weightedBipredIdc; + private int _frameNumber; + private byte[] _scalingMatrix4; + private byte[] _scalingMatrix8; - public void Decode(H264ParameterSets Params, H264Matrices Matrices, byte[] FrameData) + public void Decode(H264ParameterSets Params, H264Matrices matrices, byte[] frameData) { - Log2MaxPicOrderCntLsbMinus4 = Params.Log2MaxPicOrderCntLsbMinus4; - DeltaPicOrderAlwaysZeroFlag = Params.DeltaPicOrderAlwaysZeroFlag; - FrameMbsOnlyFlag = Params.FrameMbsOnlyFlag; - PicWidthInMbs = Params.PicWidthInMbs; - PicHeightInMapUnits = Params.PicHeightInMapUnits; - EntropyCodingModeFlag = Params.EntropyCodingModeFlag; - BottomFieldPicOrderInFramePresentFlag = Params.BottomFieldPicOrderInFramePresentFlag; - NumRefIdxL0DefaultActiveMinus1 = Params.NumRefIdxL0DefaultActiveMinus1; - NumRefIdxL1DefaultActiveMinus1 = Params.NumRefIdxL1DefaultActiveMinus1; - DeblockingFilterControlPresentFlag = Params.DeblockingFilterControlPresentFlag; - RedundantPicCntPresentFlag = Params.RedundantPicCntPresentFlag; - Transform8x8ModeFlag = Params.Transform8x8ModeFlag; + _log2MaxPicOrderCntLsbMinus4 = Params.Log2MaxPicOrderCntLsbMinus4; + _deltaPicOrderAlwaysZeroFlag = Params.DeltaPicOrderAlwaysZeroFlag; + _frameMbsOnlyFlag = Params.FrameMbsOnlyFlag; + _picWidthInMbs = Params.PicWidthInMbs; + _picHeightInMapUnits = Params.PicHeightInMapUnits; + _entropyCodingModeFlag = Params.EntropyCodingModeFlag; + _bottomFieldPicOrderInFramePresentFlag = Params.BottomFieldPicOrderInFramePresentFlag; + _numRefIdxL0DefaultActiveMinus1 = Params.NumRefIdxL0DefaultActiveMinus1; + _numRefIdxL1DefaultActiveMinus1 = Params.NumRefIdxL1DefaultActiveMinus1; + _deblockingFilterControlPresentFlag = Params.DeblockingFilterControlPresentFlag; + _redundantPicCntPresentFlag = Params.RedundantPicCntPresentFlag; + _transform8x8ModeFlag = Params.Transform8x8ModeFlag; - MbAdaptiveFrameFieldFlag = ((Params.Flags >> 0) & 1) != 0; - Direct8x8InferenceFlag = ((Params.Flags >> 1) & 1) != 0; - WeightedPredFlag = ((Params.Flags >> 2) & 1) != 0; - ConstrainedIntraPredFlag = ((Params.Flags >> 3) & 1) != 0; - FieldPicFlag = ((Params.Flags >> 5) & 1) != 0; - BottomFieldFlag = ((Params.Flags >> 6) & 1) != 0; + _mbAdaptiveFrameFieldFlag = ((Params.Flags >> 0) & 1) != 0; + _direct8x8InferenceFlag = ((Params.Flags >> 1) & 1) != 0; + _weightedPredFlag = ((Params.Flags >> 2) & 1) != 0; + _constrainedIntraPredFlag = ((Params.Flags >> 3) & 1) != 0; + _fieldPicFlag = ((Params.Flags >> 5) & 1) != 0; + _bottomFieldFlag = ((Params.Flags >> 6) & 1) != 0; - Log2MaxFrameNumMinus4 = (int)(Params.Flags >> 8) & 0xf; - ChromaFormatIdc = (int)(Params.Flags >> 12) & 0x3; - PicOrderCntType = (int)(Params.Flags >> 14) & 0x3; - PicInitQpMinus26 = (int)(Params.Flags >> 16) & 0x3f; - ChromaQpIndexOffset = (int)(Params.Flags >> 22) & 0x1f; - ChromaQpIndexOffset2 = (int)(Params.Flags >> 27) & 0x1f; - WeightedBipredIdc = (int)(Params.Flags >> 32) & 0x3; - FrameNumber = (int)(Params.Flags >> 46) & 0x1ffff; + _log2MaxFrameNumMinus4 = (int)(Params.Flags >> 8) & 0xf; + _chromaFormatIdc = (int)(Params.Flags >> 12) & 0x3; + _picOrderCntType = (int)(Params.Flags >> 14) & 0x3; + _picInitQpMinus26 = (int)(Params.Flags >> 16) & 0x3f; + _chromaQpIndexOffset = (int)(Params.Flags >> 22) & 0x1f; + _chromaQpIndexOffset2 = (int)(Params.Flags >> 27) & 0x1f; + _weightedBipredIdc = (int)(Params.Flags >> 32) & 0x3; + _frameNumber = (int)(Params.Flags >> 46) & 0x1ffff; - PicInitQpMinus26 = (PicInitQpMinus26 << 26) >> 26; - ChromaQpIndexOffset = (ChromaQpIndexOffset << 27) >> 27; - ChromaQpIndexOffset2 = (ChromaQpIndexOffset2 << 27) >> 27; + _picInitQpMinus26 = (_picInitQpMinus26 << 26) >> 26; + _chromaQpIndexOffset = (_chromaQpIndexOffset << 27) >> 27; + _chromaQpIndexOffset2 = (_chromaQpIndexOffset2 << 27) >> 27; - ScalingMatrix4 = Matrices.ScalingMatrix4; - ScalingMatrix8 = Matrices.ScalingMatrix8; + _scalingMatrix4 = matrices.ScalingMatrix4; + _scalingMatrix8 = matrices.ScalingMatrix8; if (FFmpegWrapper.IsInitialized) { - FFmpegWrapper.DecodeFrame(FrameData); + FFmpegWrapper.DecodeFrame(frameData); } else { FFmpegWrapper.H264Initialize(); - FFmpegWrapper.DecodeFrame(DecoderHelper.Combine(EncodeHeader(), FrameData)); + FFmpegWrapper.DecodeFrame(DecoderHelper.Combine(EncodeHeader(), frameData)); } } private byte[] EncodeHeader() { - using (MemoryStream Data = new MemoryStream()) + using (MemoryStream data = new MemoryStream()) { - H264BitStreamWriter Writer = new H264BitStreamWriter(Data); + H264BitStreamWriter writer = new H264BitStreamWriter(data); //Sequence Parameter Set. - Writer.WriteU(1, 24); - Writer.WriteU(0, 1); - Writer.WriteU(3, 2); - Writer.WriteU(7, 5); - Writer.WriteU(100, 8); - Writer.WriteU(0, 8); - Writer.WriteU(31, 8); - Writer.WriteUe(0); - Writer.WriteUe(ChromaFormatIdc); + writer.WriteU(1, 24); + writer.WriteU(0, 1); + writer.WriteU(3, 2); + writer.WriteU(7, 5); + writer.WriteU(100, 8); + writer.WriteU(0, 8); + writer.WriteU(31, 8); + writer.WriteUe(0); + writer.WriteUe(_chromaFormatIdc); - if (ChromaFormatIdc == 3) + if (_chromaFormatIdc == 3) { - Writer.WriteBit(false); + writer.WriteBit(false); } - Writer.WriteUe(0); - Writer.WriteUe(0); - Writer.WriteBit(false); - Writer.WriteBit(false); //Scaling matrix present flag + writer.WriteUe(0); + writer.WriteUe(0); + writer.WriteBit(false); + writer.WriteBit(false); //Scaling matrix present flag - Writer.WriteUe(Log2MaxFrameNumMinus4); - Writer.WriteUe(PicOrderCntType); + writer.WriteUe(_log2MaxFrameNumMinus4); + writer.WriteUe(_picOrderCntType); - if (PicOrderCntType == 0) + if (_picOrderCntType == 0) { - Writer.WriteUe(Log2MaxPicOrderCntLsbMinus4); + writer.WriteUe(_log2MaxPicOrderCntLsbMinus4); } - else if (PicOrderCntType == 1) + else if (_picOrderCntType == 1) { - Writer.WriteBit(DeltaPicOrderAlwaysZeroFlag); + writer.WriteBit(_deltaPicOrderAlwaysZeroFlag); - Writer.WriteSe(0); - Writer.WriteSe(0); - Writer.WriteUe(0); + writer.WriteSe(0); + writer.WriteSe(0); + writer.WriteUe(0); } - int PicHeightInMbs = PicHeightInMapUnits / (FrameMbsOnlyFlag ? 1 : 2); + int picHeightInMbs = _picHeightInMapUnits / (_frameMbsOnlyFlag ? 1 : 2); - Writer.WriteUe(16); - Writer.WriteBit(false); - Writer.WriteUe(PicWidthInMbs - 1); - Writer.WriteUe(PicHeightInMbs - 1); - Writer.WriteBit(FrameMbsOnlyFlag); + writer.WriteUe(16); + writer.WriteBit(false); + writer.WriteUe(_picWidthInMbs - 1); + writer.WriteUe(picHeightInMbs - 1); + writer.WriteBit(_frameMbsOnlyFlag); - if (!FrameMbsOnlyFlag) + if (!_frameMbsOnlyFlag) { - Writer.WriteBit(MbAdaptiveFrameFieldFlag); + writer.WriteBit(_mbAdaptiveFrameFieldFlag); } - Writer.WriteBit(Direct8x8InferenceFlag); - Writer.WriteBit(false); //Frame cropping flag - Writer.WriteBit(false); //VUI parameter present flag + writer.WriteBit(_direct8x8InferenceFlag); + writer.WriteBit(false); //Frame cropping flag + writer.WriteBit(false); //VUI parameter present flag - Writer.End(); + writer.End(); //Picture Parameter Set. - Writer.WriteU(1, 24); - Writer.WriteU(0, 1); - Writer.WriteU(3, 2); - Writer.WriteU(8, 5); + writer.WriteU(1, 24); + writer.WriteU(0, 1); + writer.WriteU(3, 2); + writer.WriteU(8, 5); - Writer.WriteUe(0); - Writer.WriteUe(0); + writer.WriteUe(0); + writer.WriteUe(0); - Writer.WriteBit(EntropyCodingModeFlag); - Writer.WriteBit(false); - Writer.WriteUe(0); - Writer.WriteUe(NumRefIdxL0DefaultActiveMinus1); - Writer.WriteUe(NumRefIdxL1DefaultActiveMinus1); - Writer.WriteBit(WeightedPredFlag); - Writer.WriteU(WeightedBipredIdc, 2); - Writer.WriteSe(PicInitQpMinus26); - Writer.WriteSe(0); - Writer.WriteSe(ChromaQpIndexOffset); - Writer.WriteBit(DeblockingFilterControlPresentFlag); - Writer.WriteBit(ConstrainedIntraPredFlag); - Writer.WriteBit(RedundantPicCntPresentFlag); - Writer.WriteBit(Transform8x8ModeFlag); + writer.WriteBit(_entropyCodingModeFlag); + writer.WriteBit(false); + writer.WriteUe(0); + writer.WriteUe(_numRefIdxL0DefaultActiveMinus1); + writer.WriteUe(_numRefIdxL1DefaultActiveMinus1); + writer.WriteBit(_weightedPredFlag); + writer.WriteU(_weightedBipredIdc, 2); + writer.WriteSe(_picInitQpMinus26); + writer.WriteSe(0); + writer.WriteSe(_chromaQpIndexOffset); + writer.WriteBit(_deblockingFilterControlPresentFlag); + writer.WriteBit(_constrainedIntraPredFlag); + writer.WriteBit(_redundantPicCntPresentFlag); + writer.WriteBit(_transform8x8ModeFlag); - Writer.WriteBit(true); + writer.WriteBit(true); - for (int Index = 0; Index < 6; Index++) + for (int index = 0; index < 6; index++) { - Writer.WriteBit(true); + writer.WriteBit(true); - WriteScalingList(Writer, ScalingMatrix4, Index * 16, 16); + WriteScalingList(writer, _scalingMatrix4, index * 16, 16); } - if (Transform8x8ModeFlag) + if (_transform8x8ModeFlag) { - for (int Index = 0; Index < 2; Index++) + for (int index = 0; index < 2; index++) { - Writer.WriteBit(true); + writer.WriteBit(true); - WriteScalingList(Writer, ScalingMatrix8, Index * 64, 64); + WriteScalingList(writer, _scalingMatrix8, index * 64, 64); } } - Writer.WriteSe(ChromaQpIndexOffset2); + writer.WriteSe(_chromaQpIndexOffset2); - Writer.End(); + writer.End(); - return Data.ToArray(); + return data.ToArray(); } } @@ -217,21 +217,21 @@ namespace Ryujinx.Graphics.VDec 3 + 1 * 4, 3 + 2 * 4, 2 + 3 * 4, 3 + 3 * 4 }; - private static void WriteScalingList(H264BitStreamWriter Writer, byte[] List, int Start, int Count) + private static void WriteScalingList(H264BitStreamWriter writer, byte[] list, int start, int count) { - byte[] Scan = Count == 16 ? ZigZagScan : ZigZagDirect; + byte[] scan = count == 16 ? ZigZagScan : ZigZagDirect; - int LastScale = 8; + int lastScale = 8; - for (int Index = 0; Index < Count; Index++) + for (int index = 0; index < count; index++) { - byte Value = List[Start + Scan[Index]]; + byte value = list[start + scan[index]]; - int DeltaScale = Value - LastScale; + int deltaScale = value - lastScale; - Writer.WriteSe(DeltaScale); + writer.WriteSe(deltaScale); - LastScale = Value; + lastScale = value; } } } diff --git a/Ryujinx.Graphics/VDec/VideoDecoder.cs b/Ryujinx.Graphics/VDec/VideoDecoder.cs index be53b1a0..2be47a30 100644 --- a/Ryujinx.Graphics/VDec/VideoDecoder.cs +++ b/Ryujinx.Graphics/VDec/VideoDecoder.cs @@ -9,124 +9,124 @@ namespace Ryujinx.Graphics.VDec { unsafe class VideoDecoder { - private NvGpu Gpu; + private NvGpu _gpu; - private H264Decoder H264Decoder; - private Vp9Decoder Vp9Decoder; + private H264Decoder _h264Decoder; + private Vp9Decoder _vp9Decoder; - private VideoCodec CurrentVideoCodec; + private VideoCodec _currentVideoCodec; - private long DecoderContextAddress; - private long FrameDataAddress; - private long VpxCurrLumaAddress; - private long VpxRef0LumaAddress; - private long VpxRef1LumaAddress; - private long VpxRef2LumaAddress; - private long VpxCurrChromaAddress; - private long VpxRef0ChromaAddress; - private long VpxRef1ChromaAddress; - private long VpxRef2ChromaAddress; - private long VpxProbTablesAddress; + private long _decoderContextAddress; + private long _frameDataAddress; + private long _vpxCurrLumaAddress; + private long _vpxRef0LumaAddress; + private long _vpxRef1LumaAddress; + private long _vpxRef2LumaAddress; + private long _vpxCurrChromaAddress; + private long _vpxRef0ChromaAddress; + private long _vpxRef1ChromaAddress; + private long _vpxRef2ChromaAddress; + private long _vpxProbTablesAddress; - public VideoDecoder(NvGpu Gpu) + public VideoDecoder(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; - H264Decoder = new H264Decoder(); - Vp9Decoder = new Vp9Decoder(); + _h264Decoder = new H264Decoder(); + _vp9Decoder = new Vp9Decoder(); } - public void Process(NvGpuVmm Vmm, int MethodOffset, int[] Arguments) + public void Process(NvGpuVmm vmm, int methodOffset, int[] arguments) { - VideoDecoderMeth Method = (VideoDecoderMeth)MethodOffset; + VideoDecoderMeth method = (VideoDecoderMeth)methodOffset; - switch (Method) + switch (method) { - case VideoDecoderMeth.SetVideoCodec: SetVideoCodec (Vmm, Arguments); break; - case VideoDecoderMeth.Execute: Execute (Vmm, Arguments); break; - case VideoDecoderMeth.SetDecoderCtxAddr: SetDecoderCtxAddr (Vmm, Arguments); break; - case VideoDecoderMeth.SetFrameDataAddr: SetFrameDataAddr (Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxCurrLumaAddr: SetVpxCurrLumaAddr (Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxRef0LumaAddr: SetVpxRef0LumaAddr (Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxRef1LumaAddr: SetVpxRef1LumaAddr (Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxRef2LumaAddr: SetVpxRef2LumaAddr (Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxCurrChromaAddr: SetVpxCurrChromaAddr(Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxRef0ChromaAddr: SetVpxRef0ChromaAddr(Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxRef1ChromaAddr: SetVpxRef1ChromaAddr(Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxRef2ChromaAddr: SetVpxRef2ChromaAddr(Vmm, Arguments); break; - case VideoDecoderMeth.SetVpxProbTablesAddr: SetVpxProbTablesAddr(Vmm, Arguments); break; + case VideoDecoderMeth.SetVideoCodec: SetVideoCodec (vmm, arguments); break; + case VideoDecoderMeth.Execute: Execute (vmm, arguments); break; + case VideoDecoderMeth.SetDecoderCtxAddr: SetDecoderCtxAddr (vmm, arguments); break; + case VideoDecoderMeth.SetFrameDataAddr: SetFrameDataAddr (vmm, arguments); break; + case VideoDecoderMeth.SetVpxCurrLumaAddr: SetVpxCurrLumaAddr (vmm, arguments); break; + case VideoDecoderMeth.SetVpxRef0LumaAddr: SetVpxRef0LumaAddr (vmm, arguments); break; + case VideoDecoderMeth.SetVpxRef1LumaAddr: SetVpxRef1LumaAddr (vmm, arguments); break; + case VideoDecoderMeth.SetVpxRef2LumaAddr: SetVpxRef2LumaAddr (vmm, arguments); break; + case VideoDecoderMeth.SetVpxCurrChromaAddr: SetVpxCurrChromaAddr(vmm, arguments); break; + case VideoDecoderMeth.SetVpxRef0ChromaAddr: SetVpxRef0ChromaAddr(vmm, arguments); break; + case VideoDecoderMeth.SetVpxRef1ChromaAddr: SetVpxRef1ChromaAddr(vmm, arguments); break; + case VideoDecoderMeth.SetVpxRef2ChromaAddr: SetVpxRef2ChromaAddr(vmm, arguments); break; + case VideoDecoderMeth.SetVpxProbTablesAddr: SetVpxProbTablesAddr(vmm, arguments); break; } } - private void SetVideoCodec(NvGpuVmm Vmm, int[] Arguments) + private void SetVideoCodec(NvGpuVmm vmm, int[] arguments) { - CurrentVideoCodec = (VideoCodec)Arguments[0]; + _currentVideoCodec = (VideoCodec)arguments[0]; } - private void Execute(NvGpuVmm Vmm, int[] Arguments) + private void Execute(NvGpuVmm vmm, int[] arguments) { - if (CurrentVideoCodec == VideoCodec.H264) + if (_currentVideoCodec == VideoCodec.H264) { - int FrameDataSize = Vmm.ReadInt32(DecoderContextAddress + 0x48); + int frameDataSize = vmm.ReadInt32(_decoderContextAddress + 0x48); - H264ParameterSets Params = MemoryHelper.Read(Vmm.Memory, Vmm.GetPhysicalAddress(DecoderContextAddress + 0x58)); + H264ParameterSets Params = MemoryHelper.Read(vmm.Memory, vmm.GetPhysicalAddress(_decoderContextAddress + 0x58)); - H264Matrices Matrices = new H264Matrices() + H264Matrices matrices = new H264Matrices() { - ScalingMatrix4 = Vmm.ReadBytes(DecoderContextAddress + 0x1c0, 6 * 16), - ScalingMatrix8 = Vmm.ReadBytes(DecoderContextAddress + 0x220, 2 * 64) + ScalingMatrix4 = vmm.ReadBytes(_decoderContextAddress + 0x1c0, 6 * 16), + ScalingMatrix8 = vmm.ReadBytes(_decoderContextAddress + 0x220, 2 * 64) }; - byte[] FrameData = Vmm.ReadBytes(FrameDataAddress, FrameDataSize); + byte[] frameData = vmm.ReadBytes(_frameDataAddress, frameDataSize); - H264Decoder.Decode(Params, Matrices, FrameData); + _h264Decoder.Decode(Params, matrices, frameData); } - else if (CurrentVideoCodec == VideoCodec.Vp9) + else if (_currentVideoCodec == VideoCodec.Vp9) { - int FrameDataSize = Vmm.ReadInt32(DecoderContextAddress + 0x30); + int frameDataSize = vmm.ReadInt32(_decoderContextAddress + 0x30); - Vp9FrameKeys Keys = new Vp9FrameKeys() + Vp9FrameKeys keys = new Vp9FrameKeys() { - CurrKey = Vmm.GetPhysicalAddress(VpxCurrLumaAddress), - Ref0Key = Vmm.GetPhysicalAddress(VpxRef0LumaAddress), - Ref1Key = Vmm.GetPhysicalAddress(VpxRef1LumaAddress), - Ref2Key = Vmm.GetPhysicalAddress(VpxRef2LumaAddress) + CurrKey = vmm.GetPhysicalAddress(_vpxCurrLumaAddress), + Ref0Key = vmm.GetPhysicalAddress(_vpxRef0LumaAddress), + Ref1Key = vmm.GetPhysicalAddress(_vpxRef1LumaAddress), + Ref2Key = vmm.GetPhysicalAddress(_vpxRef2LumaAddress) }; - Vp9FrameHeader Header = MemoryHelper.Read(Vmm.Memory, Vmm.GetPhysicalAddress(DecoderContextAddress + 0x48)); + Vp9FrameHeader header = MemoryHelper.Read(vmm.Memory, vmm.GetPhysicalAddress(_decoderContextAddress + 0x48)); - Vp9ProbabilityTables Probs = new Vp9ProbabilityTables() + Vp9ProbabilityTables probs = new Vp9ProbabilityTables() { - SegmentationTreeProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x387, 0x7), - SegmentationPredProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x38e, 0x3), - Tx8x8Probs = Vmm.ReadBytes(VpxProbTablesAddress + 0x470, 0x2), - Tx16x16Probs = Vmm.ReadBytes(VpxProbTablesAddress + 0x472, 0x4), - Tx32x32Probs = Vmm.ReadBytes(VpxProbTablesAddress + 0x476, 0x6), - CoefProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x5a0, 0x900), - SkipProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x537, 0x3), - InterModeProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x400, 0x1c), - InterpFilterProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x52a, 0x8), - IsInterProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x41c, 0x4), - CompModeProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x532, 0x5), - SingleRefProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x580, 0xa), - CompRefProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x58a, 0x5), - YModeProbs0 = Vmm.ReadBytes(VpxProbTablesAddress + 0x480, 0x20), - YModeProbs1 = Vmm.ReadBytes(VpxProbTablesAddress + 0x47c, 0x4), - PartitionProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x4e0, 0x40), - MvJointProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x53b, 0x3), - MvSignProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x53e, 0x3), - MvClassProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x54c, 0x14), - MvClass0BitProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x540, 0x3), - MvBitsProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x56c, 0x14), - MvClass0FrProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x560, 0xc), - MvFrProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x542, 0x6), - MvClass0HpProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x548, 0x2), - MvHpProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x54a, 0x2) + SegmentationTreeProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x387, 0x7), + SegmentationPredProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x38e, 0x3), + Tx8x8Probs = vmm.ReadBytes(_vpxProbTablesAddress + 0x470, 0x2), + Tx16x16Probs = vmm.ReadBytes(_vpxProbTablesAddress + 0x472, 0x4), + Tx32x32Probs = vmm.ReadBytes(_vpxProbTablesAddress + 0x476, 0x6), + CoefProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x5a0, 0x900), + SkipProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x537, 0x3), + InterModeProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x400, 0x1c), + InterpFilterProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x52a, 0x8), + IsInterProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x41c, 0x4), + CompModeProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x532, 0x5), + SingleRefProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x580, 0xa), + CompRefProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x58a, 0x5), + YModeProbs0 = vmm.ReadBytes(_vpxProbTablesAddress + 0x480, 0x20), + YModeProbs1 = vmm.ReadBytes(_vpxProbTablesAddress + 0x47c, 0x4), + PartitionProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x4e0, 0x40), + MvJointProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x53b, 0x3), + MvSignProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x53e, 0x3), + MvClassProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x54c, 0x14), + MvClass0BitProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x540, 0x3), + MvBitsProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x56c, 0x14), + MvClass0FrProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x560, 0xc), + MvFrProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x542, 0x6), + MvClass0HpProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x548, 0x2), + MvHpProbs = vmm.ReadBytes(_vpxProbTablesAddress + 0x54a, 0x2) }; - byte[] FrameData = Vmm.ReadBytes(FrameDataAddress, FrameDataSize); + byte[] frameData = vmm.ReadBytes(_frameDataAddress, frameDataSize); - Vp9Decoder.Decode(Keys, Header, Probs, FrameData); + _vp9Decoder.Decode(keys, header, probs, frameData); } else { @@ -134,148 +134,148 @@ namespace Ryujinx.Graphics.VDec } } - private void SetDecoderCtxAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetDecoderCtxAddr(NvGpuVmm vmm, int[] arguments) { - DecoderContextAddress = GetAddress(Arguments); + _decoderContextAddress = GetAddress(arguments); } - private void SetFrameDataAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetFrameDataAddr(NvGpuVmm vmm, int[] arguments) { - FrameDataAddress = GetAddress(Arguments); + _frameDataAddress = GetAddress(arguments); } - private void SetVpxCurrLumaAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxCurrLumaAddr(NvGpuVmm vmm, int[] arguments) { - VpxCurrLumaAddress = GetAddress(Arguments); + _vpxCurrLumaAddress = GetAddress(arguments); } - private void SetVpxRef0LumaAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxRef0LumaAddr(NvGpuVmm vmm, int[] arguments) { - VpxRef0LumaAddress = GetAddress(Arguments); + _vpxRef0LumaAddress = GetAddress(arguments); } - private void SetVpxRef1LumaAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxRef1LumaAddr(NvGpuVmm vmm, int[] arguments) { - VpxRef1LumaAddress = GetAddress(Arguments); + _vpxRef1LumaAddress = GetAddress(arguments); } - private void SetVpxRef2LumaAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxRef2LumaAddr(NvGpuVmm vmm, int[] arguments) { - VpxRef2LumaAddress = GetAddress(Arguments); + _vpxRef2LumaAddress = GetAddress(arguments); } - private void SetVpxCurrChromaAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxCurrChromaAddr(NvGpuVmm vmm, int[] arguments) { - VpxCurrChromaAddress = GetAddress(Arguments); + _vpxCurrChromaAddress = GetAddress(arguments); } - private void SetVpxRef0ChromaAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxRef0ChromaAddr(NvGpuVmm vmm, int[] arguments) { - VpxRef0ChromaAddress = GetAddress(Arguments); + _vpxRef0ChromaAddress = GetAddress(arguments); } - private void SetVpxRef1ChromaAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxRef1ChromaAddr(NvGpuVmm vmm, int[] arguments) { - VpxRef1ChromaAddress = GetAddress(Arguments); + _vpxRef1ChromaAddress = GetAddress(arguments); } - private void SetVpxRef2ChromaAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxRef2ChromaAddr(NvGpuVmm vmm, int[] arguments) { - VpxRef2ChromaAddress = GetAddress(Arguments); + _vpxRef2ChromaAddress = GetAddress(arguments); } - private void SetVpxProbTablesAddr(NvGpuVmm Vmm, int[] Arguments) + private void SetVpxProbTablesAddr(NvGpuVmm vmm, int[] arguments) { - VpxProbTablesAddress = GetAddress(Arguments); + _vpxProbTablesAddress = GetAddress(arguments); } - private static long GetAddress(int[] Arguments) + private static long GetAddress(int[] arguments) { - return (long)(uint)Arguments[0] << 8; + return (long)(uint)arguments[0] << 8; } - internal void CopyPlanes(NvGpuVmm Vmm, SurfaceOutputConfig OutputConfig) + internal void CopyPlanes(NvGpuVmm vmm, SurfaceOutputConfig outputConfig) { - switch (OutputConfig.PixelFormat) + switch (outputConfig.PixelFormat) { - case SurfacePixelFormat.RGBA8: CopyPlanesRgba8 (Vmm, OutputConfig); break; - case SurfacePixelFormat.YUV420P: CopyPlanesYuv420p(Vmm, OutputConfig); break; + case SurfacePixelFormat.Rgba8: CopyPlanesRgba8 (vmm, outputConfig); break; + case SurfacePixelFormat.Yuv420P: CopyPlanesYuv420P(vmm, outputConfig); break; - default: ThrowUnimplementedPixelFormat(OutputConfig.PixelFormat); break; + default: ThrowUnimplementedPixelFormat(outputConfig.PixelFormat); break; } } - private void CopyPlanesRgba8(NvGpuVmm Vmm, SurfaceOutputConfig OutputConfig) + private void CopyPlanesRgba8(NvGpuVmm vmm, SurfaceOutputConfig outputConfig) { - FFmpegFrame Frame = FFmpegWrapper.GetFrameRgba(); + FFmpegFrame frame = FFmpegWrapper.GetFrameRgba(); - if ((Frame.Width | Frame.Height) == 0) + if ((frame.Width | frame.Height) == 0) { return; } - GalImage Image = new GalImage( - OutputConfig.SurfaceWidth, - OutputConfig.SurfaceHeight, 1, 1, 1, - OutputConfig.GobBlockHeight, 1, + GalImage image = new GalImage( + outputConfig.SurfaceWidth, + outputConfig.SurfaceHeight, 1, 1, 1, + outputConfig.GobBlockHeight, 1, GalMemoryLayout.BlockLinear, - GalImageFormat.RGBA8 | GalImageFormat.Unorm, + GalImageFormat.Rgba8 | GalImageFormat.Unorm, GalTextureTarget.TwoD); - ImageUtils.WriteTexture(Vmm, Image, Vmm.GetPhysicalAddress(OutputConfig.SurfaceLumaAddress), Frame.Data); + ImageUtils.WriteTexture(vmm, image, vmm.GetPhysicalAddress(outputConfig.SurfaceLumaAddress), frame.Data); } - private void CopyPlanesYuv420p(NvGpuVmm Vmm, SurfaceOutputConfig OutputConfig) + private void CopyPlanesYuv420P(NvGpuVmm vmm, SurfaceOutputConfig outputConfig) { - FFmpegFrame Frame = FFmpegWrapper.GetFrame(); + FFmpegFrame frame = FFmpegWrapper.GetFrame(); - if ((Frame.Width | Frame.Height) == 0) + if ((frame.Width | frame.Height) == 0) { return; } - int HalfSrcWidth = Frame.Width / 2; + int halfSrcWidth = frame.Width / 2; - int HalfWidth = Frame.Width / 2; - int HalfHeight = Frame.Height / 2; + int halfWidth = frame.Width / 2; + int halfHeight = frame.Height / 2; - int AlignedWidth = (OutputConfig.SurfaceWidth + 0xff) & ~0xff; + int alignedWidth = (outputConfig.SurfaceWidth + 0xff) & ~0xff; - for (int Y = 0; Y < Frame.Height; Y++) + for (int y = 0; y < frame.Height; y++) { - int Src = Y * Frame.Width; - int Dst = Y * AlignedWidth; + int src = y * frame.Width; + int dst = y * alignedWidth; - int Size = Frame.Width; + int size = frame.Width; - for (int Offset = 0; Offset < Size; Offset++) + for (int offset = 0; offset < size; offset++) { - Vmm.WriteByte(OutputConfig.SurfaceLumaAddress + Dst + Offset, *(Frame.LumaPtr + Src + Offset)); + vmm.WriteByte(outputConfig.SurfaceLumaAddress + dst + offset, *(frame.LumaPtr + src + offset)); } } //Copy chroma data from both channels with interleaving. - for (int Y = 0; Y < HalfHeight; Y++) + for (int y = 0; y < halfHeight; y++) { - int Src = Y * HalfSrcWidth; - int Dst = Y * AlignedWidth; + int src = y * halfSrcWidth; + int dst = y * alignedWidth; - for (int X = 0; X < HalfWidth; X++) + for (int x = 0; x < halfWidth; x++) { - Vmm.WriteByte(OutputConfig.SurfaceChromaUAddress + Dst + X * 2 + 0, *(Frame.ChromaBPtr + Src + X)); - Vmm.WriteByte(OutputConfig.SurfaceChromaUAddress + Dst + X * 2 + 1, *(Frame.ChromaRPtr + Src + X)); + vmm.WriteByte(outputConfig.SurfaceChromaUAddress + dst + x * 2 + 0, *(frame.ChromaBPtr + src + x)); + vmm.WriteByte(outputConfig.SurfaceChromaUAddress + dst + x * 2 + 1, *(frame.ChromaRPtr + src + x)); } } } private void ThrowUnimplementedCodec() { - throw new NotImplementedException("Codec \"" + CurrentVideoCodec + "\" is not supported!"); + throw new NotImplementedException("Codec \"" + _currentVideoCodec + "\" is not supported!"); } - private void ThrowUnimplementedPixelFormat(SurfacePixelFormat PixelFormat) + private void ThrowUnimplementedPixelFormat(SurfacePixelFormat pixelFormat) { - throw new NotImplementedException("Pixel format \"" + PixelFormat + "\" is not supported!"); + throw new NotImplementedException("Pixel format \"" + pixelFormat + "\" is not supported!"); } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/VDec/Vp9Decoder.cs b/Ryujinx.Graphics/VDec/Vp9Decoder.cs index 6e3fc1f2..d77bc6c4 100644 --- a/Ryujinx.Graphics/VDec/Vp9Decoder.cs +++ b/Ryujinx.Graphics/VDec/Vp9Decoder.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Graphics.VDec private byte[] DefaultTx16x16Probs = new byte[] { 20, 152, 15, 101 }; private byte[] DefaultTx32x32Probs = new byte[] { 3, 136, 37, 5, 52, 13 }; - private byte[] DefaultCoefProbs = new byte[] + private byte[] _defaultCoefProbs = new byte[] { 195, 29, 183, 0, 84, 49, 136, 0, 8, 42, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 107, 169, 0, 35, 99, 159, 0, @@ -181,39 +181,39 @@ namespace Ryujinx.Graphics.VDec 1, 115, 166, 0, 1, 84, 121, 0, 1, 51, 67, 0, 1, 16, 6, 0 }; - private byte[] DefaultSkipProbs = new byte[] { 192, 128, 64 }; + private byte[] _defaultSkipProbs = new byte[] { 192, 128, 64 }; - private byte[] DefaultInterModeProbs = new byte[] + private byte[] _defaultInterModeProbs = new byte[] { 2, 173, 34, 0, 7, 145, 85, 0, 7, 166, 63, 0, 7, 94, 66, 0, 8, 64, 46, 0, 17, 81, 31, 0, 25, 29, 30, 0 }; - private byte[] DefaultInterpFilterProbs = new byte[] + private byte[] _defaultInterpFilterProbs = new byte[] { 235, 162, 36, 255, 34, 3, 149, 144 }; - private byte[] DefaultIsInterProbs = new byte[] { 9, 102, 187, 225 }; + private byte[] _defaultIsInterProbs = new byte[] { 9, 102, 187, 225 }; - private byte[] DefaultCompModeProbs = new byte[] { 239, 183, 119, 96, 41 }; + private byte[] _defaultCompModeProbs = new byte[] { 239, 183, 119, 96, 41 }; - private byte[] DefaultSingleRefProbs = new byte[] + private byte[] _defaultSingleRefProbs = new byte[] { 33, 16, 77, 74, 142, 142, 172, 170, 238, 247 }; - private byte[] DefaultCompRefProbs = new byte[] { 50, 126, 123, 221, 226 }; + private byte[] _defaultCompRefProbs = new byte[] { 50, 126, 123, 221, 226 }; - private byte[] DefaultYModeProbs0 = new byte[] + private byte[] _defaultYModeProbs0 = new byte[] { 65, 32, 18, 144, 162, 194, 41, 51, 132, 68, 18, 165, 217, 196, 45, 40, 173, 80, 19, 176, 240, 193, 64, 35, 221, 135, 38, 194, 248, 121, 96, 85 }; - private byte[] DefaultYModeProbs1 = new byte[] { 98, 78, 46, 29 }; + private byte[] _defaultYModeProbs1 = new byte[] { 98, 78, 46, 29 }; - private byte[] DefaultPartitionProbs = new byte[] + private byte[] _defaultPartitionProbs = new byte[] { 199, 122, 141, 0, 147, 63, 159, 0, 148, 133, 118, 0, 121, 104, 114, 0, 174, 73, 87, 0, 92, 41, 83, 0, 82, 99, 50, 0, 53, 39, 39, 0, @@ -221,184 +221,184 @@ namespace Ryujinx.Graphics.VDec 222, 34, 30, 0, 72, 16, 44, 0, 58, 32, 12, 0, 10, 7, 6, 0 }; - private byte[] DefaultMvJointProbs = new byte[] { 32, 64, 96 }; + private byte[] _defaultMvJointProbs = new byte[] { 32, 64, 96 }; - private byte[] DefaultMvSignProbs = new byte[] { 128, 128 }; + private byte[] _defaultMvSignProbs = new byte[] { 128, 128 }; - private byte[] DefaultMvClassProbs = new byte[] + private byte[] _defaultMvClassProbs = new byte[] { 224, 144, 192, 168, 192, 176, 192, 198, 198, 245, 216, 128, 176, 160, 176, 176, 192, 198, 198, 208 }; - private byte[] DefaultMvClass0BitProbs = new byte[] { 216, 208 }; + private byte[] _defaultMvClass0BitProbs = new byte[] { 216, 208 }; - private byte[] DefaultMvBitsProbs = new byte[] + private byte[] _defaultMvBitsProbs = new byte[] { 136, 140, 148, 160, 176, 192, 224, 234, 234, 240, 136, 140, 148, 160, 176, 192, 224, 234, 234, 240 }; - private byte[] DefaultMvClass0FrProbs = new byte[] + private byte[] _defaultMvClass0FrProbs = new byte[] { 128, 128, 64, 96, 112, 64, 128, 128, 64, 96, 112, 64 }; - private byte[] DefaultMvFrProbs = new byte[] { 64, 96, 64, 64, 96, 64 }; + private byte[] _defaultMvFrProbs = new byte[] { 64, 96, 64, 64, 96, 64 }; - private byte[] DefaultMvClass0HpProbs = new byte[] { 160, 160 }; + private byte[] _defaultMvClass0HpProbs = new byte[] { 160, 160 }; - private byte[] DefaultMvHpProbs = new byte[] { 128, 128 }; + private byte[] _defaultMvHpProbs = new byte[] { 128, 128 }; - private sbyte[] LoopFilterRefDeltas; - private sbyte[] LoopFilterModeDeltas; + private sbyte[] _loopFilterRefDeltas; + private sbyte[] _loopFilterModeDeltas; - private LinkedList FrameSlotByLastUse; + private LinkedList _frameSlotByLastUse; - private Dictionary> CachedRefFrames; + private Dictionary> _cachedRefFrames; public Vp9Decoder() { - LoopFilterRefDeltas = new sbyte[4]; - LoopFilterModeDeltas = new sbyte[2]; + _loopFilterRefDeltas = new sbyte[4]; + _loopFilterModeDeltas = new sbyte[2]; - FrameSlotByLastUse = new LinkedList(); + _frameSlotByLastUse = new LinkedList(); - for (int Slot = 0; Slot < 8; Slot++) + for (int slot = 0; slot < 8; slot++) { - FrameSlotByLastUse.AddFirst(Slot); + _frameSlotByLastUse.AddFirst(slot); } - CachedRefFrames = new Dictionary>(); + _cachedRefFrames = new Dictionary>(); } public void Decode( - Vp9FrameKeys Keys, - Vp9FrameHeader Header, - Vp9ProbabilityTables Probs, - byte[] FrameData) + Vp9FrameKeys keys, + Vp9FrameHeader header, + Vp9ProbabilityTables probs, + byte[] frameData) { - bool IsKeyFrame = ((Header.Flags >> 0) & 1) != 0; - bool LastIsKeyFrame = ((Header.Flags >> 1) & 1) != 0; - bool FrameSizeChanged = ((Header.Flags >> 2) & 1) != 0; - bool ErrorResilientMode = ((Header.Flags >> 3) & 1) != 0; - bool LastShowFrame = ((Header.Flags >> 4) & 1) != 0; - bool IsFrameIntra = ((Header.Flags >> 5) & 1) != 0; + bool isKeyFrame = ((header.Flags >> 0) & 1) != 0; + bool lastIsKeyFrame = ((header.Flags >> 1) & 1) != 0; + bool frameSizeChanged = ((header.Flags >> 2) & 1) != 0; + bool errorResilientMode = ((header.Flags >> 3) & 1) != 0; + bool lastShowFrame = ((header.Flags >> 4) & 1) != 0; + bool isFrameIntra = ((header.Flags >> 5) & 1) != 0; - bool ShowFrame = !IsFrameIntra; + bool showFrame = !isFrameIntra; //Write compressed header. - byte[] CompressedHeaderData; + byte[] compressedHeaderData; - using (MemoryStream CompressedHeader = new MemoryStream()) + using (MemoryStream compressedHeader = new MemoryStream()) { - VpxRangeEncoder Writer = new VpxRangeEncoder(CompressedHeader); + VpxRangeEncoder writer = new VpxRangeEncoder(compressedHeader); - if (!Header.Lossless) + if (!header.Lossless) { - if ((uint)Header.TxMode >= 3) + if ((uint)header.TxMode >= 3) { - Writer.Write(3, 2); - Writer.Write(Header.TxMode == 4); + writer.Write(3, 2); + writer.Write(header.TxMode == 4); } else { - Writer.Write(Header.TxMode, 2); + writer.Write(header.TxMode, 2); } } - if (Header.TxMode == 4) + if (header.TxMode == 4) { - WriteProbabilityUpdate(Writer, Probs.Tx8x8Probs, DefaultTx8x8Probs); - WriteProbabilityUpdate(Writer, Probs.Tx16x16Probs, DefaultTx16x16Probs); - WriteProbabilityUpdate(Writer, Probs.Tx32x32Probs, DefaultTx32x32Probs); + WriteProbabilityUpdate(writer, probs.Tx8x8Probs, DefaultTx8x8Probs); + WriteProbabilityUpdate(writer, probs.Tx16x16Probs, DefaultTx16x16Probs); + WriteProbabilityUpdate(writer, probs.Tx32x32Probs, DefaultTx32x32Probs); } - WriteCoefProbabilityUpdate(Writer, Header.TxMode, Probs.CoefProbs, DefaultCoefProbs); + WriteCoefProbabilityUpdate(writer, header.TxMode, probs.CoefProbs, _defaultCoefProbs); - WriteProbabilityUpdate(Writer, Probs.SkipProbs, DefaultSkipProbs); + WriteProbabilityUpdate(writer, probs.SkipProbs, _defaultSkipProbs); - if (!IsFrameIntra) + if (!isFrameIntra) { - WriteProbabilityUpdateAligned4(Writer, Probs.InterModeProbs, DefaultInterModeProbs); + WriteProbabilityUpdateAligned4(writer, probs.InterModeProbs, _defaultInterModeProbs); - if (Header.RawInterpolationFilter == 4) + if (header.RawInterpolationFilter == 4) { - WriteProbabilityUpdate(Writer, Probs.InterpFilterProbs, DefaultInterpFilterProbs); + WriteProbabilityUpdate(writer, probs.InterpFilterProbs, _defaultInterpFilterProbs); } - WriteProbabilityUpdate(Writer, Probs.IsInterProbs, DefaultIsInterProbs); + WriteProbabilityUpdate(writer, probs.IsInterProbs, _defaultIsInterProbs); - if ((Header.RefFrameSignBias[1] & 1) != (Header.RefFrameSignBias[2] & 1) || - (Header.RefFrameSignBias[1] & 1) != (Header.RefFrameSignBias[3] & 1)) + if ((header.RefFrameSignBias[1] & 1) != (header.RefFrameSignBias[2] & 1) || + (header.RefFrameSignBias[1] & 1) != (header.RefFrameSignBias[3] & 1)) { - if ((uint)Header.CompPredMode >= 1) + if ((uint)header.CompPredMode >= 1) { - Writer.Write(1, 1); - Writer.Write(Header.CompPredMode == 2); + writer.Write(1, 1); + writer.Write(header.CompPredMode == 2); } else { - Writer.Write(0, 1); + writer.Write(0, 1); } } - if (Header.CompPredMode == 2) + if (header.CompPredMode == 2) { - WriteProbabilityUpdate(Writer, Probs.CompModeProbs, DefaultCompModeProbs); + WriteProbabilityUpdate(writer, probs.CompModeProbs, _defaultCompModeProbs); } - if (Header.CompPredMode != 1) + if (header.CompPredMode != 1) { - WriteProbabilityUpdate(Writer, Probs.SingleRefProbs, DefaultSingleRefProbs); + WriteProbabilityUpdate(writer, probs.SingleRefProbs, _defaultSingleRefProbs); } - if (Header.CompPredMode != 0) + if (header.CompPredMode != 0) { - WriteProbabilityUpdate(Writer, Probs.CompRefProbs, DefaultCompRefProbs); + WriteProbabilityUpdate(writer, probs.CompRefProbs, _defaultCompRefProbs); } - for (int Index = 0; Index < 4; Index++) + for (int index = 0; index < 4; index++) { - int i = Index * 8; - int j = Index; + int i = index * 8; + int j = index; - WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 0], DefaultYModeProbs0[i + 0]); - WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 1], DefaultYModeProbs0[i + 1]); - WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 2], DefaultYModeProbs0[i + 2]); - WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 3], DefaultYModeProbs0[i + 3]); - WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 4], DefaultYModeProbs0[i + 4]); - WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 5], DefaultYModeProbs0[i + 5]); - WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 6], DefaultYModeProbs0[i + 6]); - WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 7], DefaultYModeProbs0[i + 7]); - WriteProbabilityUpdate(Writer, Probs.YModeProbs1[j + 0], DefaultYModeProbs1[j + 0]); + WriteProbabilityUpdate(writer, probs.YModeProbs0[i + 0], _defaultYModeProbs0[i + 0]); + WriteProbabilityUpdate(writer, probs.YModeProbs0[i + 1], _defaultYModeProbs0[i + 1]); + WriteProbabilityUpdate(writer, probs.YModeProbs0[i + 2], _defaultYModeProbs0[i + 2]); + WriteProbabilityUpdate(writer, probs.YModeProbs0[i + 3], _defaultYModeProbs0[i + 3]); + WriteProbabilityUpdate(writer, probs.YModeProbs0[i + 4], _defaultYModeProbs0[i + 4]); + WriteProbabilityUpdate(writer, probs.YModeProbs0[i + 5], _defaultYModeProbs0[i + 5]); + WriteProbabilityUpdate(writer, probs.YModeProbs0[i + 6], _defaultYModeProbs0[i + 6]); + WriteProbabilityUpdate(writer, probs.YModeProbs0[i + 7], _defaultYModeProbs0[i + 7]); + WriteProbabilityUpdate(writer, probs.YModeProbs1[j + 0], _defaultYModeProbs1[j + 0]); } - WriteProbabilityUpdateAligned4(Writer, Probs.PartitionProbs, DefaultPartitionProbs); + WriteProbabilityUpdateAligned4(writer, probs.PartitionProbs, _defaultPartitionProbs); for (int i = 0; i < 3; i++) { - WriteMvProbabilityUpdate(Writer, Probs.MvJointProbs[i], DefaultMvJointProbs[i]); + WriteMvProbabilityUpdate(writer, probs.MvJointProbs[i], _defaultMvJointProbs[i]); } for (int i = 0; i < 2; i++) { - WriteMvProbabilityUpdate(Writer, Probs.MvSignProbs[i], DefaultMvSignProbs[i]); + WriteMvProbabilityUpdate(writer, probs.MvSignProbs[i], _defaultMvSignProbs[i]); for (int j = 0; j < 10; j++) { - int Index = i * 10 + j; + int index = i * 10 + j; - WriteMvProbabilityUpdate(Writer, Probs.MvClassProbs[Index], DefaultMvClassProbs[Index]); + WriteMvProbabilityUpdate(writer, probs.MvClassProbs[index], _defaultMvClassProbs[index]); } - WriteMvProbabilityUpdate(Writer, Probs.MvClass0BitProbs[i], DefaultMvClass0BitProbs[i]); + WriteMvProbabilityUpdate(writer, probs.MvClass0BitProbs[i], _defaultMvClass0BitProbs[i]); for (int j = 0; j < 10; j++) { - int Index = i * 10 + j; + int index = i * 10 + j; - WriteMvProbabilityUpdate(Writer, Probs.MvBitsProbs[Index], DefaultMvBitsProbs[Index]); + WriteMvProbabilityUpdate(writer, probs.MvBitsProbs[index], _defaultMvBitsProbs[index]); } } @@ -408,249 +408,249 @@ namespace Ryujinx.Graphics.VDec { for (int k = 0; k < 3; k++) { - int Index = i * 2 * 3 + j * 3 + k; + int index = i * 2 * 3 + j * 3 + k; - WriteMvProbabilityUpdate(Writer, Probs.MvClass0FrProbs[Index], DefaultMvClass0FrProbs[Index]); + WriteMvProbabilityUpdate(writer, probs.MvClass0FrProbs[index], _defaultMvClass0FrProbs[index]); } } for (int j = 0; j < 3; j++) { - int Index = i * 3 + j; + int index = i * 3 + j; - WriteMvProbabilityUpdate(Writer, Probs.MvFrProbs[Index], DefaultMvFrProbs[Index]); + WriteMvProbabilityUpdate(writer, probs.MvFrProbs[index], _defaultMvFrProbs[index]); } } - if (Header.AllowHighPrecisionMv) + if (header.AllowHighPrecisionMv) { - for (int Index = 0; Index < 2; Index++) + for (int index = 0; index < 2; index++) { - WriteMvProbabilityUpdate(Writer, Probs.MvClass0HpProbs[Index], DefaultMvClass0HpProbs[Index]); - WriteMvProbabilityUpdate(Writer, Probs.MvHpProbs[Index], DefaultMvHpProbs[Index]); + WriteMvProbabilityUpdate(writer, probs.MvClass0HpProbs[index], _defaultMvClass0HpProbs[index]); + WriteMvProbabilityUpdate(writer, probs.MvHpProbs[index], _defaultMvHpProbs[index]); } } } - Writer.End(); + writer.End(); - CompressedHeaderData = CompressedHeader.ToArray(); + compressedHeaderData = compressedHeader.ToArray(); } //Write uncompressed header. - using (MemoryStream EncodedHeader = new MemoryStream()) + using (MemoryStream encodedHeader = new MemoryStream()) { - VpxBitStreamWriter Writer = new VpxBitStreamWriter(EncodedHeader); + VpxBitStreamWriter writer = new VpxBitStreamWriter(encodedHeader); - Writer.WriteU(2, 2); //Frame marker. - Writer.WriteU(0, 2); //Profile. - Writer.WriteBit(false); //Show existing frame. - Writer.WriteBit(!IsKeyFrame); - Writer.WriteBit(ShowFrame); - Writer.WriteBit(ErrorResilientMode); + writer.WriteU(2, 2); //Frame marker. + writer.WriteU(0, 2); //Profile. + writer.WriteBit(false); //Show existing frame. + writer.WriteBit(!isKeyFrame); + writer.WriteBit(showFrame); + writer.WriteBit(errorResilientMode); - if (IsKeyFrame) + if (isKeyFrame) { - Writer.WriteU(FrameSyncCode, 24); - Writer.WriteU(0, 3); //Color space. - Writer.WriteU(0, 1); //Color range. - Writer.WriteU(Header.CurrentFrame.Width - 1, 16); - Writer.WriteU(Header.CurrentFrame.Height - 1, 16); - Writer.WriteBit(false); //Render and frame size different. + writer.WriteU(FrameSyncCode, 24); + writer.WriteU(0, 3); //Color space. + writer.WriteU(0, 1); //Color range. + writer.WriteU(header.CurrentFrame.Width - 1, 16); + writer.WriteU(header.CurrentFrame.Height - 1, 16); + writer.WriteBit(false); //Render and frame size different. - CachedRefFrames.Clear(); + _cachedRefFrames.Clear(); //On key frames, all frame slots are set to the current frame, //so the value of the selected slot doesn't really matter. - GetNewFrameSlot(Keys.CurrKey); + GetNewFrameSlot(keys.CurrKey); } else { - if (!ShowFrame) + if (!showFrame) { - Writer.WriteBit(IsFrameIntra); + writer.WriteBit(isFrameIntra); } - if (!ErrorResilientMode) + if (!errorResilientMode) { - Writer.WriteU(0, 2); //Reset frame context. + writer.WriteU(0, 2); //Reset frame context. } - int RefreshFrameFlags = 1 << GetNewFrameSlot(Keys.CurrKey); + int refreshFrameFlags = 1 << GetNewFrameSlot(keys.CurrKey); - if (IsFrameIntra) + if (isFrameIntra) { - Writer.WriteU(FrameSyncCode, 24); - Writer.WriteU(RefreshFrameFlags, 8); - Writer.WriteU(Header.CurrentFrame.Width - 1, 16); - Writer.WriteU(Header.CurrentFrame.Height - 1, 16); - Writer.WriteBit(false); //Render and frame size different. + writer.WriteU(FrameSyncCode, 24); + writer.WriteU(refreshFrameFlags, 8); + writer.WriteU(header.CurrentFrame.Width - 1, 16); + writer.WriteU(header.CurrentFrame.Height - 1, 16); + writer.WriteBit(false); //Render and frame size different. } else { - Writer.WriteU(RefreshFrameFlags, 8); + writer.WriteU(refreshFrameFlags, 8); - int[] RefFrameIndex = new int[] + int[] refFrameIndex = new int[] { - GetFrameSlot(Keys.Ref0Key), - GetFrameSlot(Keys.Ref1Key), - GetFrameSlot(Keys.Ref2Key) + GetFrameSlot(keys.Ref0Key), + GetFrameSlot(keys.Ref1Key), + GetFrameSlot(keys.Ref2Key) }; - byte[] RefFrameSignBias = Header.RefFrameSignBias; + byte[] refFrameSignBias = header.RefFrameSignBias; - for (int Index = 1; Index < 4; Index++) + for (int index = 1; index < 4; index++) { - Writer.WriteU(RefFrameIndex[Index - 1], 3); - Writer.WriteU(RefFrameSignBias[Index], 1); + writer.WriteU(refFrameIndex[index - 1], 3); + writer.WriteU(refFrameSignBias[index], 1); } - Writer.WriteBit(true); //Frame size with refs. - Writer.WriteBit(false); //Render and frame size different. - Writer.WriteBit(Header.AllowHighPrecisionMv); - Writer.WriteBit(Header.RawInterpolationFilter == 4); + writer.WriteBit(true); //Frame size with refs. + writer.WriteBit(false); //Render and frame size different. + writer.WriteBit(header.AllowHighPrecisionMv); + writer.WriteBit(header.RawInterpolationFilter == 4); - if (Header.RawInterpolationFilter != 4) + if (header.RawInterpolationFilter != 4) { - Writer.WriteU(Header.RawInterpolationFilter, 2); + writer.WriteU(header.RawInterpolationFilter, 2); } } } - if (!ErrorResilientMode) + if (!errorResilientMode) { - Writer.WriteBit(false); //Refresh frame context. - Writer.WriteBit(true); //Frame parallel decoding mode. + writer.WriteBit(false); //Refresh frame context. + writer.WriteBit(true); //Frame parallel decoding mode. } - Writer.WriteU(0, 2); //Frame context index. + writer.WriteU(0, 2); //Frame context index. - Writer.WriteU(Header.LoopFilterLevel, 6); - Writer.WriteU(Header.LoopFilterSharpness, 3); - Writer.WriteBit(Header.LoopFilterDeltaEnabled); + writer.WriteU(header.LoopFilterLevel, 6); + writer.WriteU(header.LoopFilterSharpness, 3); + writer.WriteBit(header.LoopFilterDeltaEnabled); - if (Header.LoopFilterDeltaEnabled) + if (header.LoopFilterDeltaEnabled) { - bool[] UpdateLoopFilterRefDeltas = new bool[4]; - bool[] UpdateLoopFilterModeDeltas = new bool[2]; + bool[] updateLoopFilterRefDeltas = new bool[4]; + bool[] updateLoopFilterModeDeltas = new bool[2]; - bool LoopFilterDeltaUpdate = false; + bool loopFilterDeltaUpdate = false; - for (int Index = 0; Index < Header.LoopFilterRefDeltas.Length; Index++) + for (int index = 0; index < header.LoopFilterRefDeltas.Length; index++) { - sbyte Old = LoopFilterRefDeltas[Index]; - sbyte New = Header.LoopFilterRefDeltas[Index]; + sbyte old = _loopFilterRefDeltas[index]; + sbyte New = header.LoopFilterRefDeltas[index]; - LoopFilterDeltaUpdate |= (UpdateLoopFilterRefDeltas[Index] = Old != New); + loopFilterDeltaUpdate |= (updateLoopFilterRefDeltas[index] = old != New); } - for (int Index = 0; Index < Header.LoopFilterModeDeltas.Length; Index++) + for (int index = 0; index < header.LoopFilterModeDeltas.Length; index++) { - sbyte Old = LoopFilterModeDeltas[Index]; - sbyte New = Header.LoopFilterModeDeltas[Index]; + sbyte old = _loopFilterModeDeltas[index]; + sbyte New = header.LoopFilterModeDeltas[index]; - LoopFilterDeltaUpdate |= (UpdateLoopFilterModeDeltas[Index] = Old != New); + loopFilterDeltaUpdate |= (updateLoopFilterModeDeltas[index] = old != New); } - Writer.WriteBit(LoopFilterDeltaUpdate); + writer.WriteBit(loopFilterDeltaUpdate); - if (LoopFilterDeltaUpdate) + if (loopFilterDeltaUpdate) { - for (int Index = 0; Index < Header.LoopFilterRefDeltas.Length; Index++) + for (int index = 0; index < header.LoopFilterRefDeltas.Length; index++) { - Writer.WriteBit(UpdateLoopFilterRefDeltas[Index]); + writer.WriteBit(updateLoopFilterRefDeltas[index]); - if (UpdateLoopFilterRefDeltas[Index]) + if (updateLoopFilterRefDeltas[index]) { - Writer.WriteS(Header.LoopFilterRefDeltas[Index], 6); + writer.WriteS(header.LoopFilterRefDeltas[index], 6); } } - for (int Index = 0; Index < Header.LoopFilterModeDeltas.Length; Index++) + for (int index = 0; index < header.LoopFilterModeDeltas.Length; index++) { - Writer.WriteBit(UpdateLoopFilterModeDeltas[Index]); + writer.WriteBit(updateLoopFilterModeDeltas[index]); - if (UpdateLoopFilterModeDeltas[Index]) + if (updateLoopFilterModeDeltas[index]) { - Writer.WriteS(Header.LoopFilterModeDeltas[Index], 6); + writer.WriteS(header.LoopFilterModeDeltas[index], 6); } } } } - Writer.WriteU(Header.BaseQIndex, 8); + writer.WriteU(header.BaseQIndex, 8); - Writer.WriteDeltaQ(Header.DeltaQYDc); - Writer.WriteDeltaQ(Header.DeltaQUvDc); - Writer.WriteDeltaQ(Header.DeltaQUvAc); + writer.WriteDeltaQ(header.DeltaQYDc); + writer.WriteDeltaQ(header.DeltaQUvDc); + writer.WriteDeltaQ(header.DeltaQUvAc); - Writer.WriteBit(false); //Segmentation enabled (TODO). + writer.WriteBit(false); //Segmentation enabled (TODO). - int MinTileColsLog2 = CalcMinLog2TileCols(Header.CurrentFrame.Width); - int MaxTileColsLog2 = CalcMaxLog2TileCols(Header.CurrentFrame.Width); + int minTileColsLog2 = CalcMinLog2TileCols(header.CurrentFrame.Width); + int maxTileColsLog2 = CalcMaxLog2TileCols(header.CurrentFrame.Width); - int TileColsLog2Diff = Header.TileColsLog2 - MinTileColsLog2; + int tileColsLog2Diff = header.TileColsLog2 - minTileColsLog2; - int TileColsLog2IncMask = (1 << TileColsLog2Diff) - 1; + int tileColsLog2IncMask = (1 << tileColsLog2Diff) - 1; //If it's less than the maximum, we need to add an extra 0 on the bitstream //to indicate that it should stop reading. - if (Header.TileColsLog2 < MaxTileColsLog2) + if (header.TileColsLog2 < maxTileColsLog2) { - Writer.WriteU(TileColsLog2IncMask << 1, TileColsLog2Diff + 1); + writer.WriteU(tileColsLog2IncMask << 1, tileColsLog2Diff + 1); } else { - Writer.WriteU(TileColsLog2IncMask, TileColsLog2Diff); + writer.WriteU(tileColsLog2IncMask, tileColsLog2Diff); } - bool TileRowsLog2IsNonZero = Header.TileRowsLog2 != 0; + bool tileRowsLog2IsNonZero = header.TileRowsLog2 != 0; - Writer.WriteBit(TileRowsLog2IsNonZero); + writer.WriteBit(tileRowsLog2IsNonZero); - if (TileRowsLog2IsNonZero) + if (tileRowsLog2IsNonZero) { - Writer.WriteBit(Header.TileRowsLog2 > 1); + writer.WriteBit(header.TileRowsLog2 > 1); } - Writer.WriteU(CompressedHeaderData.Length, 16); + writer.WriteU(compressedHeaderData.Length, 16); - Writer.Flush(); + writer.Flush(); - EncodedHeader.Write(CompressedHeaderData, 0, CompressedHeaderData.Length); + encodedHeader.Write(compressedHeaderData, 0, compressedHeaderData.Length); if (!FFmpegWrapper.IsInitialized) { FFmpegWrapper.Vp9Initialize(); } - FFmpegWrapper.DecodeFrame(DecoderHelper.Combine(EncodedHeader.ToArray(), FrameData)); + FFmpegWrapper.DecodeFrame(DecoderHelper.Combine(encodedHeader.ToArray(), frameData)); } - LoopFilterRefDeltas = Header.LoopFilterRefDeltas; - LoopFilterModeDeltas = Header.LoopFilterModeDeltas; + _loopFilterRefDeltas = header.LoopFilterRefDeltas; + _loopFilterModeDeltas = header.LoopFilterModeDeltas; } - private int GetNewFrameSlot(long Key) + private int GetNewFrameSlot(long key) { - LinkedListNode Node = FrameSlotByLastUse.Last; + LinkedListNode node = _frameSlotByLastUse.Last; - FrameSlotByLastUse.RemoveLast(); - FrameSlotByLastUse.AddFirst(Node); + _frameSlotByLastUse.RemoveLast(); + _frameSlotByLastUse.AddFirst(node); - CachedRefFrames[Key] = Node; + _cachedRefFrames[key] = node; - return Node.Value; + return node.Value; } - private int GetFrameSlot(long Key) + private int GetFrameSlot(long key) { - if (CachedRefFrames.TryGetValue(Key, out LinkedListNode Node)) + if (_cachedRefFrames.TryGetValue(key, out LinkedListNode node)) { - FrameSlotByLastUse.Remove(Node); - FrameSlotByLastUse.AddFirst(Node); + _frameSlotByLastUse.Remove(node); + _frameSlotByLastUse.AddFirst(node); - return Node.Value; + return node.Value; } //Reference frame was lost. @@ -658,53 +658,53 @@ namespace Ryujinx.Graphics.VDec return 0; } - private void WriteProbabilityUpdate(VpxRangeEncoder Writer, byte[] New, byte[] Old) + private void WriteProbabilityUpdate(VpxRangeEncoder writer, byte[] New, byte[] old) { - for (int Offset = 0; Offset < New.Length; Offset++) + for (int offset = 0; offset < New.Length; offset++) { - WriteProbabilityUpdate(Writer, New[Offset], Old[Offset]); + WriteProbabilityUpdate(writer, New[offset], old[offset]); } } - private void WriteCoefProbabilityUpdate(VpxRangeEncoder Writer, int TxMode, byte[] New, byte[] Old) + private void WriteCoefProbabilityUpdate(VpxRangeEncoder writer, int txMode, byte[] New, byte[] old) { //Note: There's 1 byte added on each packet for alignment, //this byte is ignored when doing updates. - const int BlockBytes = 2 * 2 * 6 * 6 * 4; + const int blockBytes = 2 * 2 * 6 * 6 * 4; - bool NeedsUpdate(int BaseIndex) + bool NeedsUpdate(int baseIndex) { - int Index = BaseIndex; + int index = baseIndex; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 6; k++) for (int l = 0; l < 6; l++) { - if (New[Index + 0] != Old[Index + 0] || - New[Index + 1] != Old[Index + 1] || - New[Index + 2] != Old[Index + 2]) + if (New[index + 0] != old[index + 0] || + New[index + 1] != old[index + 1] || + New[index + 2] != old[index + 2]) { return true; } - Index += 4; + index += 4; } return false; } - for (int BlockIndex = 0; BlockIndex < 4; BlockIndex++) + for (int blockIndex = 0; blockIndex < 4; blockIndex++) { - int BaseIndex = BlockIndex * BlockBytes; + int baseIndex = blockIndex * blockBytes; - bool Update = NeedsUpdate(BaseIndex); + bool update = NeedsUpdate(baseIndex); - Writer.Write(Update); + writer.Write(update); - if (Update) + if (update) { - int Index = BaseIndex; + int index = baseIndex; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) @@ -713,167 +713,167 @@ namespace Ryujinx.Graphics.VDec { if (k != 0 || l < 3) { - WriteProbabilityUpdate(Writer, New[Index + 0], Old[Index + 0]); - WriteProbabilityUpdate(Writer, New[Index + 1], Old[Index + 1]); - WriteProbabilityUpdate(Writer, New[Index + 2], Old[Index + 2]); + WriteProbabilityUpdate(writer, New[index + 0], old[index + 0]); + WriteProbabilityUpdate(writer, New[index + 1], old[index + 1]); + WriteProbabilityUpdate(writer, New[index + 2], old[index + 2]); } - Index += 4; + index += 4; } } - if (BlockIndex == TxMode) + if (blockIndex == txMode) { break; } } } - private void WriteProbabilityUpdateAligned4(VpxRangeEncoder Writer, byte[] New, byte[] Old) + private void WriteProbabilityUpdateAligned4(VpxRangeEncoder writer, byte[] New, byte[] old) { - for (int Offset = 0; Offset < New.Length; Offset += 4) + for (int offset = 0; offset < New.Length; offset += 4) { - WriteProbabilityUpdate(Writer, New[Offset + 0], Old[Offset + 0]); - WriteProbabilityUpdate(Writer, New[Offset + 1], Old[Offset + 1]); - WriteProbabilityUpdate(Writer, New[Offset + 2], Old[Offset + 2]); + WriteProbabilityUpdate(writer, New[offset + 0], old[offset + 0]); + WriteProbabilityUpdate(writer, New[offset + 1], old[offset + 1]); + WriteProbabilityUpdate(writer, New[offset + 2], old[offset + 2]); } } - private void WriteProbabilityUpdate(VpxRangeEncoder Writer, byte New, byte Old) + private void WriteProbabilityUpdate(VpxRangeEncoder writer, byte New, byte old) { - bool Update = New != Old; + bool update = New != old; - Writer.Write(Update, DiffUpdateProbability); + writer.Write(update, DiffUpdateProbability); - if (Update) + if (update) { - WriteProbabilityDelta(Writer, New, Old); + WriteProbabilityDelta(writer, New, old); } } - private void WriteProbabilityDelta(VpxRangeEncoder Writer, int New, int Old) + private void WriteProbabilityDelta(VpxRangeEncoder writer, int New, int old) { - int Delta = RemapProbability(New, Old); + int delta = RemapProbability(New, old); - EncodeTermSubExp(Writer, Delta); + EncodeTermSubExp(writer, delta); } - private int RemapProbability(int New, int Old) + private int RemapProbability(int New, int old) { New--; - Old--; + old--; - int Index; + int index; - if (Old * 2 <= 0xff) + if (old * 2 <= 0xff) { - Index = RecenterNonNeg(New, Old) - 1; + index = RecenterNonNeg(New, old) - 1; } else { - Index = RecenterNonNeg(0xff - 1 - New, 0xff - 1 - Old) - 1; + index = RecenterNonNeg(0xff - 1 - New, 0xff - 1 - old) - 1; } - return MapLut[Index]; + return MapLut[index]; } - private int RecenterNonNeg(int New, int Old) + private int RecenterNonNeg(int New, int old) { - if (New > Old * 2) + if (New > old * 2) { return New; } - else if (New >= Old) + else if (New >= old) { - return (New - Old) * 2; + return (New - old) * 2; } else /* if (New < Old) */ { - return (Old - New) * 2 - 1; + return (old - New) * 2 - 1; } } - private void EncodeTermSubExp(VpxRangeEncoder Writer, int Value) + private void EncodeTermSubExp(VpxRangeEncoder writer, int value) { - if (WriteLessThan(Writer, Value, 16)) + if (WriteLessThan(writer, value, 16)) { - Writer.Write(Value, 4); + writer.Write(value, 4); } - else if (WriteLessThan(Writer, Value, 32)) + else if (WriteLessThan(writer, value, 32)) { - Writer.Write(Value - 16, 4); + writer.Write(value - 16, 4); } - else if (WriteLessThan(Writer, Value, 64)) + else if (WriteLessThan(writer, value, 64)) { - Writer.Write(Value - 32, 5); + writer.Write(value - 32, 5); } else { - Value -= 64; + value -= 64; - const int Size = 8; + const int size = 8; - int Mask = (1 << Size) - 191; + int mask = (1 << size) - 191; - int Delta = Value - Mask; + int delta = value - mask; - if (Delta < 0) + if (delta < 0) { - Writer.Write(Value, Size - 1); + writer.Write(value, size - 1); } else { - Writer.Write(Delta / 2 + Mask, Size - 1); - Writer.Write(Delta & 1, 1); + writer.Write(delta / 2 + mask, size - 1); + writer.Write(delta & 1, 1); } } } - private bool WriteLessThan(VpxRangeEncoder Writer, int Value, int Test) + private bool WriteLessThan(VpxRangeEncoder writer, int value, int test) { - bool IsLessThan = Value < Test; + bool isLessThan = value < test; - Writer.Write(!IsLessThan); + writer.Write(!isLessThan); - return IsLessThan; + return isLessThan; } - private void WriteMvProbabilityUpdate(VpxRangeEncoder Writer, byte New, byte Old) + private void WriteMvProbabilityUpdate(VpxRangeEncoder writer, byte New, byte old) { - bool Update = New != Old; + bool update = New != old; - Writer.Write(Update, DiffUpdateProbability); + writer.Write(update, DiffUpdateProbability); - if (Update) + if (update) { - Writer.Write(New >> 1, 7); + writer.Write(New >> 1, 7); } } - private static int CalcMinLog2TileCols(int FrameWidth) + private static int CalcMinLog2TileCols(int frameWidth) { - int Sb64Cols = (FrameWidth + 63) / 64; - int MinLog2 = 0; + int sb64Cols = (frameWidth + 63) / 64; + int minLog2 = 0; - while ((64 << MinLog2) < Sb64Cols) + while ((64 << minLog2) < sb64Cols) { - MinLog2++; + minLog2++; } - return MinLog2; + return minLog2; } - private static int CalcMaxLog2TileCols(int FrameWidth) + private static int CalcMaxLog2TileCols(int frameWidth) { - int Sb64Cols = (FrameWidth + 63) / 64; - int MaxLog2 = 1; + int sb64Cols = (frameWidth + 63) / 64; + int maxLog2 = 1; - while ((Sb64Cols >> MaxLog2) >= 4) + while ((sb64Cols >> maxLog2) >= 4) { - MaxLog2++; + maxLog2++; } - return MaxLog2 - 1; + return maxLog2 - 1; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/VDec/VpxBitStreamWriter.cs b/Ryujinx.Graphics/VDec/VpxBitStreamWriter.cs index 0c712d2c..97ada333 100644 --- a/Ryujinx.Graphics/VDec/VpxBitStreamWriter.cs +++ b/Ryujinx.Graphics/VDec/VpxBitStreamWriter.cs @@ -4,34 +4,34 @@ namespace Ryujinx.Graphics.VDec { class VpxBitStreamWriter : BitStreamWriter { - public VpxBitStreamWriter(Stream BaseStream) : base(BaseStream) { } + public VpxBitStreamWriter(Stream baseStream) : base(baseStream) { } - public void WriteU(int Value, int ValueSize) + public void WriteU(int value, int valueSize) { - WriteBits(Value, ValueSize); + WriteBits(value, valueSize); } - public void WriteS(int Value, int ValueSize) + public void WriteS(int value, int valueSize) { - bool Sign = Value < 0; + bool sign = value < 0; - if (Sign) + if (sign) { - Value = -Value; + value = -value; } - WriteBits((Value << 1) | (Sign ? 1 : 0), ValueSize + 1); + WriteBits((value << 1) | (sign ? 1 : 0), valueSize + 1); } - public void WriteDeltaQ(int Value) + public void WriteDeltaQ(int value) { - bool DeltaCoded = Value != 0; + bool deltaCoded = value != 0; - WriteBit(DeltaCoded); + WriteBit(deltaCoded); - if (DeltaCoded) + if (deltaCoded) { - WriteBits(Value, 4); + WriteBits(value, 4); } } } diff --git a/Ryujinx.Graphics/VDec/VpxRangeEncoder.cs b/Ryujinx.Graphics/VDec/VpxRangeEncoder.cs index 3e381d2c..c854c9d9 100644 --- a/Ryujinx.Graphics/VDec/VpxRangeEncoder.cs +++ b/Ryujinx.Graphics/VDec/VpxRangeEncoder.cs @@ -26,106 +26,106 @@ namespace Ryujinx.Graphics.VDec 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - private Stream BaseStream; + private Stream _baseStream; - private uint LowValue; - private uint Range; - private int Count; + private uint _lowValue; + private uint _range; + private int _count; - public VpxRangeEncoder(Stream BaseStream) + public VpxRangeEncoder(Stream baseStream) { - this.BaseStream = BaseStream; + _baseStream = baseStream; - Range = 0xff; - Count = -24; + _range = 0xff; + _count = -24; Write(false); } - public void WriteByte(byte Value) + public void WriteByte(byte value) { - Write(Value, 8); + Write(value, 8); } - public void Write(int Value, int ValueSize) + public void Write(int value, int valueSize) { - for (int Bit = ValueSize - 1; Bit >= 0; Bit--) + for (int bit = valueSize - 1; bit >= 0; bit--) { - Write(((Value >> Bit) & 1) != 0); + Write(((value >> bit) & 1) != 0); } } - public void Write(bool Bit) + public void Write(bool bit) { - Write(Bit, HalfProbability); + Write(bit, HalfProbability); } - public void Write(bool Bit, int Probability) + public void Write(bool bit, int probability) { - uint Range = this.Range; + uint range = _range; - uint Split = 1 + (((Range - 1) * (uint)Probability) >> 8); + uint split = 1 + (((range - 1) * (uint)probability) >> 8); - Range = Split; + range = split; - if (Bit) + if (bit) { - LowValue += Split; - Range = this.Range - Split; + _lowValue += split; + range = _range - split; } - int Shift = NormLut[Range]; + int shift = NormLut[range]; - Range <<= Shift; - Count += Shift; + range <<= shift; + _count += shift; - if (Count >= 0) + if (_count >= 0) { - int Offset = Shift - Count; + int offset = shift - _count; - if (((LowValue << (Offset - 1)) >> 31) != 0) + if (((_lowValue << (offset - 1)) >> 31) != 0) { - long CurrentPos = BaseStream.Position; + long currentPos = _baseStream.Position; - BaseStream.Seek(-1, SeekOrigin.Current); + _baseStream.Seek(-1, SeekOrigin.Current); - while (BaseStream.Position >= 0 && PeekByte() == 0xff) + while (_baseStream.Position >= 0 && PeekByte() == 0xff) { - BaseStream.WriteByte(0); + _baseStream.WriteByte(0); - BaseStream.Seek(-2, SeekOrigin.Current); + _baseStream.Seek(-2, SeekOrigin.Current); } - BaseStream.WriteByte((byte)(PeekByte() + 1)); + _baseStream.WriteByte((byte)(PeekByte() + 1)); - BaseStream.Seek(CurrentPos, SeekOrigin.Begin); + _baseStream.Seek(currentPos, SeekOrigin.Begin); } - BaseStream.WriteByte((byte)(LowValue >> (24 - Offset))); + _baseStream.WriteByte((byte)(_lowValue >> (24 - offset))); - LowValue <<= Offset; - Shift = Count; - LowValue &= 0xffffff; - Count -= 8; + _lowValue <<= offset; + shift = _count; + _lowValue &= 0xffffff; + _count -= 8; } - LowValue <<= Shift; + _lowValue <<= shift; - this.Range = Range; + _range = range; } private byte PeekByte() { - byte Value = (byte)BaseStream.ReadByte(); + byte value = (byte)_baseStream.ReadByte(); - BaseStream.Seek(-1, SeekOrigin.Current); + _baseStream.Seek(-1, SeekOrigin.Current); - return Value; + return value; } public void End() { - for (int Index = 0; Index < 32; Index++) + for (int index = 0; index < 32; index++) { Write(false); } diff --git a/Ryujinx.Graphics/Vic/StructUnpacker.cs b/Ryujinx.Graphics/Vic/StructUnpacker.cs index 62777aad..6b6b9795 100644 --- a/Ryujinx.Graphics/Vic/StructUnpacker.cs +++ b/Ryujinx.Graphics/Vic/StructUnpacker.cs @@ -5,64 +5,64 @@ namespace Ryujinx.Graphics.Vic { class StructUnpacker { - private NvGpuVmm Vmm; + private NvGpuVmm _vmm; - private long Position; + private long _position; - private ulong Buffer; - private int BuffPos; + private ulong _buffer; + private int _buffPos; - public StructUnpacker(NvGpuVmm Vmm, long Position) + public StructUnpacker(NvGpuVmm vmm, long position) { - this.Vmm = Vmm; - this.Position = Position; + _vmm = vmm; + _position = position; - BuffPos = 64; + _buffPos = 64; } - public int Read(int Bits) + public int Read(int bits) { - if ((uint)Bits > 32) + if ((uint)bits > 32) { - throw new ArgumentOutOfRangeException(nameof(Bits)); + throw new ArgumentOutOfRangeException(nameof(bits)); } - int Value = 0; + int value = 0; - while (Bits > 0) + while (bits > 0) { RefillBufferIfNeeded(); - int ReadBits = Bits; + int readBits = bits; - int MaxReadBits = 64 - BuffPos; + int maxReadBits = 64 - _buffPos; - if (ReadBits > MaxReadBits) + if (readBits > maxReadBits) { - ReadBits = MaxReadBits; + readBits = maxReadBits; } - Value <<= ReadBits; + value <<= readBits; - Value |= (int)(Buffer >> BuffPos) & (int)(0xffffffff >> (32 - ReadBits)); + value |= (int)(_buffer >> _buffPos) & (int)(0xffffffff >> (32 - readBits)); - BuffPos += ReadBits; + _buffPos += readBits; - Bits -= ReadBits; + bits -= readBits; } - return Value; + return value; } private void RefillBufferIfNeeded() { - if (BuffPos >= 64) + if (_buffPos >= 64) { - Buffer = Vmm.ReadUInt64(Position); + _buffer = _vmm.ReadUInt64(_position); - Position += 8; + _position += 8; - BuffPos = 0; + _buffPos = 0; } } } diff --git a/Ryujinx.Graphics/Vic/SurfaceOutputConfig.cs b/Ryujinx.Graphics/Vic/SurfaceOutputConfig.cs index 0a232744..bdd55fc7 100644 --- a/Ryujinx.Graphics/Vic/SurfaceOutputConfig.cs +++ b/Ryujinx.Graphics/Vic/SurfaceOutputConfig.cs @@ -13,21 +13,21 @@ namespace Ryujinx.Graphics.Vic public long SurfaceChromaVAddress; public SurfaceOutputConfig( - SurfacePixelFormat PixelFormat, - int SurfaceWidth, - int SurfaceHeight, - int GobBlockHeight, - long OutputSurfaceLumaAddress, - long OutputSurfaceChromaUAddress, - long OutputSurfaceChromaVAddress) + SurfacePixelFormat pixelFormat, + int surfaceWidth, + int surfaceHeight, + int gobBlockHeight, + long outputSurfaceLumaAddress, + long outputSurfaceChromaUAddress, + long outputSurfaceChromaVAddress) { - this.PixelFormat = PixelFormat; - this.SurfaceWidth = SurfaceWidth; - this.SurfaceHeight = SurfaceHeight; - this.GobBlockHeight = GobBlockHeight; - this.SurfaceLumaAddress = OutputSurfaceLumaAddress; - this.SurfaceChromaUAddress = OutputSurfaceChromaUAddress; - this.SurfaceChromaVAddress = OutputSurfaceChromaVAddress; + PixelFormat = pixelFormat; + SurfaceWidth = surfaceWidth; + SurfaceHeight = surfaceHeight; + GobBlockHeight = gobBlockHeight; + SurfaceLumaAddress = outputSurfaceLumaAddress; + SurfaceChromaUAddress = outputSurfaceChromaUAddress; + SurfaceChromaVAddress = outputSurfaceChromaVAddress; } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Vic/SurfacePixelFormat.cs b/Ryujinx.Graphics/Vic/SurfacePixelFormat.cs index ee56ac05..8dabd094 100644 --- a/Ryujinx.Graphics/Vic/SurfacePixelFormat.cs +++ b/Ryujinx.Graphics/Vic/SurfacePixelFormat.cs @@ -2,7 +2,7 @@ namespace Ryujinx.Graphics.Vic { enum SurfacePixelFormat { - RGBA8 = 0x1f, - YUV420P = 0x44 + Rgba8 = 0x1f, + Yuv420P = 0x44 } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Vic/VideoImageComposer.cs b/Ryujinx.Graphics/Vic/VideoImageComposer.cs index 758382fa..e05bcfdb 100644 --- a/Ryujinx.Graphics/Vic/VideoImageComposer.cs +++ b/Ryujinx.Graphics/Vic/VideoImageComposer.cs @@ -4,104 +4,104 @@ namespace Ryujinx.Graphics.Vic { class VideoImageComposer { - private NvGpu Gpu; + private NvGpu _gpu; - private long ConfigStructAddress; - private long OutputSurfaceLumaAddress; - private long OutputSurfaceChromaUAddress; - private long OutputSurfaceChromaVAddress; + private long _configStructAddress; + private long _outputSurfaceLumaAddress; + private long _outputSurfaceChromaUAddress; + private long _outputSurfaceChromaVAddress; - public VideoImageComposer(NvGpu Gpu) + public VideoImageComposer(NvGpu gpu) { - this.Gpu = Gpu; + _gpu = gpu; } - public void Process(NvGpuVmm Vmm, int MethodOffset, int[] Arguments) + public void Process(NvGpuVmm vmm, int methodOffset, int[] arguments) { - VideoImageComposerMeth Method = (VideoImageComposerMeth)MethodOffset; + VideoImageComposerMeth method = (VideoImageComposerMeth)methodOffset; - switch (Method) + switch (method) { case VideoImageComposerMeth.Execute: - Execute(Vmm, Arguments); + Execute(vmm, arguments); break; case VideoImageComposerMeth.SetConfigStructOffset: - SetConfigStructOffset(Vmm, Arguments); + SetConfigStructOffset(vmm, arguments); break; case VideoImageComposerMeth.SetOutputSurfaceLumaOffset: - SetOutputSurfaceLumaOffset(Vmm, Arguments); + SetOutputSurfaceLumaOffset(vmm, arguments); break; case VideoImageComposerMeth.SetOutputSurfaceChromaUOffset: - SetOutputSurfaceChromaUOffset(Vmm, Arguments); + SetOutputSurfaceChromaUOffset(vmm, arguments); break; case VideoImageComposerMeth.SetOutputSurfaceChromaVOffset: - SetOutputSurfaceChromaVOffset(Vmm, Arguments); + SetOutputSurfaceChromaVOffset(vmm, arguments); break; } } - private void Execute(NvGpuVmm Vmm, int[] Arguments) + private void Execute(NvGpuVmm vmm, int[] arguments) { - StructUnpacker Unpacker = new StructUnpacker(Vmm, ConfigStructAddress + 0x20); + StructUnpacker unpacker = new StructUnpacker(vmm, _configStructAddress + 0x20); - SurfacePixelFormat PixelFormat = (SurfacePixelFormat)Unpacker.Read(7); + SurfacePixelFormat pixelFormat = (SurfacePixelFormat)unpacker.Read(7); - int ChromaLocHoriz = Unpacker.Read(2); - int ChromaLocVert = Unpacker.Read(2); + int chromaLocHoriz = unpacker.Read(2); + int chromaLocVert = unpacker.Read(2); - int BlockLinearKind = Unpacker.Read(4); - int BlockLinearHeightLog2 = Unpacker.Read(4); + int blockLinearKind = unpacker.Read(4); + int blockLinearHeightLog2 = unpacker.Read(4); - int Reserved0 = Unpacker.Read(3); - int Reserved1 = Unpacker.Read(10); + int reserved0 = unpacker.Read(3); + int reserved1 = unpacker.Read(10); - int SurfaceWidthMinus1 = Unpacker.Read(14); - int SurfaceHeightMinus1 = Unpacker.Read(14); + int surfaceWidthMinus1 = unpacker.Read(14); + int surfaceHeightMinus1 = unpacker.Read(14); - int GobBlockHeight = 1 << BlockLinearHeightLog2; + int gobBlockHeight = 1 << blockLinearHeightLog2; - int SurfaceWidth = SurfaceWidthMinus1 + 1; - int SurfaceHeight = SurfaceHeightMinus1 + 1; + int surfaceWidth = surfaceWidthMinus1 + 1; + int surfaceHeight = surfaceHeightMinus1 + 1; - SurfaceOutputConfig OutputConfig = new SurfaceOutputConfig( - PixelFormat, - SurfaceWidth, - SurfaceHeight, - GobBlockHeight, - OutputSurfaceLumaAddress, - OutputSurfaceChromaUAddress, - OutputSurfaceChromaVAddress); + SurfaceOutputConfig outputConfig = new SurfaceOutputConfig( + pixelFormat, + surfaceWidth, + surfaceHeight, + gobBlockHeight, + _outputSurfaceLumaAddress, + _outputSurfaceChromaUAddress, + _outputSurfaceChromaVAddress); - Gpu.VideoDecoder.CopyPlanes(Vmm, OutputConfig); + _gpu.VideoDecoder.CopyPlanes(vmm, outputConfig); } - private void SetConfigStructOffset(NvGpuVmm Vmm, int[] Arguments) + private void SetConfigStructOffset(NvGpuVmm vmm, int[] arguments) { - ConfigStructAddress = GetAddress(Arguments); + _configStructAddress = GetAddress(arguments); } - private void SetOutputSurfaceLumaOffset(NvGpuVmm Vmm, int[] Arguments) + private void SetOutputSurfaceLumaOffset(NvGpuVmm vmm, int[] arguments) { - OutputSurfaceLumaAddress = GetAddress(Arguments); + _outputSurfaceLumaAddress = GetAddress(arguments); } - private void SetOutputSurfaceChromaUOffset(NvGpuVmm Vmm, int[] Arguments) + private void SetOutputSurfaceChromaUOffset(NvGpuVmm vmm, int[] arguments) { - OutputSurfaceChromaUAddress = GetAddress(Arguments); + _outputSurfaceChromaUAddress = GetAddress(arguments); } - private void SetOutputSurfaceChromaVOffset(NvGpuVmm Vmm, int[] Arguments) + private void SetOutputSurfaceChromaVOffset(NvGpuVmm vmm, int[] arguments) { - OutputSurfaceChromaVAddress = GetAddress(Arguments); + _outputSurfaceChromaVAddress = GetAddress(arguments); } - private static long GetAddress(int[] Arguments) + private static long GetAddress(int[] arguments) { - return (long)(uint)Arguments[0] << 8; + return (long)(uint)arguments[0] << 8; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs b/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs index dbf255be..66c33279 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs @@ -357,15 +357,15 @@ namespace Ryujinx.HLE.HOS.Services.Android switch (colorFormat) { case ColorFormat.A8B8G8R8: - return GalImageFormat.RGBA8 | GalImageFormat.Unorm; + return GalImageFormat.Rgba8 | GalImageFormat.Unorm; case ColorFormat.X8B8G8R8: - return GalImageFormat.RGBX8 | GalImageFormat.Unorm; + return GalImageFormat.Rgbx8 | GalImageFormat.Unorm; case ColorFormat.R5G6B5: - return GalImageFormat.BGR565 | GalImageFormat.Unorm; + return GalImageFormat.Bgr565 | GalImageFormat.Unorm; case ColorFormat.A8R8G8B8: - return GalImageFormat.BGRA8 | GalImageFormat.Unorm; + return GalImageFormat.Bgra8 | GalImageFormat.Unorm; case ColorFormat.A4B4G4R4: - return GalImageFormat.RGBA4 | GalImageFormat.Unorm; + return GalImageFormat.Rgba4 | GalImageFormat.Unorm; default: throw new NotImplementedException($"Color Format \"{colorFormat}\" not implemented!"); } diff --git a/Ryujinx.sln.DotSettings b/Ryujinx.sln.DotSettings index 737b5688..579d97a4 100644 --- a/Ryujinx.sln.DotSettings +++ b/Ryujinx.sln.DotSettings @@ -4,4 +4,11 @@ UseExplicitType UseExplicitType <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="I" Suffix="" Style="AaBb" /></Policy> + True + True + True + True + True + True + True \ No newline at end of file diff --git a/Ryujinx/Program.cs b/Ryujinx/Program.cs index 52c85d56..1b26b391 100644 --- a/Ryujinx/Program.cs +++ b/Ryujinx/Program.cs @@ -16,7 +16,7 @@ namespace Ryujinx { Console.Title = "Ryujinx Console"; - IGalRenderer renderer = new OGLRenderer(); + IGalRenderer renderer = new OglRenderer(); IAalOutput audioOut = InitializeAudioEngine();