Compare commits

...

17 Commits

Author SHA1 Message Date
Wunk
295fbd0542 ARMeilleure: Add initial support for AVX512(EVEX encoding) (#3663)
* ARMeilleure: Add AVX512{F,VL,DQ,BW} detection

Add `UseAvx512Ortho` and `UseAvx512OrthoFloat` optimization flags as
short-hands for `F+VL` and `F+VL+DQ`.

* ARMeilleure: Add initial support for EVEX instruction encoding

Does not implement rounding, or exception controls.

* ARMeilleure: Add `X86Vpternlogd`

Accelerates the vector-`Not` instruction.

* ARMeilleure: Add check for `OSXSAVE` for AVX{2,512}

* ARMeilleure: Add check for `XCR0` flags

Add XCR0 register checks for AVX and AVX512F, following the guidelines
from section 14.3 and 15.2 from the Intel Architecture Software
Developer's Manual.

* ARMeilleure: Increment InternalVersion

* ARMeilleure: Remove redundant `ReProtect` and `Dispose`, formatting

* ARMeilleure: Move XCR0 procedure to GetXcr0Eax

* ARMeilleure: Add `XCR0` to `FeatureInfo` structure

* ARMeilleure: Utilize `ReadOnlySpan` for Xcr0 assembly

Avoids an additional allocation

* ARMeilleure: Formatting fixes
2022-12-18 16:46:13 -03:00
Mary-nyan
d7310d7a1c hle: Fix wrong conversion in UserPresence.ToString (#4142)
This fixes an error from #3805 that caused a wrong conversion of ``AppKeyValueStorage`` to string.
As that information isn't really relevant without appropriate parsing, it was removed from ``ToString``.

This should get ride of "bell warning" in Mario Kart 8 when entering Time Trials.
2022-12-18 14:23:19 +00:00
dependabot[bot]
8c50943a2e nuget: bump Microsoft.NET.Test.Sdk from 17.4.0 to 17.4.1 (#4137)
Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.4.0 to 17.4.1.
- [Release notes](https://github.com/microsoft/vstest/releases)
- [Changelog](https://github.com/microsoft/vstest/blob/main/docs/releases.md)
- [Commits](https://github.com/microsoft/vstest/compare/v17.4.0...v17.4.1)

---
updated-dependencies:
- dependency-name: Microsoft.NET.Test.Sdk
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-17 01:19:04 +01:00
gdkchan
ec4cd57ccf Implement another non-indexed draw method on GPU (#4123) 2022-12-16 12:06:38 -03:00
riperiperi
5a085cba0f GPU: Fix layered attachment write (#4131)
Fixes a regression caused by #4003 where the code that writes `_vtgWritesRtLayer` was removed, breaking the crowd in mario strikers.
2022-12-16 09:40:01 -03:00
TSRBerry
1a1d33a018 ava: Fix invisible swkbd applet on Linux (#4130) 2022-12-16 02:40:55 +01:00
Isaac Marovitz
0fbcd630bc Replace DllImport usage with LibraryImport (#4084)
* Replace usage of `DllImport` with `LibraryImport`

* Mark methods as `partial`

* Marshalling

* More `partial` & marshalling

* More `partial` and marshalling

* More partial and marshalling

* Update GdiPlusHelper to LibraryImport

* Unicorn

* More Partial

* Marshal

* Specify EntryPoint

* Specify EntryPoint

* Change GlobalMemoryStatusEx to LibraryImport

* Change RegisterClassEx to LibraryImport

* Define EntryPoints

* Update Ryujinx.Ava/Ui/Controls/Win32NativeInterop.cs

Co-authored-by: TSRBerry <20988865+TSRBerry@users.noreply.github.com>

* Update Ryujinx.Graphics.Nvdec.FFmpeg/Native/FFmpegApi.cs

Co-authored-by: TSRBerry <20988865+TSRBerry@users.noreply.github.com>

* Move return mashal

* Remove calling convention specification

* Remove calling conventions

* Update Ryujinx.Common/SystemInfo/WindowsSystemInfo.cs

Co-authored-by: TSRBerry <20988865+TSRBerry@users.noreply.github.com>

* Update Ryujinx/Modules/Updater/Updater.cs

Co-authored-by: Mary-nyan <thog@protonmail.com>

* Update Ryujinx.Ava/Modules/Updater/Updater.cs

Co-authored-by: Mary-nyan <thog@protonmail.com>

Co-authored-by: TSRBerry <20988865+TSRBerry@users.noreply.github.com>
Co-authored-by: Mary-nyan <thog@protonmail.com>
2022-12-15 18:07:31 +01:00
gdkchan
f4d731ae20 Fix NRE when loading Vulkan shader cache with Vertex A shaders (#4124) 2022-12-15 17:52:12 +01:00
Isaac Marovitz
8ac53c66b4 Remove Half Conversion (#4106)
* Remove HalfConversion

* Update `CodeGenVersion`
2022-12-14 21:13:23 -03:00
Georg Lehmann
0f50de72be Vulkan: enable VK_EXT_custom_border_color features (#4116)
* Vulkan: enable VK_EXT_custom_border_color features

radv only create the border color bo if this feature is enabled, so it crashed when creating samplers with custom border colors
Fixes #4072
Fixes #3993

* Address gdkchan's comment

Co-authored-by: Mary <mary@mary.zone>
2022-12-14 20:53:33 -03:00
TSRBerry
df758eddd1 Bsd: Add support for dns_mitm (#4102)
* bsd: Add dns_mitm from Atmosphère

related AMS files:
- https://github.com/Atmosphere-NX/Atmosphere/blob/master/stratosphere/ams_mitm/source/dns_mitm/dnsmitm_resolver_impl.cpp
- https://github.com/Atmosphere-NX/Atmosphere/blob/master/stratosphere/ams_mitm/source/dns_mitm/dnsmitm_host_redirection.cpp

* Remove debug logging and adjust redirect message

* Improve formatting

Co-authored-by: Ac_K <Acoustik666@gmail.com>

* Replace Initialize with instance property

* bsd: dns_mitm - Ignore empty lines

* bsd: Mark _mitmHostEntries as readonly

* bsd: Initialize Aliases when returning IpHostEntry

Fixes NullReferenceException

Co-authored-by: Ac_K <Acoustik666@gmail.com>
2022-12-12 18:04:08 +01:00
Mary-nyan
5f32a8ed94 misc: Update to Ryujinx.Graphics.Nvdec.Dependencies 5.0.1-build13 (#4097)
Fix packaging issues on macOS related to an unsatisfied dependency on libX11
2022-12-12 16:19:46 +01:00
Andrey Sukharev
535fbec675 Use NuGet Central Package Management to manage package versions solution-wise (#4095) 2022-12-12 16:03:10 +01:00
Mary-nyan
6fe88115a3 misc: Some fixes to the updaters (#4092)
This was meant to be only an upgrade of how we set unix permission in
the updater to use .NET 7 new APIs, but I end up finding bugs along the
way.

Changelog:
- Remove direct usage of chmod to use File.SetUnixFileMode.
- Fix command line being broken when updating (#3744) but on
  Ryujinx.Ava.
- Makes Ryujinx.Ava updater fallback to Ryujinx executable if current
  name isn't found.
- Make permission setter function more generic.
2022-12-12 15:17:22 +01:00
&Olga
475fa4d390 Fix "UI" abbreviation being miscapitalized (#4093) 2022-12-12 15:11:55 +01:00
Andrey Sukharev
edf7e628ca Use method overloads that support trimming. Mark some types to be trimming friendly (#4083)
* Use method overloads that support trimming. Mark some types to be trimming friendly

* Use generic version of marshalling method
2022-12-12 15:10:05 +01:00
TSRBerry
ba5c0cf5d8 Bsd: Implement Select (#4017)
* bsd: Add gdkchan's Select implementation

Co-authored-by: TSRBerry <20988865+tsrberry@users.noreply.github.com>

* bsd: Fix Select() causing a crash with an ArgumentException

.NET Sockets have to be used for the Select() call

* bsd: Make Select more generic

* bsd: Adjust namespaces and remove unused imports

* bsd: Fix NullReferenceException in Select

Co-authored-by: gdkchan <gab.dark.100@gmail.com>
2022-12-12 14:59:31 +01:00
108 changed files with 1312 additions and 585 deletions

View File

@@ -7,6 +7,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Ryujinx.Common\Ryujinx.Common.csproj" /> <ProjectReference Include="..\Ryujinx.Common\Ryujinx.Common.csproj" />
<ProjectReference Include="..\Ryujinx.Memory\Ryujinx.Memory.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1033,7 +1033,13 @@ namespace ARMeilleure.CodeGen.X86
Debug.Assert(opCode != BadOp, "Invalid opcode value."); Debug.Assert(opCode != BadOp, "Invalid opcode value.");
if ((flags & InstructionFlags.Vex) != 0 && HardwareCapabilities.SupportsVexEncoding) if ((flags & InstructionFlags.Evex) != 0 && HardwareCapabilities.SupportsEvexEncoding)
{
WriteEvexInst(dest, src1, src2, type, flags, opCode);
opCode &= 0xff;
}
else if ((flags & InstructionFlags.Vex) != 0 && HardwareCapabilities.SupportsVexEncoding)
{ {
// In a vex encoding, only one prefix can be active at a time. The active prefix is encoded in the second byte using two bits. // In a vex encoding, only one prefix can be active at a time. The active prefix is encoded in the second byte using two bits.
@@ -1152,6 +1158,103 @@ namespace ARMeilleure.CodeGen.X86
} }
} }
private void WriteEvexInst(
Operand dest,
Operand src1,
Operand src2,
OperandType type,
InstructionFlags flags,
int opCode,
bool broadcast = false,
int registerWidth = 128,
int maskRegisterIdx = 0,
bool zeroElements = false)
{
int destIdx = dest.GetRegister().Index;
int src1Idx = src1.GetRegister().Index;
int src2Idx = src2.GetRegister().Index;
WriteByte(0x62);
// P0
// Extend dest register
bool r = (destIdx & 8) == 0;
// Extend src register
bool x = (src1Idx & 16) == 0;
// Extend src register
bool b = (src1Idx & 8) == 0;
// Extend dest register
bool rp = (destIdx & 16) == 0;
// Escape code index
byte mm = 0b00;
switch ((ushort)(opCode >> 8))
{
case 0xf00: mm = 0b01; break;
case 0xf38: mm = 0b10; break;
case 0xf3a: mm = 0b11; break;
default: Debug.Assert(false, $"Failed to EVEX encode opcode 0x{opCode:X}."); break;
}
WriteByte(
(byte)(
(r ? 0x80 : 0) |
(x ? 0x40 : 0) |
(b ? 0x20 : 0) |
(rp ? 0x10 : 0) |
mm));
// P1
// Specify 64-bit lane mode
bool w = Is64Bits(type);
// Src2 register index
byte vvvv = (byte)(src2Idx & 0b1111);
// Opcode prefix
byte pp = (flags & InstructionFlags.PrefixMask) switch
{
InstructionFlags.Prefix66 => 0b01,
InstructionFlags.PrefixF3 => 0b10,
InstructionFlags.PrefixF2 => 0b11,
_ => 0
};
WriteByte(
(byte)(
(w ? 0x80 : 0) |
(vvvv << 3) |
0b100 |
pp));
// P2
// Mask register determines what elements to zero, rather than what elements to merge
bool z = zeroElements;
// Specifies register-width
byte ll = 0b00;
switch (registerWidth)
{
case 128: ll = 0b00; break;
case 256: ll = 0b01; break;
case 512: ll = 0b10; break;
default: Debug.Assert(false, $"Invalid EVEX vector register width {registerWidth}."); break;
}
// Embedded broadcast in the case of a memory operand
bool bcast = broadcast;
// Extend src2 register
bool vp = (src2Idx & 16) == 0;
// Mask register index
Debug.Assert(maskRegisterIdx < 8, $"Invalid mask register index {maskRegisterIdx}.");
byte aaa = (byte)(maskRegisterIdx & 0b111);
WriteByte(
(byte)(
(z ? 0x80 : 0) |
(ll << 5) |
(bcast ? 0x10 : 0) |
(vp ? 8 : 0) |
aaa));
}
private void WriteCompactInst(Operand operand, int opCode) private void WriteCompactInst(Operand operand, int opCode)
{ {
int regIndex = operand.GetRegister().Index; int regIndex = operand.GetRegister().Index;

View File

@@ -20,6 +20,7 @@ namespace ARMeilleure.CodeGen.X86
Reg8Dest = 1 << 2, Reg8Dest = 1 << 2,
RexW = 1 << 3, RexW = 1 << 3,
Vex = 1 << 4, Vex = 1 << 4,
Evex = 1 << 5,
PrefixBit = 16, PrefixBit = 16,
PrefixMask = 7 << PrefixBit, PrefixMask = 7 << PrefixBit,
@@ -278,6 +279,7 @@ namespace ARMeilleure.CodeGen.X86
Add(X86Instruction.Vfnmsub231sd, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x000f38bf, InstructionFlags.Vex | InstructionFlags.Prefix66 | InstructionFlags.RexW)); Add(X86Instruction.Vfnmsub231sd, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x000f38bf, InstructionFlags.Vex | InstructionFlags.Prefix66 | InstructionFlags.RexW));
Add(X86Instruction.Vfnmsub231ss, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x000f38bf, InstructionFlags.Vex | InstructionFlags.Prefix66)); Add(X86Instruction.Vfnmsub231ss, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x000f38bf, InstructionFlags.Vex | InstructionFlags.Prefix66));
Add(X86Instruction.Vpblendvb, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x000f3a4c, InstructionFlags.Vex | InstructionFlags.Prefix66)); Add(X86Instruction.Vpblendvb, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x000f3a4c, InstructionFlags.Vex | InstructionFlags.Prefix66));
Add(X86Instruction.Vpternlogd, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x000f3a25, InstructionFlags.Evex | InstructionFlags.Prefix66));
Add(X86Instruction.Xor, new InstructionInfo(0x00000031, 0x06000083, 0x06000081, BadOp, 0x00000033, InstructionFlags.None)); Add(X86Instruction.Xor, new InstructionInfo(0x00000031, 0x06000083, 0x06000081, BadOp, 0x00000033, InstructionFlags.None));
Add(X86Instruction.Xorpd, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x00000f57, InstructionFlags.Vex | InstructionFlags.Prefix66)); Add(X86Instruction.Xorpd, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x00000f57, InstructionFlags.Vex | InstructionFlags.Prefix66));
Add(X86Instruction.Xorps, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x00000f57, InstructionFlags.Vex)); Add(X86Instruction.Xorps, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x00000f57, InstructionFlags.Vex));

View File

@@ -1,10 +1,14 @@
using Ryujinx.Memory;
using System; using System;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics.X86;
namespace ARMeilleure.CodeGen.X86 namespace ARMeilleure.CodeGen.X86
{ {
static class HardwareCapabilities static class HardwareCapabilities
{ {
private delegate uint GetXcr0();
static HardwareCapabilities() static HardwareCapabilities()
{ {
if (!X86Base.IsSupported) if (!X86Base.IsSupported)
@@ -24,6 +28,28 @@ namespace ARMeilleure.CodeGen.X86
FeatureInfo7Ebx = (FeatureFlags7Ebx)ebx7; FeatureInfo7Ebx = (FeatureFlags7Ebx)ebx7;
FeatureInfo7Ecx = (FeatureFlags7Ecx)ecx7; FeatureInfo7Ecx = (FeatureFlags7Ecx)ecx7;
} }
Xcr0InfoEax = (Xcr0FlagsEax)GetXcr0Eax();
}
private static uint GetXcr0Eax()
{
ReadOnlySpan<byte> asmGetXcr0 = new byte[]
{
0x31, 0xc9, // xor ecx, ecx
0xf, 0x01, 0xd0, // xgetbv
0xc3, // ret
};
using MemoryBlock memGetXcr0 = new MemoryBlock((ulong)asmGetXcr0.Length);
memGetXcr0.Write(0, asmGetXcr0);
memGetXcr0.Reprotect(0, (ulong)asmGetXcr0.Length, MemoryPermission.ReadAndExecute);
var fGetXcr0 = Marshal.GetDelegateForFunctionPointer<GetXcr0>(memGetXcr0.Pointer);
return fGetXcr0();
} }
[Flags] [Flags]
@@ -44,6 +70,7 @@ namespace ARMeilleure.CodeGen.X86
Sse42 = 1 << 20, Sse42 = 1 << 20,
Popcnt = 1 << 23, Popcnt = 1 << 23,
Aes = 1 << 25, Aes = 1 << 25,
Osxsave = 1 << 27,
Avx = 1 << 28, Avx = 1 << 28,
F16c = 1 << 29 F16c = 1 << 29
} }
@@ -52,7 +79,11 @@ namespace ARMeilleure.CodeGen.X86
public enum FeatureFlags7Ebx public enum FeatureFlags7Ebx
{ {
Avx2 = 1 << 5, Avx2 = 1 << 5,
Sha = 1 << 29 Avx512f = 1 << 16,
Avx512dq = 1 << 17,
Sha = 1 << 29,
Avx512bw = 1 << 30,
Avx512vl = 1 << 31
} }
[Flags] [Flags]
@@ -61,10 +92,21 @@ namespace ARMeilleure.CodeGen.X86
Gfni = 1 << 8, Gfni = 1 << 8,
} }
[Flags]
public enum Xcr0FlagsEax
{
Sse = 1 << 1,
YmmHi128 = 1 << 2,
Opmask = 1 << 5,
ZmmHi256 = 1 << 6,
Hi16Zmm = 1 << 7
}
public static FeatureFlags1Edx FeatureInfo1Edx { get; } public static FeatureFlags1Edx FeatureInfo1Edx { get; }
public static FeatureFlags1Ecx FeatureInfo1Ecx { get; } public static FeatureFlags1Ecx FeatureInfo1Ecx { get; }
public static FeatureFlags7Ebx FeatureInfo7Ebx { get; } = 0; public static FeatureFlags7Ebx FeatureInfo7Ebx { get; } = 0;
public static FeatureFlags7Ecx FeatureInfo7Ecx { get; } = 0; public static FeatureFlags7Ecx FeatureInfo7Ecx { get; } = 0;
public static Xcr0FlagsEax Xcr0InfoEax { get; } = 0;
public static bool SupportsSse => FeatureInfo1Edx.HasFlag(FeatureFlags1Edx.Sse); public static bool SupportsSse => FeatureInfo1Edx.HasFlag(FeatureFlags1Edx.Sse);
public static bool SupportsSse2 => FeatureInfo1Edx.HasFlag(FeatureFlags1Edx.Sse2); public static bool SupportsSse2 => FeatureInfo1Edx.HasFlag(FeatureFlags1Edx.Sse2);
@@ -76,8 +118,13 @@ namespace ARMeilleure.CodeGen.X86
public static bool SupportsSse42 => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Sse42); public static bool SupportsSse42 => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Sse42);
public static bool SupportsPopcnt => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Popcnt); public static bool SupportsPopcnt => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Popcnt);
public static bool SupportsAesni => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Aes); public static bool SupportsAesni => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Aes);
public static bool SupportsAvx => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Avx); public static bool SupportsAvx => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Avx | FeatureFlags1Ecx.Osxsave) && Xcr0InfoEax.HasFlag(Xcr0FlagsEax.Sse | Xcr0FlagsEax.YmmHi128);
public static bool SupportsAvx2 => FeatureInfo7Ebx.HasFlag(FeatureFlags7Ebx.Avx2) && SupportsAvx; public static bool SupportsAvx2 => FeatureInfo7Ebx.HasFlag(FeatureFlags7Ebx.Avx2) && SupportsAvx;
public static bool SupportsAvx512F => FeatureInfo7Ebx.HasFlag(FeatureFlags7Ebx.Avx512f) && FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.Osxsave)
&& Xcr0InfoEax.HasFlag(Xcr0FlagsEax.Sse | Xcr0FlagsEax.YmmHi128 | Xcr0FlagsEax.Opmask | Xcr0FlagsEax.ZmmHi256 | Xcr0FlagsEax.Hi16Zmm);
public static bool SupportsAvx512Vl => FeatureInfo7Ebx.HasFlag(FeatureFlags7Ebx.Avx512vl) && SupportsAvx512F;
public static bool SupportsAvx512Bw => FeatureInfo7Ebx.HasFlag(FeatureFlags7Ebx.Avx512bw) && SupportsAvx512F;
public static bool SupportsAvx512Dq => FeatureInfo7Ebx.HasFlag(FeatureFlags7Ebx.Avx512dq) && SupportsAvx512F;
public static bool SupportsF16c => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.F16c); public static bool SupportsF16c => FeatureInfo1Ecx.HasFlag(FeatureFlags1Ecx.F16c);
public static bool SupportsSha => FeatureInfo7Ebx.HasFlag(FeatureFlags7Ebx.Sha); public static bool SupportsSha => FeatureInfo7Ebx.HasFlag(FeatureFlags7Ebx.Sha);
public static bool SupportsGfni => FeatureInfo7Ecx.HasFlag(FeatureFlags7Ecx.Gfni); public static bool SupportsGfni => FeatureInfo7Ecx.HasFlag(FeatureFlags7Ecx.Gfni);
@@ -85,5 +132,6 @@ namespace ARMeilleure.CodeGen.X86
public static bool ForceLegacySse { get; set; } public static bool ForceLegacySse { get; set; }
public static bool SupportsVexEncoding => SupportsAvx && !ForceLegacySse; public static bool SupportsVexEncoding => SupportsAvx && !ForceLegacySse;
public static bool SupportsEvexEncoding => SupportsAvx512F && !ForceLegacySse;
} }
} }

View File

@@ -182,6 +182,7 @@ namespace ARMeilleure.CodeGen.X86
Add(Intrinsic.X86Vfnmadd231ss, new IntrinsicInfo(X86Instruction.Vfnmadd231ss, IntrinsicType.Fma)); Add(Intrinsic.X86Vfnmadd231ss, new IntrinsicInfo(X86Instruction.Vfnmadd231ss, IntrinsicType.Fma));
Add(Intrinsic.X86Vfnmsub231sd, new IntrinsicInfo(X86Instruction.Vfnmsub231sd, IntrinsicType.Fma)); Add(Intrinsic.X86Vfnmsub231sd, new IntrinsicInfo(X86Instruction.Vfnmsub231sd, IntrinsicType.Fma));
Add(Intrinsic.X86Vfnmsub231ss, new IntrinsicInfo(X86Instruction.Vfnmsub231ss, IntrinsicType.Fma)); Add(Intrinsic.X86Vfnmsub231ss, new IntrinsicInfo(X86Instruction.Vfnmsub231ss, IntrinsicType.Fma));
Add(Intrinsic.X86Vpternlogd, new IntrinsicInfo(X86Instruction.Vpternlogd, IntrinsicType.TernaryImm));
Add(Intrinsic.X86Xorpd, new IntrinsicInfo(X86Instruction.Xorpd, IntrinsicType.Binary)); Add(Intrinsic.X86Xorpd, new IntrinsicInfo(X86Instruction.Xorpd, IntrinsicType.Binary));
Add(Intrinsic.X86Xorps, new IntrinsicInfo(X86Instruction.Xorps, IntrinsicType.Binary)); Add(Intrinsic.X86Xorps, new IntrinsicInfo(X86Instruction.Xorps, IntrinsicType.Binary));
} }

View File

@@ -219,6 +219,7 @@ namespace ARMeilleure.CodeGen.X86
Vfnmsub231sd, Vfnmsub231sd,
Vfnmsub231ss, Vfnmsub231ss,
Vpblendvb, Vpblendvb,
Vpternlogd,
Xor, Xor,
Xorpd, Xorpd,
Xorps, Xorps,

View File

@@ -224,7 +224,22 @@ namespace ARMeilleure.Instructions
public static void Not_V(ArmEmitterContext context) public static void Not_V(ArmEmitterContext context)
{ {
if (Optimizations.UseSse2) if (Optimizations.UseAvx512Ortho)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
Operand n = GetVec(op.Rn);
Operand res = context.AddIntrinsic(Intrinsic.X86Vpternlogd, n, n, Const(0b01010101));
if (op.RegisterSize == RegisterSize.Simd64)
{
res = context.VectorZeroUpper64(res);
}
context.Copy(GetVec(op.Rd), res);
}
else if (Optimizations.UseSse2)
{ {
OpCodeSimd op = (OpCodeSimd)context.CurrOp; OpCodeSimd op = (OpCodeSimd)context.CurrOp;

View File

@@ -171,6 +171,7 @@ namespace ARMeilleure.IntermediateRepresentation
X86Vfnmadd231ss, X86Vfnmadd231ss,
X86Vfnmsub231sd, X86Vfnmsub231sd,
X86Vfnmsub231ss, X86Vfnmsub231ss,
X86Vpternlogd,
X86Xorpd, X86Xorpd,
X86Xorps X86Xorps
} }

View File

@@ -17,6 +17,10 @@ namespace ARMeilleure
public static bool UseSse42IfAvailable { get; set; } = true; public static bool UseSse42IfAvailable { get; set; } = true;
public static bool UsePopCntIfAvailable { get; set; } = true; public static bool UsePopCntIfAvailable { get; set; } = true;
public static bool UseAvxIfAvailable { get; set; } = true; public static bool UseAvxIfAvailable { get; set; } = true;
public static bool UseAvx512FIfAvailable { get; set; } = true;
public static bool UseAvx512VlIfAvailable { get; set; } = true;
public static bool UseAvx512BwIfAvailable { get; set; } = true;
public static bool UseAvx512DqIfAvailable { get; set; } = true;
public static bool UseF16cIfAvailable { get; set; } = true; public static bool UseF16cIfAvailable { get; set; } = true;
public static bool UseFmaIfAvailable { get; set; } = true; public static bool UseFmaIfAvailable { get; set; } = true;
public static bool UseAesniIfAvailable { get; set; } = true; public static bool UseAesniIfAvailable { get; set; } = true;
@@ -38,11 +42,18 @@ namespace ARMeilleure
internal static bool UseSse42 => UseSse42IfAvailable && HardwareCapabilities.SupportsSse42; internal static bool UseSse42 => UseSse42IfAvailable && HardwareCapabilities.SupportsSse42;
internal static bool UsePopCnt => UsePopCntIfAvailable && HardwareCapabilities.SupportsPopcnt; internal static bool UsePopCnt => UsePopCntIfAvailable && HardwareCapabilities.SupportsPopcnt;
internal static bool UseAvx => UseAvxIfAvailable && HardwareCapabilities.SupportsAvx && !ForceLegacySse; internal static bool UseAvx => UseAvxIfAvailable && HardwareCapabilities.SupportsAvx && !ForceLegacySse;
internal static bool UseAvx512F => UseAvx512FIfAvailable && HardwareCapabilities.SupportsAvx512F && !ForceLegacySse;
internal static bool UseAvx512Vl => UseAvx512VlIfAvailable && HardwareCapabilities.SupportsAvx512Vl && !ForceLegacySse;
internal static bool UseAvx512Bw => UseAvx512BwIfAvailable && HardwareCapabilities.SupportsAvx512Bw && !ForceLegacySse;
internal static bool UseAvx512Dq => UseAvx512DqIfAvailable && HardwareCapabilities.SupportsAvx512Dq && !ForceLegacySse;
internal static bool UseF16c => UseF16cIfAvailable && HardwareCapabilities.SupportsF16c; internal static bool UseF16c => UseF16cIfAvailable && HardwareCapabilities.SupportsF16c;
internal static bool UseFma => UseFmaIfAvailable && HardwareCapabilities.SupportsFma; internal static bool UseFma => UseFmaIfAvailable && HardwareCapabilities.SupportsFma;
internal static bool UseAesni => UseAesniIfAvailable && HardwareCapabilities.SupportsAesni; internal static bool UseAesni => UseAesniIfAvailable && HardwareCapabilities.SupportsAesni;
internal static bool UsePclmulqdq => UsePclmulqdqIfAvailable && HardwareCapabilities.SupportsPclmulqdq; internal static bool UsePclmulqdq => UsePclmulqdqIfAvailable && HardwareCapabilities.SupportsPclmulqdq;
internal static bool UseSha => UseShaIfAvailable && HardwareCapabilities.SupportsSha; internal static bool UseSha => UseShaIfAvailable && HardwareCapabilities.SupportsSha;
internal static bool UseGfni => UseGfniIfAvailable && HardwareCapabilities.SupportsGfni; internal static bool UseGfni => UseGfniIfAvailable && HardwareCapabilities.SupportsGfni;
internal static bool UseAvx512Ortho => UseAvx512F && UseAvx512Vl;
internal static bool UseAvx512OrthoFloat => UseAvx512Ortho && UseAvx512Dq;
} }
} }

View File

@@ -18,17 +18,17 @@ namespace ARMeilleure.Signal
public IntPtr sa_restorer; public IntPtr sa_restorer;
} }
static class UnixSignalHandlerRegistration static partial class UnixSignalHandlerRegistration
{ {
private const int SIGSEGV = 11; private const int SIGSEGV = 11;
private const int SIGBUS = 10; private const int SIGBUS = 10;
private const int SA_SIGINFO = 0x00000004; private const int SA_SIGINFO = 0x00000004;
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
private static extern int sigaction(int signum, ref SigAction sigAction, out SigAction oldAction); private static partial int sigaction(int signum, ref SigAction sigAction, out SigAction oldAction);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
private static extern int sigemptyset(ref SigSet set); private static partial int sigemptyset(ref SigSet set);
public static SigAction RegisterExceptionHandler(IntPtr action) public static SigAction RegisterExceptionHandler(IntPtr action)
{ {

View File

@@ -3,19 +3,19 @@ using System.Runtime.InteropServices;
namespace ARMeilleure.Signal namespace ARMeilleure.Signal
{ {
unsafe class WindowsSignalHandlerRegistration unsafe partial class WindowsSignalHandlerRegistration
{ {
[DllImport("kernel32.dll")] [LibraryImport("kernel32.dll")]
private static extern IntPtr AddVectoredExceptionHandler(uint first, IntPtr handler); private static partial IntPtr AddVectoredExceptionHandler(uint first, IntPtr handler);
[DllImport("kernel32.dll")] [LibraryImport("kernel32.dll")]
private static extern ulong RemoveVectoredExceptionHandler(IntPtr handle); private static partial ulong RemoveVectoredExceptionHandler(IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)] [LibraryImport("kernel32.dll", SetLastError = true, EntryPoint = "LoadLibraryA")]
static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName); private static partial IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); private static partial IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string procName);
private static IntPtr _getCurrentThreadIdPtr; private static IntPtr _getCurrentThreadIdPtr;

View File

@@ -7,7 +7,7 @@ using System.Runtime.InteropServices;
namespace ARMeilleure.Translation.Cache namespace ARMeilleure.Translation.Cache
{ {
static class JitUnwindWindows static partial class JitUnwindWindows
{ {
private const int MaxUnwindCodesArraySize = 32; // Must be an even value. private const int MaxUnwindCodesArraySize = 32; // Must be an even value.
@@ -42,14 +42,15 @@ namespace ARMeilleure.Translation.Cache
private unsafe delegate RuntimeFunction* GetRuntimeFunctionCallback(ulong controlPc, IntPtr context); private unsafe delegate RuntimeFunction* GetRuntimeFunctionCallback(ulong controlPc, IntPtr context);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] [LibraryImport("kernel32.dll")]
private static unsafe extern bool RtlInstallFunctionTableCallback( [return: MarshalAs(UnmanagedType.Bool)]
private static unsafe partial bool RtlInstallFunctionTableCallback(
ulong tableIdentifier, ulong tableIdentifier,
ulong baseAddress, ulong baseAddress,
uint length, uint length,
GetRuntimeFunctionCallback callback, GetRuntimeFunctionCallback callback,
IntPtr context, IntPtr context,
string outOfProcessCallbackDll); [MarshalAs(UnmanagedType.LPWStr)] string outOfProcessCallbackDll);
private static GetRuntimeFunctionCallback _getRuntimeFunctionCallback; private static GetRuntimeFunctionCallback _getRuntimeFunctionCallback;

View File

@@ -27,7 +27,7 @@ namespace ARMeilleure.Translation.PTC
private const string OuterHeaderMagicString = "PTCohd\0\0"; private const string OuterHeaderMagicString = "PTCohd\0\0";
private const string InnerHeaderMagicString = "PTCihd\0\0"; private const string InnerHeaderMagicString = "PTCihd\0\0";
private const uint InternalVersion = 3713; //! To be incremented manually for each change to the ARMeilleure project. private const uint InternalVersion = 3714; //! To be incremented manually for each change to the ARMeilleure project.
private const string ActualDir = "0"; private const string ActualDir = "0";
private const string BackupDir = "1"; private const string BackupDir = "1";
@@ -952,7 +952,8 @@ namespace ARMeilleure.Translation.PTC
(uint)HardwareCapabilities.FeatureInfo1Ecx, (uint)HardwareCapabilities.FeatureInfo1Ecx,
(uint)HardwareCapabilities.FeatureInfo1Edx, (uint)HardwareCapabilities.FeatureInfo1Edx,
(uint)HardwareCapabilities.FeatureInfo7Ebx, (uint)HardwareCapabilities.FeatureInfo7Ebx,
(uint)HardwareCapabilities.FeatureInfo7Ecx); (uint)HardwareCapabilities.FeatureInfo7Ecx,
(uint)HardwareCapabilities.Xcr0InfoEax);
} }
private static byte GetMemoryManagerMode() private static byte GetMemoryManagerMode()
@@ -972,7 +973,7 @@ namespace ARMeilleure.Translation.PTC
return osPlatform; return osPlatform;
} }
[StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 58*/)] [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 62*/)]
private struct OuterHeader private struct OuterHeader
{ {
public ulong Magic; public ulong Magic;
@@ -1003,8 +1004,8 @@ namespace ARMeilleure.Translation.PTC
} }
} }
[StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 16*/)] [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 20*/)]
private record struct FeatureInfo(uint FeatureInfo0, uint FeatureInfo1, uint FeatureInfo2, uint FeatureInfo3); private record struct FeatureInfo(uint FeatureInfo0, uint FeatureInfo1, uint FeatureInfo2, uint FeatureInfo3, uint FeatureInfo4);
[StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 128*/)] [StructLayout(LayoutKind.Sequential, Pack = 1/*, Size = 128*/)]
private struct InnerHeader private struct InnerHeader

54
Directory.Packages.props Normal file
View File

@@ -0,0 +1,54 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Avalonia" Version="0.10.18" />
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="0.10.18" />
<PackageVersion Include="Avalonia.Desktop" Version="0.10.18" />
<PackageVersion Include="Avalonia.Diagnostics" Version="0.10.18" />
<PackageVersion Include="Avalonia.Markup.Xaml.Loader" Version="0.10.18" />
<PackageVersion Include="Avalonia.Svg" Version="0.10.18" />
<PackageVersion Include="Avalonia.Svg.Skia" Version="0.10.18" />
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
<PackageVersion Include="Concentus" Version="1.1.7" />
<PackageVersion Include="Crc32.NET" Version="1.2.0" />
<PackageVersion Include="DiscordRichPresence" Version="1.1.3.18" />
<PackageVersion Include="DynamicData" Version="7.12.11" />
<PackageVersion Include="FluentAvaloniaUI" Version="1.4.5" />
<PackageVersion Include="GtkSharp.Dependencies" Version="1.1.1" />
<PackageVersion Include="GtkSharp.Dependencies.osx" Version="0.0.5" />
<PackageVersion Include="jp2masa.Avalonia.Flexbox" Version="0.2.0" />
<PackageVersion Include="LibHac" Version="0.17.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.4.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
<PackageVersion Include="MsgPack.Cli" Version="1.0.1" />
<PackageVersion Include="NUnit" Version="3.13.3" />
<PackageVersion Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageVersion Include="OpenTK.Core" Version="4.7.5" />
<PackageVersion Include="OpenTK.Graphics" Version="4.7.5" />
<PackageVersion Include="OpenTK.OpenAL" Version="4.7.5" />
<PackageVersion Include="OpenTK.Windowing.GraphicsLibraryFramework" Version="4.7.5" />
<PackageVersion Include="Ryujinx.Audio.OpenAL.Dependencies" Version="1.21.0.1" />
<PackageVersion Include="Ryujinx.Graphics.Nvdec.Dependencies" Version="5.0.1-build13" />
<PackageVersion Include="Ryujinx.Graphics.Vulkan.Dependencies.MoltenVK" Version="1.2.0" />
<PackageVersion Include="Ryujinx.GtkSharp" Version="3.24.24.59-ryujinx" />
<PackageVersion Include="Ryujinx.SDL2-CS" Version="2.24.2-build21" />
<PackageVersion Include="shaderc.net" Version="0.1.0" />
<PackageVersion Include="SharpZipLib" Version="1.4.1" />
<PackageVersion Include="Silk.NET.Vulkan" Version="2.16.0" />
<PackageVersion Include="Silk.NET.Vulkan.Extensions.EXT" Version="2.16.0" />
<PackageVersion Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.16.0" />
<PackageVersion Include="SixLabors.ImageSharp" Version="1.0.4" />
<PackageVersion Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta11" />
<PackageVersion Include="SPB" Version="0.0.4-build28" />
<PackageVersion Include="System.Drawing.Common" Version="7.0.0" />
<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="6.25.1" />
<PackageVersion Include="System.IO.FileSystem.Primitives" Version="4.3.0" />
<PackageVersion Include="System.Management" Version="7.0.0" />
<PackageVersion Include="System.Net.NameResolution" Version="4.3.0" />
<PackageVersion Include="System.Threading.ThreadPool" Version="4.3.0" />
<PackageVersion Include="XamlNameReferenceGenerator" Version="1.5.1" />
</ItemGroup>
</Project>

View File

@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="OpenTK.OpenAL" Version="4.7.5" /> <PackageReference Include="OpenTK.OpenAL" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -17,7 +17,7 @@ using Ryujinx.Ava.Ui.Windows;
using Ryujinx.Common; using Ryujinx.Common;
using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration;
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.Common.System; using Ryujinx.Common.SystemInterop;
using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.GAL.Multithreading; using Ryujinx.Graphics.GAL.Multithreading;
using Ryujinx.Graphics.Gpu; using Ryujinx.Graphics.Gpu;

View File

@@ -280,7 +280,7 @@
"ControllerSettingsRemoveProfileToolTip": "Remove Profile", "ControllerSettingsRemoveProfileToolTip": "Remove Profile",
"ControllerSettingsSaveProfileToolTip": "Save Profile", "ControllerSettingsSaveProfileToolTip": "Save Profile",
"MenuBarFileToolsTakeScreenshot": "Take Screenshot", "MenuBarFileToolsTakeScreenshot": "Take Screenshot",
"MenuBarFileToolsHideUi": "Hide Ui", "MenuBarFileToolsHideUi": "Hide UI",
"GameListContextMenuToggleFavorite": "Toggle Favorite", "GameListContextMenuToggleFavorite": "Toggle Favorite",
"GameListContextMenuToggleFavoriteToolTip": "Toggle Favorite status of Game", "GameListContextMenuToggleFavoriteToolTip": "Toggle Favorite status of Game",
"SettingsTabGeneralTheme": "Theme", "SettingsTabGeneralTheme": "Theme",

View File

@@ -8,7 +8,7 @@ namespace Ryujinx.Ava.Ui.Helper
public delegate void UpdateBoundsCallbackDelegate(Rect rect); public delegate void UpdateBoundsCallbackDelegate(Rect rect);
[SupportedOSPlatform("macos")] [SupportedOSPlatform("macos")]
static class MetalHelper static partial class MetalHelper
{ {
private const string LibObjCImport = "/usr/lib/libobjc.A.dylib"; private const string LibObjCImport = "/usr/lib/libobjc.A.dylib";
@@ -100,28 +100,28 @@ namespace Ryujinx.Ava.Ui.Helper
// TODO // TODO
} }
[DllImport(LibObjCImport)] [LibraryImport(LibObjCImport)]
private static unsafe extern IntPtr sel_registerName(byte* data); private static unsafe partial IntPtr sel_registerName(byte* data);
[DllImport(LibObjCImport)] [LibraryImport(LibObjCImport)]
private static unsafe extern IntPtr objc_getClass(byte* data); private static unsafe partial IntPtr objc_getClass(byte* data);
[DllImport(LibObjCImport)] [LibraryImport(LibObjCImport)]
private static extern void objc_msgSend(IntPtr receiver, Selector selector); private static partial void objc_msgSend(IntPtr receiver, Selector selector);
[DllImport(LibObjCImport)] [LibraryImport(LibObjCImport)]
private static extern void objc_msgSend(IntPtr receiver, Selector selector, byte value); private static partial void objc_msgSend(IntPtr receiver, Selector selector, byte value);
[DllImport(LibObjCImport)] [LibraryImport(LibObjCImport)]
private static extern void objc_msgSend(IntPtr receiver, Selector selector, IntPtr value); private static partial void objc_msgSend(IntPtr receiver, Selector selector, IntPtr value);
[DllImport(LibObjCImport)] [LibraryImport(LibObjCImport)]
private static extern void objc_msgSend(IntPtr receiver, Selector selector, NSRect point); private static partial void objc_msgSend(IntPtr receiver, Selector selector, NSRect point);
[DllImport(LibObjCImport)] [LibraryImport(LibObjCImport)]
private static extern void objc_msgSend(IntPtr receiver, Selector selector, double value); private static partial void objc_msgSend(IntPtr receiver, Selector selector, double value);
[DllImport(LibObjCImport, EntryPoint = "objc_msgSend")] [LibraryImport(LibObjCImport, EntryPoint = "objc_msgSend")]
private static extern IntPtr IntPtr_objc_msgSend(IntPtr receiver, Selector selector); private static partial IntPtr IntPtr_objc_msgSend(IntPtr receiver, Selector selector);
} }
} }

View File

@@ -7,8 +7,7 @@ namespace Ryujinx.Ava.Input
{ {
internal static class AvaloniaKeyboardMappingHelper internal static class AvaloniaKeyboardMappingHelper
{ {
private static readonly AvaKey[] _keyMapping = new AvaKey[(int)Key.Count] private static readonly AvaKey[] _keyMapping = {
{
// NOTE: Invalid // NOTE: Invalid
AvaKey.None, AvaKey.None,
@@ -151,16 +150,16 @@ namespace Ryujinx.Ava.Input
static AvaloniaKeyboardMappingHelper() static AvaloniaKeyboardMappingHelper()
{ {
var inputKeys = Enum.GetValues(typeof(Key)); var inputKeys = Enum.GetValues<Key>();
// NOTE: Avalonia.Input.Key is not contiguous and quite large, so use a dictionary instead of an array. // NOTE: Avalonia.Input.Key is not contiguous and quite large, so use a dictionary instead of an array.
_avaKeyMapping = new Dictionary<AvaKey, Key>(); _avaKeyMapping = new Dictionary<AvaKey, Key>();
foreach (var key in inputKeys) foreach (var key in inputKeys)
{ {
if (TryGetAvaKey((Key)key, out var index)) if (TryGetAvaKey(key, out var index))
{ {
_avaKeyMapping[index] = (Key)key; _avaKeyMapping[index] = key;
} }
} }
} }

View File

@@ -11,6 +11,7 @@ using Ryujinx.Ava.Ui.Controls;
using Ryujinx.Ava.Ui.Windows; using Ryujinx.Ava.Ui.Windows;
using Ryujinx.Common; using Ryujinx.Common;
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.Ui.Common.Helper;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
@@ -278,14 +279,15 @@ namespace Ryujinx.Modules
{ {
string ryuName = Path.GetFileName(Environment.ProcessPath); string ryuName = Path.GetFileName(Environment.ProcessPath);
string ryuExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ryuName); string ryuExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ryuName);
var ryuArg = Environment.GetCommandLineArgs().Skip(1);
if (!OperatingSystem.IsWindows()) if (!Path.Exists(ryuExe))
{ {
chmod(ryuExe, Convert.ToUInt32("0777", 8)); ryuExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, OperatingSystem.IsWindows() ? "Ryujinx.exe" : "Ryujinx");
} }
Process.Start(ryuExe, ryuArg); SetFileExecutable(ryuExe);
Process.Start(ryuExe, CommandLineState.Arguments);
Environment.Exit(0); Environment.Exit(0);
} }
@@ -456,16 +458,19 @@ namespace Ryujinx.Modules
worker.Start(); worker.Start();
} }
[DllImport("libc", SetLastError = true)] private static void SetFileExecutable(string path)
private static extern int chmod(string path, uint mode);
private static void SetUnixPermissions()
{ {
string ryuBin = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx"); const UnixFileMode ExecutableFileMode = UnixFileMode.UserExecute |
UnixFileMode.UserWrite |
UnixFileMode.UserRead |
UnixFileMode.GroupRead |
UnixFileMode.GroupWrite |
UnixFileMode.OtherRead |
UnixFileMode.OtherWrite;
if (!OperatingSystem.IsWindows()) if (!OperatingSystem.IsWindows() && File.Exists(path))
{ {
chmod(ryuBin, 493); File.SetUnixFileMode(path, ExecutableFileMode);
} }
} }
@@ -586,7 +591,7 @@ namespace Ryujinx.Modules
Directory.Delete(UpdateDir, true); Directory.Delete(UpdateDir, true);
SetUnixPermissions(); SetFileExecutable(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Ryujinx"));
UpdateSuccessful = true; UpdateSuccessful = true;

View File

@@ -6,7 +6,7 @@ using Ryujinx.Common;
using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration;
using Ryujinx.Common.GraphicsDriver; using Ryujinx.Common.GraphicsDriver;
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.Common.System; using Ryujinx.Common.SystemInterop;
using Ryujinx.Common.SystemInfo; using Ryujinx.Common.SystemInfo;
using Ryujinx.Modules; using Ryujinx.Modules;
using Ryujinx.SDL2.Common; using Ryujinx.SDL2.Common;
@@ -20,7 +20,7 @@ using System.Threading.Tasks;
namespace Ryujinx.Ava namespace Ryujinx.Ava
{ {
internal class Program internal partial class Program
{ {
public static double WindowScaleFactor { get; set; } public static double WindowScaleFactor { get; set; }
public static double DesktopScaleFactor { get; set; } = 1.0; public static double DesktopScaleFactor { get; set; } = 1.0;
@@ -28,8 +28,8 @@ namespace Ryujinx.Ava
public static string ConfigurationPath { get; private set; } public static string ConfigurationPath { get; private set; }
public static bool PreviewerDetached { get; private set; } public static bool PreviewerDetached { get; private set; }
[DllImport("user32.dll", SetLastError = true)] [LibraryImport("user32.dll", SetLastError = true)]
public static extern int MessageBoxA(IntPtr hWnd, string text, string caption, uint type); public static partial int MessageBoxA(IntPtr hWnd, [MarshalAs(UnmanagedType.LPStr)] string text, [MarshalAs(UnmanagedType.LPStr)] string caption, uint type);
private const uint MB_ICONWARNING = 0x30; private const uint MB_ICONWARNING = 0x30;

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<RuntimeIdentifiers>win10-x64;osx-x64;linux-x64</RuntimeIdentifiers> <RuntimeIdentifiers>win10-x64;osx-x64;linux-x64</RuntimeIdentifiers>
@@ -18,31 +18,31 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Avalonia" Version="0.10.18" /> <PackageReference Include="Avalonia" />
<PackageReference Include="Avalonia.Desktop" Version="0.10.18" /> <PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Diagnostics" Version="0.10.18" /> <PackageReference Include="Avalonia.Diagnostics" />
<PackageReference Include="Avalonia.Controls.DataGrid" Version="0.10.18" /> <PackageReference Include="Avalonia.Controls.DataGrid" />
<PackageReference Include="Avalonia.Markup.Xaml.Loader" Version="0.10.18" /> <PackageReference Include="Avalonia.Markup.Xaml.Loader" />
<PackageReference Include="Avalonia.Svg" Version="0.10.18" /> <PackageReference Include="Avalonia.Svg" />
<PackageReference Include="Avalonia.Svg.Skia" Version="0.10.18" /> <PackageReference Include="Avalonia.Svg.Skia" />
<PackageReference Include="jp2masa.Avalonia.Flexbox" Version="0.2.0" /> <PackageReference Include="jp2masa.Avalonia.Flexbox" />
<PackageReference Include="DynamicData" Version="7.12.11" /> <PackageReference Include="DynamicData" />
<PackageReference Include="FluentAvaloniaUI" Version="1.4.5" /> <PackageReference Include="FluentAvaloniaUI" />
<PackageReference Include="XamlNameReferenceGenerator" Version="1.5.1" /> <PackageReference Include="XamlNameReferenceGenerator" />
<PackageReference Include="OpenTK.Core" Version="4.7.5" /> <PackageReference Include="OpenTK.Core" />
<PackageReference Include="Ryujinx.Audio.OpenAL.Dependencies" Version="1.21.0.1" Condition="'$(RuntimeIdentifier)' != 'linux-x64' AND '$(RuntimeIdentifier)' != 'osx-x64' AND '$(RuntimeIdentifier)' != 'osx-arm64'" /> <PackageReference Include="Ryujinx.Audio.OpenAL.Dependencies" Condition="'$(RuntimeIdentifier)' != 'linux-x64' AND '$(RuntimeIdentifier)' != 'osx-x64' AND '$(RuntimeIdentifier)' != 'osx-arm64'" />
<PackageReference Include="Ryujinx.Graphics.Nvdec.Dependencies" Version="5.0.1-build12" /> <PackageReference Include="Ryujinx.Graphics.Nvdec.Dependencies" />
<PackageReference Include="Ryujinx.Graphics.Vulkan.Dependencies.MoltenVK" Version="1.2.0" Condition="'$(RuntimeIdentifier)' != 'linux-x64' AND '$(RuntimeIdentifier)' != 'win10-x64'" /> <PackageReference Include="Ryujinx.Graphics.Vulkan.Dependencies.MoltenVK" Condition="'$(RuntimeIdentifier)' != 'linux-x64' AND '$(RuntimeIdentifier)' != 'win10-x64'" />
<PackageReference Include="Silk.NET.Vulkan" Version="2.16.0" /> <PackageReference Include="Silk.NET.Vulkan" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.EXT" Version="2.16.0" /> <PackageReference Include="Silk.NET.Vulkan.Extensions.EXT" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.16.0" /> <PackageReference Include="Silk.NET.Vulkan.Extensions.KHR" />
<PackageReference Include="SPB" Version="0.0.4-build28" /> <PackageReference Include="SPB" />
<PackageReference Include="SharpZipLib" Version="1.4.1" /> <PackageReference Include="SharpZipLib" />
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.4" /> <PackageReference Include="SixLabors.ImageSharp" />
<!--NOTE: DO NOT REMOVE, THIS IS REQUIRED AS A RESULT OF A TRIMMING ISSUE IN AVALONIA --> <!--NOTE: DO NOT REMOVE, THIS IS REQUIRED AS A RESULT OF A TRIMMING ISSUE IN AVALONIA -->
<PackageReference Include="System.Drawing.Common" Version="7.0.0" /> <PackageReference Include="System.Drawing.Common" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -111,7 +111,7 @@ namespace Ryujinx.Ava.Ui.Controls
overlay.Position = window.PointToScreen(new Point()); overlay.Position = window.PointToScreen(new Point());
await contentDialog.ShowAsync(); await contentDialog.ShowAsync(overlay);
contentDialog.Closed -= handler; contentDialog.Closed -= handler;
overlay.Close(); overlay.Close();
}; };

View File

@@ -125,9 +125,9 @@ namespace Ryujinx.Ava.Ui.Controls
{ {
cbSize = Marshal.SizeOf<WNDCLASSEX>(), cbSize = Marshal.SizeOf<WNDCLASSEX>(),
hInstance = GetModuleHandle(null), hInstance = GetModuleHandle(null),
lpfnWndProc = _wndProcDelegate, lpfnWndProc = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate),
style = ClassStyles.CS_OWNDC, style = ClassStyles.CS_OWNDC,
lpszClassName = _className, lpszClassName = Marshal.StringToHGlobalUni(_className),
hCursor = LoadCursor(IntPtr.Zero, (IntPtr)Cursors.IDC_ARROW) hCursor = LoadCursor(IntPtr.Zero, (IntPtr)Cursors.IDC_ARROW)
}; };
@@ -149,6 +149,8 @@ namespace Ryujinx.Ava.Ui.Controls
WindowHandle = handle; WindowHandle = handle;
Marshal.FreeHGlobal(wndClassEx.lpszClassName);
return new PlatformHandle(WindowHandle, "HWND"); return new PlatformHandle(WindowHandle, "HWND");
} }

View File

@@ -5,7 +5,7 @@ using System.Runtime.Versioning;
namespace Ryujinx.Ava.Ui.Controls namespace Ryujinx.Ava.Ui.Controls
{ {
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
internal class Win32NativeInterop internal partial class Win32NativeInterop
{ {
[Flags] [Flags]
public enum ClassStyles : uint public enum ClassStyles : uint
@@ -48,58 +48,52 @@ namespace Ryujinx.Ava.Ui.Controls
[UnmanagedFunctionPointer(CallingConvention.Winapi)] [UnmanagedFunctionPointer(CallingConvention.Winapi)]
internal delegate IntPtr WindowProc(IntPtr hWnd, WindowsMessages msg, IntPtr wParam, IntPtr lParam); internal delegate IntPtr WindowProc(IntPtr hWnd, WindowsMessages msg, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] [StructLayout(LayoutKind.Sequential)]
public struct WNDCLASSEX public struct WNDCLASSEX
{ {
public int cbSize; public int cbSize;
public ClassStyles style; public ClassStyles style;
[MarshalAs(UnmanagedType.FunctionPtr)] public IntPtr lpfnWndProc; // not WndProc
public WindowProc lpfnWndProc; // not WndProc
public int cbClsExtra; public int cbClsExtra;
public int cbWndExtra; public int cbWndExtra;
public IntPtr hInstance; public IntPtr hInstance;
public IntPtr hIcon; public IntPtr hIcon;
public IntPtr hCursor; public IntPtr hCursor;
public IntPtr hbrBackground; public IntPtr hbrBackground;
[MarshalAs(UnmanagedType.LPWStr)] public IntPtr lpszMenuName;
public string lpszMenuName; public IntPtr lpszClassName;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpszClassName;
public IntPtr hIconSm; public IntPtr hIconSm;
public static WNDCLASSEX Create() public WNDCLASSEX()
{ {
return new WNDCLASSEX cbSize = Marshal.SizeOf<WNDCLASSEX>();
{
cbSize = Marshal.SizeOf<WNDCLASSEX>()
};
} }
} }
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [LibraryImport("user32.dll", SetLastError = true, EntryPoint = "RegisterClassExW")]
public static extern ushort RegisterClassEx(ref WNDCLASSEX param); public static partial ushort RegisterClassEx(ref WNDCLASSEX param);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [LibraryImport("user32.dll", SetLastError = true, EntryPoint = "UnregisterClassW")]
public static extern short UnregisterClass([MarshalAs(UnmanagedType.LPWStr)] string lpClassName, IntPtr instance); public static partial short UnregisterClass([MarshalAs(UnmanagedType.LPWStr)] string lpClassName, IntPtr instance);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] [LibraryImport("user32.dll", EntryPoint = "DefWindowProcW")]
public static extern IntPtr DefWindowProc(IntPtr hWnd, WindowsMessages msg, IntPtr wParam, IntPtr lParam); public static partial IntPtr DefWindowProc(IntPtr hWnd, WindowsMessages msg, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")] [LibraryImport("kernel32.dll", EntryPoint = "GetModuleHandleA")]
public static extern IntPtr GetModuleHandle(string lpModuleName); public static partial IntPtr GetModuleHandle([MarshalAs(UnmanagedType.LPStr)] string lpModuleName);
[DllImport("user32.dll", SetLastError = true)] [LibraryImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)] [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DestroyWindow(IntPtr hwnd); public static partial bool DestroyWindow(IntPtr hwnd);
[DllImport("user32.dll", SetLastError = true)] [LibraryImport("user32.dll", SetLastError = true, EntryPoint = "LoadCursorA")]
public static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName); public static partial IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [LibraryImport("user32.dll", SetLastError = true, EntryPoint = "CreateWindowExW")]
public static extern IntPtr CreateWindowEx( public static partial IntPtr CreateWindowEx(
uint dwExStyle, uint dwExStyle,
string lpClassName, [MarshalAs(UnmanagedType.LPWStr)] string lpClassName,
string lpWindowName, [MarshalAs(UnmanagedType.LPWStr)] string lpWindowName,
WindowStyles dwStyle, WindowStyles dwStyle,
int x, int x,
int y, int y,

View File

@@ -5,7 +5,7 @@ using System.Runtime.InteropServices;
namespace Ryujinx.Common.GraphicsDriver namespace Ryujinx.Common.GraphicsDriver
{ {
static class NVThreadedOptimization static partial class NVThreadedOptimization
{ {
private const string ProfileName = "Ryujinx Nvidia Profile"; private const string ProfileName = "Ryujinx Nvidia Profile";
@@ -19,8 +19,8 @@ namespace Ryujinx.Common.GraphicsDriver
private const uint NvAPI_DRS_SaveSettings_ID = 0xFCBC7E14; private const uint NvAPI_DRS_SaveSettings_ID = 0xFCBC7E14;
private const uint NvAPI_DRS_DestroySession_ID = 0x0DAD9CFF8; private const uint NvAPI_DRS_DestroySession_ID = 0x0DAD9CFF8;
[DllImport("nvapi64")] [LibraryImport("nvapi64")]
private static extern IntPtr nvapi_QueryInterface(uint id); private static partial IntPtr nvapi_QueryInterface(uint id);
private delegate int NvAPI_InitializeDelegate(); private delegate int NvAPI_InitializeDelegate();
private static NvAPI_InitializeDelegate NvAPI_Initialize; private static NvAPI_InitializeDelegate NvAPI_Initialize;
@@ -152,7 +152,7 @@ namespace Ryujinx.Common.GraphicsDriver
if (ptr != IntPtr.Zero) if (ptr != IntPtr.Zero)
{ {
return Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)) as T; return Marshal.GetDelegateForFunctionPointer<T>(ptr);
} }
else else
{ {

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using System.Threading; using System.Threading;
@@ -12,7 +13,7 @@ namespace Ryujinx.Common.Memory.PartialUnmaps
/// State for partial unmaps. Intended to be used on Windows. /// State for partial unmaps. Intended to be used on Windows.
/// </summary> /// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)] [StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PartialUnmapState public partial struct PartialUnmapState
{ {
public NativeReaderWriterLock PartialUnmapLock; public NativeReaderWriterLock PartialUnmapLock;
public int PartialUnmapsCount; public int PartialUnmapsCount;
@@ -25,20 +26,22 @@ namespace Ryujinx.Common.Memory.PartialUnmaps
public readonly static IntPtr GlobalState; public readonly static IntPtr GlobalState;
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
[DllImport("kernel32.dll")] [LibraryImport("kernel32.dll")]
public static extern int GetCurrentThreadId(); public static partial int GetCurrentThreadId();
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenThread(int dwDesiredAccess, bool bInheritHandle, uint dwThreadId); private static partial IntPtr OpenThread(int dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwThreadId);
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject); [return: MarshalAs (UnmanagedType.Bool)]
public static partial bool CloseHandle(IntPtr hObject);
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
static extern bool GetExitCodeThread(IntPtr hThread, out uint lpExitCode); [return: MarshalAs(UnmanagedType.Bool)]
private static partial bool GetExitCodeThread(IntPtr hThread, out uint lpExitCode);
/// <summary> /// <summary>
/// Creates a global static PartialUnmapState and populates the field offsets. /// Creates a global static PartialUnmapState and populates the field offsets.

View File

@@ -6,8 +6,8 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="MsgPack.Cli" Version="1.0.1" /> <PackageReference Include="MsgPack.Cli" />
<PackageReference Include="System.Management" Version="7.0.0" /> <PackageReference Include="System.Management" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -8,7 +8,7 @@ using Ryujinx.Common.Logging;
namespace Ryujinx.Common.SystemInfo namespace Ryujinx.Common.SystemInfo
{ {
[SupportedOSPlatform("macos")] [SupportedOSPlatform("macos")]
class MacOSSystemInfo : SystemInfo partial class MacOSSystemInfo : SystemInfo
{ {
internal MacOSSystemInfo() internal MacOSSystemInfo()
{ {
@@ -60,8 +60,8 @@ namespace Ryujinx.Common.SystemInfo
private const string SystemLibraryName = "libSystem.dylib"; private const string SystemLibraryName = "libSystem.dylib";
[DllImport(SystemLibraryName, CharSet = CharSet.Ansi, SetLastError = true)] [LibraryImport(SystemLibraryName, SetLastError = true)]
private static extern int sysctlbyname(string name, IntPtr oldValue, ref ulong oldSize, IntPtr newValue, ulong newValueSize); private static partial int sysctlbyname([MarshalAs(UnmanagedType.LPStr)] string name, IntPtr oldValue, ref ulong oldSize, IntPtr newValue, ulong newValueSize);
private static int sysctlbyname(string name, IntPtr oldValue, ref ulong oldSize) private static int sysctlbyname(string name, IntPtr oldValue, ref ulong oldSize)
{ {
@@ -116,11 +116,11 @@ namespace Ryujinx.Common.SystemInfo
return res; return res;
} }
[DllImport(SystemLibraryName, CharSet = CharSet.Ansi, SetLastError = true)] [LibraryImport(SystemLibraryName, SetLastError = true)]
private static extern uint mach_host_self(); private static partial uint mach_host_self();
[DllImport(SystemLibraryName, CharSet = CharSet.Ansi, SetLastError = true)] [LibraryImport(SystemLibraryName, SetLastError = true)]
private static extern int host_page_size(uint host, ref uint out_page_size); private static partial int host_page_size(uint host, ref uint out_page_size);
[StructLayout(LayoutKind.Sequential, Pack = 8)] [StructLayout(LayoutKind.Sequential, Pack = 8)]
struct VMStatistics64 struct VMStatistics64
@@ -151,7 +151,7 @@ namespace Ryujinx.Common.SystemInfo
public ulong TotalUncompressedPagesInCompressor; public ulong TotalUncompressedPagesInCompressor;
} }
[DllImport(SystemLibraryName, CharSet = CharSet.Ansi, SetLastError = true)] [LibraryImport(SystemLibraryName, SetLastError = true)]
private static extern int host_statistics64(uint host_priv, int host_flavor, ref VMStatistics64 host_info64_out, ref uint host_info64_outCnt); private static partial int host_statistics64(uint host_priv, int host_flavor, ref VMStatistics64 host_info64_out, ref uint host_info64_outCnt);
} }
} }

View File

@@ -7,7 +7,7 @@ using Ryujinx.Common.Logging;
namespace Ryujinx.Common.SystemInfo namespace Ryujinx.Common.SystemInfo
{ {
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
class WindowsSystemInfo : SystemInfo partial class WindowsSystemInfo : SystemInfo
{ {
internal WindowsSystemInfo() internal WindowsSystemInfo()
{ {
@@ -18,7 +18,7 @@ namespace Ryujinx.Common.SystemInfo
private static (ulong Total, ulong Available) GetMemoryStats() private static (ulong Total, ulong Available) GetMemoryStats()
{ {
MemoryStatusEx memStatus = new MemoryStatusEx(); MemoryStatusEx memStatus = new MemoryStatusEx();
if (GlobalMemoryStatusEx(memStatus)) if (GlobalMemoryStatusEx(ref memStatus))
{ {
return (memStatus.TotalPhys, memStatus.AvailPhys); // Bytes return (memStatus.TotalPhys, memStatus.AvailPhys); // Bytes
} }
@@ -45,8 +45,8 @@ namespace Ryujinx.Common.SystemInfo
return Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER").Trim(); return Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER").Trim();
} }
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] [StructLayout(LayoutKind.Sequential)]
private class MemoryStatusEx private struct MemoryStatusEx
{ {
public uint Length; public uint Length;
public uint MemoryLoad; public uint MemoryLoad;
@@ -60,13 +60,13 @@ namespace Ryujinx.Common.SystemInfo
public MemoryStatusEx() public MemoryStatusEx()
{ {
Length = (uint)Marshal.SizeOf(typeof(MemoryStatusEx)); Length = (uint)Marshal.SizeOf<MemoryStatusEx>();
} }
} }
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)] [return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static partial bool GlobalMemoryStatusEx(ref MemoryStatusEx lpBuffer);
private static extern bool GlobalMemoryStatusEx([In, Out] MemoryStatusEx lpBuffer);
private static ManagementObjectCollection GetWMIObjects(string scope, string query) private static ManagementObjectCollection GetWMIObjects(string scope, string query)
{ {

View File

@@ -1,9 +1,9 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Ryujinx.Common.System namespace Ryujinx.Common.SystemInterop
{ {
public class DisplaySleep public partial class DisplaySleep
{ {
[Flags] [Flags]
enum EXECUTION_STATE : uint enum EXECUTION_STATE : uint
@@ -13,8 +13,8 @@ namespace Ryujinx.Common.System
ES_SYSTEM_REQUIRED = 0x00000001 ES_SYSTEM_REQUIRED = 0x00000001
} }
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags); private static partial EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
static public void Prevent() static public void Prevent()
{ {

View File

@@ -3,29 +3,30 @@ using System;
using System.Globalization; using System.Globalization;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Ryujinx.Common.System namespace Ryujinx.Common.SystemInterop
{ {
public static class ForceDpiAware public static partial class ForceDpiAware
{ {
[DllImport("user32.dll")] [LibraryImport("user32.dll")]
private static extern bool SetProcessDPIAware(); [return: MarshalAs(UnmanagedType.Bool)]
private static partial bool SetProcessDPIAware();
private const string X11LibraryName = "libX11.so.6"; private const string X11LibraryName = "libX11.so.6";
[DllImport(X11LibraryName)] [LibraryImport(X11LibraryName)]
private static extern IntPtr XOpenDisplay(string display); private static partial IntPtr XOpenDisplay([MarshalAs(UnmanagedType.LPStr)] string display);
[DllImport(X11LibraryName)] [LibraryImport(X11LibraryName)]
private static extern IntPtr XGetDefault(IntPtr display, string program, string option); private static partial IntPtr XGetDefault(IntPtr display, [MarshalAs(UnmanagedType.LPStr)] string program, [MarshalAs(UnmanagedType.LPStr)] string option);
[DllImport(X11LibraryName)] [LibraryImport(X11LibraryName)]
private static extern int XDisplayWidth(IntPtr display, int screenNumber); private static partial int XDisplayWidth(IntPtr display, int screenNumber);
[DllImport(X11LibraryName)] [LibraryImport(X11LibraryName)]
private static extern int XDisplayWidthMM(IntPtr display, int screenNumber); private static partial int XDisplayWidthMM(IntPtr display, int screenNumber);
[DllImport(X11LibraryName)] [LibraryImport(X11LibraryName)]
private static extern int XCloseDisplay(IntPtr display); private static partial int XCloseDisplay(IntPtr display);
private static readonly double _standardDpiScale = 96.0; private static readonly double _standardDpiScale = 96.0;
private static readonly double _maxScaleFactor = 1.25; private static readonly double _maxScaleFactor = 1.25;

View File

@@ -2,10 +2,10 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Ryujinx.Common.System namespace Ryujinx.Common.SystemInterop
{ {
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
public static class GdiPlusHelper public static partial class GdiPlusHelper
{ {
private const string LibraryName = "gdiplus.dll"; private const string LibraryName = "gdiplus.dll";
@@ -52,17 +52,17 @@ namespace Ryujinx.Common.System
public IntPtr NotificationUnhook; public IntPtr NotificationUnhook;
} }
[DllImport(LibraryName)] [LibraryImport(LibraryName)]
private static extern int GdiplusStartup(out IntPtr token, in StartupInputEx input, out StartupOutput output); private static partial int GdiplusStartup(out IntPtr token, in StartupInputEx input, out StartupOutput output);
[DllImport(LibraryName)] [LibraryImport(LibraryName)]
private static extern int GdipCreateFromHWND(IntPtr hwnd, out IntPtr graphics); private static partial int GdipCreateFromHWND(IntPtr hwnd, out IntPtr graphics);
[DllImport(LibraryName)] [LibraryImport(LibraryName)]
private static extern int GdipDeleteGraphics(IntPtr graphics); private static partial int GdipDeleteGraphics(IntPtr graphics);
[DllImport(LibraryName)] [LibraryImport(LibraryName)]
private static extern int GdipGetDpiX(IntPtr graphics, out float dpi); private static partial int GdipGetDpiX(IntPtr graphics, out float dpi);
public static float GetDpiX(IntPtr hwnd) public static float GetDpiX(IntPtr hwnd)
{ {

View File

@@ -4,13 +4,13 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Versioning; using System.Runtime.Versioning;
namespace Ryujinx.Common.System namespace Ryujinx.Common.SystemInterop
{ {
/// <summary> /// <summary>
/// Handle Windows Multimedia timer resolution. /// Handle Windows Multimedia timer resolution.
/// </summary> /// </summary>
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
public class WindowsMultimediaTimerResolution : IDisposable public partial class WindowsMultimediaTimerResolution : IDisposable
{ {
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct TimeCaps public struct TimeCaps
@@ -19,14 +19,14 @@ namespace Ryujinx.Common.System
public uint wPeriodMax; public uint wPeriodMax;
}; };
[DllImport("winmm.dll", EntryPoint = "timeGetDevCaps", SetLastError = true)] [LibraryImport("winmm.dll", EntryPoint = "timeGetDevCaps", SetLastError = true)]
private static extern uint TimeGetDevCaps(ref TimeCaps timeCaps, uint sizeTimeCaps); private static partial uint TimeGetDevCaps(ref TimeCaps timeCaps, uint sizeTimeCaps);
[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")] [LibraryImport("winmm.dll", EntryPoint = "timeBeginPeriod")]
private static extern uint TimeBeginPeriod(uint uMilliseconds); private static partial uint TimeBeginPeriod(uint uMilliseconds);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod")] [LibraryImport("winmm.dll", EntryPoint = "timeEndPeriod")]
private static extern uint TimeEndPeriod(uint uMilliseconds); private static partial uint TimeEndPeriod(uint uMilliseconds);
private uint _targetResolutionInMilliseconds; private uint _targetResolutionInMilliseconds;
private bool _isActive; private bool _isActive;

View File

@@ -1,12 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Ryujinx.Graphics.Device namespace Ryujinx.Graphics.Device
{ {
public class DeviceState<TState> : IDeviceState where TState : unmanaged public class DeviceState<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TState> : IDeviceState where TState : unmanaged
{ {
private const int RegisterSize = sizeof(int); private const int RegisterSize = sizeof(int);

View File

@@ -2,6 +2,7 @@ using Ryujinx.Graphics.Device;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace Ryujinx.Graphics.Gpu.Engine namespace Ryujinx.Graphics.Gpu.Engine
@@ -21,7 +22,7 @@ namespace Ryujinx.Graphics.Gpu.Engine
/// Represents a device's state, with a additional shadow state. /// Represents a device's state, with a additional shadow state.
/// </summary> /// </summary>
/// <typeparam name="TState">Type of the state</typeparam> /// <typeparam name="TState">Type of the state</typeparam>
class DeviceStateWithShadow<TState> : IDeviceState where TState : unmanaged, IShadowState class DeviceStateWithShadow<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TState> : IDeviceState where TState : unmanaged, IShadowState
{ {
private readonly DeviceState<TState> _state; private readonly DeviceState<TState> _state;
private readonly DeviceState<TState> _shadowState; private readonly DeviceState<TState> _shadowState;

View File

@@ -98,7 +98,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
public void DrawEnd(ThreedClass engine, int argument) public void DrawEnd(ThreedClass engine, int argument)
{ {
DrawEnd(engine, _state.State.IndexBufferState.First, (int)_state.State.IndexBufferCount); DrawEnd(
engine,
_state.State.IndexBufferState.First,
(int)_state.State.IndexBufferCount,
_state.State.VertexBufferDrawState.First,
_state.State.VertexBufferDrawState.Count);
} }
/// <summary> /// <summary>
@@ -108,7 +113,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
/// <param name="engine">3D engine where this method is being called</param> /// <param name="engine">3D engine where this method is being called</param>
/// <param name="firstIndex">Index of the first index buffer element used on the draw</param> /// <param name="firstIndex">Index of the first index buffer element used on the draw</param>
/// <param name="indexCount">Number of index buffer elements used on the draw</param> /// <param name="indexCount">Number of index buffer elements used on the draw</param>
private void DrawEnd(ThreedClass engine, int firstIndex, int indexCount) /// <param name="drawFirstVertex">Index of the first vertex used on the draw</param>
/// <param name="drawVertexCount">Number of vertices used on the draw</param>
private void DrawEnd(ThreedClass engine, int firstIndex, int indexCount, int drawFirstVertex, int drawVertexCount)
{ {
ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable( ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
_context, _context,
@@ -195,7 +202,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
{ {
var drawState = _state.State.VertexBufferDrawState; var drawState = _state.State.VertexBufferDrawState;
_context.Renderer.Pipeline.Draw(drawState.Count, 1, drawState.First, firstInstance); _context.Renderer.Pipeline.Draw(drawVertexCount, 1, drawFirstVertex, firstInstance);
} }
_drawState.DrawIndexed = false; _drawState.DrawIndexed = false;
@@ -216,16 +223,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
bool incrementInstance = (argument & (1 << 26)) != 0; bool incrementInstance = (argument & (1 << 26)) != 0;
bool resetInstance = (argument & (1 << 27)) == 0; bool resetInstance = (argument & (1 << 27)) == 0;
if (_state.State.PrimitiveTypeOverrideEnable)
{
PrimitiveTypeOverride typeOverride = _state.State.PrimitiveTypeOverride;
DrawBegin(incrementInstance, resetInstance, typeOverride.Convert());
}
else
{
PrimitiveType type = (PrimitiveType)(argument & 0xffff); PrimitiveType type = (PrimitiveType)(argument & 0xffff);
DrawBegin(incrementInstance, resetInstance, type.Convert()); DrawBegin(incrementInstance, resetInstance, type);
}
} }
/// <summary> /// <summary>
@@ -234,8 +233,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
/// </summary> /// </summary>
/// <param name="incrementInstance">Indicates if the current instance should be incremented</param> /// <param name="incrementInstance">Indicates if the current instance should be incremented</param>
/// <param name="resetInstance">Indicates if the current instance should be set to zero</param> /// <param name="resetInstance">Indicates if the current instance should be set to zero</param>
/// <param name="topology">Primitive topology</param> /// <param name="primitiveType">Primitive type</param>
private void DrawBegin(bool incrementInstance, bool resetInstance, PrimitiveTopology topology) private void DrawBegin(bool incrementInstance, bool resetInstance, PrimitiveType primitiveType)
{ {
if (incrementInstance) if (incrementInstance)
{ {
@@ -248,6 +247,18 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
_instanceIndex = 0; _instanceIndex = 0;
} }
PrimitiveTopology topology;
if (_state.State.PrimitiveTypeOverrideEnable)
{
PrimitiveTypeOverride typeOverride = _state.State.PrimitiveTypeOverride;
topology = typeOverride.Convert();
}
else
{
topology = primitiveType.Convert();
}
UpdateTopology(topology); UpdateTopology(topology);
} }
@@ -276,46 +287,70 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
_drawState.DrawIndexed = true; _drawState.DrawIndexed = true;
} }
// TODO: Verify if the index type is implied from the method that is called,
// or if it uses the state index type on hardware.
/// <summary> /// <summary>
/// Performs a indexed draw with a low number of index buffer elements. /// Performs a indexed draw with 8-bit index buffer elements.
/// </summary> /// </summary>
/// <param name="engine">3D engine where this method is being called</param> /// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
public void DrawIndexedSmall(ThreedClass engine, int argument) public void DrawIndexBuffer8BeginEndInstanceFirst(ThreedClass engine, int argument)
{ {
DrawIndexedSmall(engine, argument, false); DrawIndexBufferBeginEndInstance(engine, argument, false);
} }
/// <summary> /// <summary>
/// Performs a indexed draw with a low number of index buffer elements. /// Performs a indexed draw with 16-bit index buffer elements.
/// </summary> /// </summary>
/// <param name="engine">3D engine where this method is being called</param> /// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
public void DrawIndexedSmall2(ThreedClass engine, int argument) public void DrawIndexBuffer16BeginEndInstanceFirst(ThreedClass engine, int argument)
{ {
DrawIndexedSmall(engine, argument); DrawIndexBufferBeginEndInstance(engine, argument, false);
} }
/// <summary> /// <summary>
/// Performs a indexed draw with a low number of index buffer elements, /// Performs a indexed draw with 32-bit index buffer elements.
/// </summary>
/// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param>
public void DrawIndexBuffer32BeginEndInstanceFirst(ThreedClass engine, int argument)
{
DrawIndexBufferBeginEndInstance(engine, argument, false);
}
/// <summary>
/// Performs a indexed draw with 8-bit index buffer elements,
/// while also pre-incrementing the current instance value. /// while also pre-incrementing the current instance value.
/// </summary> /// </summary>
/// <param name="engine">3D engine where this method is being called</param> /// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
public void DrawIndexedSmallIncInstance(ThreedClass engine, int argument) public void DrawIndexBuffer8BeginEndInstanceSubsequent(ThreedClass engine, int argument)
{ {
DrawIndexedSmall(engine, argument, true); DrawIndexBufferBeginEndInstance(engine, argument, true);
} }
/// <summary> /// <summary>
/// Performs a indexed draw with a low number of index buffer elements, /// Performs a indexed draw with 16-bit index buffer elements,
/// while also pre-incrementing the current instance value. /// while also pre-incrementing the current instance value.
/// </summary> /// </summary>
/// <param name="engine">3D engine where this method is being called</param> /// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
public void DrawIndexedSmallIncInstance2(ThreedClass engine, int argument) public void DrawIndexBuffer16BeginEndInstanceSubsequent(ThreedClass engine, int argument)
{ {
DrawIndexedSmallIncInstance(engine, argument); DrawIndexBufferBeginEndInstance(engine, argument, true);
}
/// <summary>
/// Performs a indexed draw with 32-bit index buffer elements,
/// while also pre-incrementing the current instance value.
/// </summary>
/// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param>
public void DrawIndexBuffer32BeginEndInstanceSubsequent(ThreedClass engine, int argument)
{
DrawIndexBufferBeginEndInstance(engine, argument, true);
} }
/// <summary> /// <summary>
@@ -325,11 +360,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
/// <param name="engine">3D engine where this method is being called</param> /// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
/// <param name="instanced">True to increment the current instance value, false otherwise</param> /// <param name="instanced">True to increment the current instance value, false otherwise</param>
private void DrawIndexedSmall(ThreedClass engine, int argument, bool instanced) private void DrawIndexBufferBeginEndInstance(ThreedClass engine, int argument, bool instanced)
{ {
PrimitiveTypeOverride typeOverride = _state.State.PrimitiveTypeOverride; DrawBegin(instanced, !instanced, (PrimitiveType)((argument >> 28) & 0xf));
DrawBegin(instanced, !instanced, typeOverride.Convert());
int firstIndex = argument & 0xffff; int firstIndex = argument & 0xffff;
int indexCount = (argument >> 16) & 0xfff; int indexCount = (argument >> 16) & 0xfff;
@@ -339,7 +372,51 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
_drawState.DrawIndexed = true; _drawState.DrawIndexed = true;
engine.ForceStateDirty(IndexBufferCountMethodOffset * 4); engine.ForceStateDirty(IndexBufferCountMethodOffset * 4);
DrawEnd(engine, firstIndex, indexCount); DrawEnd(engine, firstIndex, indexCount, 0, 0);
_drawState.DrawIndexed = oldDrawIndexed;
}
/// <summary>
/// Performs a non-indexed draw with the specified topology, index and count.
/// </summary>
/// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param>
public void DrawVertexArrayBeginEndInstanceFirst(ThreedClass engine, int argument)
{
DrawVertexArrayBeginEndInstance(engine, argument, false);
}
/// <summary>
/// Performs a non-indexed draw with the specified topology, index and count,
/// while incrementing the current instance.
/// </summary>
/// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param>
public void DrawVertexArrayBeginEndInstanceSubsequent(ThreedClass engine, int argument)
{
DrawVertexArrayBeginEndInstance(engine, argument, true);
}
/// <summary>
/// Performs a indexed draw with a low number of index buffer elements,
/// while optionally also pre-incrementing the current instance value.
/// </summary>
/// <param name="engine">3D engine where this method is being called</param>
/// <param name="argument">Method call argument</param>
/// <param name="instanced">True to increment the current instance value, false otherwise</param>
private void DrawVertexArrayBeginEndInstance(ThreedClass engine, int argument, bool instanced)
{
DrawBegin(instanced, !instanced, (PrimitiveType)((argument >> 28) & 0xf));
int firstVertex = argument & 0xffff;
int vertexCount = (argument >> 16) & 0xfff;
bool oldDrawIndexed = _drawState.DrawIndexed;
_drawState.DrawIndexed = false;
DrawEnd(engine, 0, 0, firstVertex, vertexCount);
_drawState.DrawIndexed = oldDrawIndexed; _drawState.DrawIndexed = oldDrawIndexed;
} }

View File

@@ -2,6 +2,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@@ -39,7 +40,7 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
/// GPU state update tracker. /// GPU state update tracker.
/// </summary> /// </summary>
/// <typeparam name="TState">State type</typeparam> /// <typeparam name="TState">State type</typeparam>
class StateUpdateTracker<TState> class StateUpdateTracker<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TState>
{ {
private const int BlockSize = 0xe00; private const int BlockSize = 0xe00;
private const int RegisterSize = sizeof(uint); private const int RegisterSize = sizeof(uint);

View File

@@ -1,7 +1,5 @@
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory;
using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.Gpu.Engine.GPFifo;
using Ryujinx.Graphics.Gpu.Engine.Types; using Ryujinx.Graphics.Gpu.Engine.Types;
using Ryujinx.Graphics.Gpu.Image; using Ryujinx.Graphics.Gpu.Image;
using Ryujinx.Graphics.Gpu.Shader; using Ryujinx.Graphics.Gpu.Shader;
@@ -1295,7 +1293,14 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
for (int stageIndex = 0; stageIndex < Constants.ShaderStages; stageIndex++) for (int stageIndex = 0; stageIndex < Constants.ShaderStages; stageIndex++)
{ {
_currentProgramInfo[stageIndex] = gs.Shaders[stageIndex + 1]?.Info; ShaderProgramInfo info = gs.Shaders[stageIndex + 1]?.Info;
if (info?.UsesRtLayer == true)
{
_vtgWritesRtLayer = true;
}
_currentProgramInfo[stageIndex] = info;
} }
_context.Renderer.Pipeline.SetProgram(gs.HostProgram); _context.Renderer.Pipeline.SetProgram(gs.HostProgram);

View File

@@ -42,6 +42,8 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
{ nameof(ThreedClassState.TextureBarrier), new RwCallback(TextureBarrier, null) }, { nameof(ThreedClassState.TextureBarrier), new RwCallback(TextureBarrier, null) },
{ nameof(ThreedClassState.TextureBarrierTiled), new RwCallback(TextureBarrierTiled, null) }, { nameof(ThreedClassState.TextureBarrierTiled), new RwCallback(TextureBarrierTiled, null) },
{ nameof(ThreedClassState.DrawTextureSrcY), new RwCallback(DrawTexture, null) }, { nameof(ThreedClassState.DrawTextureSrcY), new RwCallback(DrawTexture, null) },
{ nameof(ThreedClassState.DrawVertexArrayBeginEndInstanceFirst), new RwCallback(DrawVertexArrayBeginEndInstanceFirst, null) },
{ nameof(ThreedClassState.DrawVertexArrayBeginEndInstanceSubsequent), new RwCallback(DrawVertexArrayBeginEndInstanceSubsequent, null) },
{ nameof(ThreedClassState.VbElementU8), new RwCallback(VbElementU8, null) }, { nameof(ThreedClassState.VbElementU8), new RwCallback(VbElementU8, null) },
{ nameof(ThreedClassState.VbElementU16), new RwCallback(VbElementU16, null) }, { nameof(ThreedClassState.VbElementU16), new RwCallback(VbElementU16, null) },
{ nameof(ThreedClassState.VbElementU32), new RwCallback(VbElementU32, null) }, { nameof(ThreedClassState.VbElementU32), new RwCallback(VbElementU32, null) },
@@ -49,10 +51,12 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
{ nameof(ThreedClassState.RenderEnableCondition), new RwCallback(null, Zero) }, { nameof(ThreedClassState.RenderEnableCondition), new RwCallback(null, Zero) },
{ nameof(ThreedClassState.DrawEnd), new RwCallback(DrawEnd, null) }, { nameof(ThreedClassState.DrawEnd), new RwCallback(DrawEnd, null) },
{ nameof(ThreedClassState.DrawBegin), new RwCallback(DrawBegin, null) }, { nameof(ThreedClassState.DrawBegin), new RwCallback(DrawBegin, null) },
{ nameof(ThreedClassState.DrawIndexedSmall), new RwCallback(DrawIndexedSmall, null) }, { nameof(ThreedClassState.DrawIndexBuffer32BeginEndInstanceFirst), new RwCallback(DrawIndexBuffer32BeginEndInstanceFirst, null) },
{ nameof(ThreedClassState.DrawIndexedSmall2), new RwCallback(DrawIndexedSmall2, null) }, { nameof(ThreedClassState.DrawIndexBuffer16BeginEndInstanceFirst), new RwCallback(DrawIndexBuffer16BeginEndInstanceFirst, null) },
{ nameof(ThreedClassState.DrawIndexedSmallIncInstance), new RwCallback(DrawIndexedSmallIncInstance, null) }, { nameof(ThreedClassState.DrawIndexBuffer8BeginEndInstanceFirst), new RwCallback(DrawIndexBuffer8BeginEndInstanceFirst, null) },
{ nameof(ThreedClassState.DrawIndexedSmallIncInstance2), new RwCallback(DrawIndexedSmallIncInstance2, null) }, { nameof(ThreedClassState.DrawIndexBuffer32BeginEndInstanceSubsequent), new RwCallback(DrawIndexBuffer32BeginEndInstanceSubsequent, null) },
{ nameof(ThreedClassState.DrawIndexBuffer16BeginEndInstanceSubsequent), new RwCallback(DrawIndexBuffer16BeginEndInstanceSubsequent, null) },
{ nameof(ThreedClassState.DrawIndexBuffer8BeginEndInstanceSubsequent), new RwCallback(DrawIndexBuffer8BeginEndInstanceSubsequent, null) },
{ nameof(ThreedClassState.IndexBufferCount), new RwCallback(SetIndexBufferCount, null) }, { nameof(ThreedClassState.IndexBufferCount), new RwCallback(SetIndexBufferCount, null) },
{ nameof(ThreedClassState.Clear), new RwCallback(Clear, null) }, { nameof(ThreedClassState.Clear), new RwCallback(Clear, null) },
{ nameof(ThreedClassState.SemaphoreControl), new RwCallback(Report, null) }, { nameof(ThreedClassState.SemaphoreControl), new RwCallback(Report, null) },
@@ -303,6 +307,25 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
_drawManager.DrawTexture(this, argument); _drawManager.DrawTexture(this, argument);
} }
/// <summary>
/// Performs a non-indexed draw with the specified topology, index and count.
/// </summary>
/// <param name="argument">Method call argument</param>
private void DrawVertexArrayBeginEndInstanceFirst(int argument)
{
_drawManager.DrawVertexArrayBeginEndInstanceFirst(this, argument);
}
/// <summary>
/// Performs a non-indexed draw with the specified topology, index and count,
/// while incrementing the current instance.
/// </summary>
/// <param name="argument">Method call argument</param>
private void DrawVertexArrayBeginEndInstanceSubsequent(int argument)
{
_drawManager.DrawVertexArrayBeginEndInstanceSubsequent(this, argument);
}
/// <summary> /// <summary>
/// Pushes four 8-bit index buffer elements. /// Pushes four 8-bit index buffer elements.
/// </summary> /// </summary>
@@ -370,41 +393,60 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
} }
/// <summary> /// <summary>
/// Performs a indexed draw with a low number of index buffer elements. /// Performs a indexed draw with 8-bit index buffer elements.
/// </summary> /// </summary>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
private void DrawIndexedSmall(int argument) private void DrawIndexBuffer8BeginEndInstanceFirst(int argument)
{ {
_drawManager.DrawIndexedSmall(this, argument); _drawManager.DrawIndexBuffer8BeginEndInstanceFirst(this, argument);
} }
/// <summary> /// <summary>
/// Performs a indexed draw with a low number of index buffer elements. /// Performs a indexed draw with 16-bit index buffer elements.
/// </summary> /// </summary>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
private void DrawIndexedSmall2(int argument) private void DrawIndexBuffer16BeginEndInstanceFirst(int argument)
{ {
_drawManager.DrawIndexedSmall2(this, argument); _drawManager.DrawIndexBuffer16BeginEndInstanceFirst(this, argument);
} }
/// <summary> /// <summary>
/// Performs a indexed draw with a low number of index buffer elements, /// Performs a indexed draw with 32-bit index buffer elements.
/// </summary>
/// <param name="argument">Method call argument</param>
private void DrawIndexBuffer32BeginEndInstanceFirst(int argument)
{
_drawManager.DrawIndexBuffer32BeginEndInstanceFirst(this, argument);
}
/// <summary>
/// Performs a indexed draw with 8-bit index buffer elements,
/// while also pre-incrementing the current instance value. /// while also pre-incrementing the current instance value.
/// </summary> /// </summary>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
private void DrawIndexedSmallIncInstance(int argument) private void DrawIndexBuffer8BeginEndInstanceSubsequent(int argument)
{ {
_drawManager.DrawIndexedSmallIncInstance(this, argument); _drawManager.DrawIndexBuffer8BeginEndInstanceSubsequent(this, argument);
} }
/// <summary> /// <summary>
/// Performs a indexed draw with a low number of index buffer elements, /// Performs a indexed draw with 16-bit index buffer elements,
/// while also pre-incrementing the current instance value. /// while also pre-incrementing the current instance value.
/// </summary> /// </summary>
/// <param name="argument">Method call argument</param> /// <param name="argument">Method call argument</param>
private void DrawIndexedSmallIncInstance2(int argument) private void DrawIndexBuffer16BeginEndInstanceSubsequent(int argument)
{ {
_drawManager.DrawIndexedSmallIncInstance2(this, argument); _drawManager.DrawIndexBuffer16BeginEndInstanceSubsequent(this, argument);
}
/// <summary>
/// Performs a indexed draw with 32-bit index buffer elements,
/// while also pre-incrementing the current instance value.
/// </summary>
/// <param name="argument">Method call argument</param>
private void DrawIndexBuffer32BeginEndInstanceSubsequent(int argument)
{
_drawManager.DrawIndexBuffer32BeginEndInstanceSubsequent(this, argument);
} }
/// <summary> /// <summary>

View File

@@ -813,7 +813,9 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
public uint ClearFlags; public uint ClearFlags;
public fixed uint Reserved10FC[25]; public fixed uint Reserved10FC[25];
public Array32<VertexAttribState> VertexAttribState; public Array32<VertexAttribState> VertexAttribState;
public fixed uint Reserved11E0[15]; public fixed uint Reserved11E0[13];
public uint DrawVertexArrayBeginEndInstanceFirst;
public uint DrawVertexArrayBeginEndInstanceSubsequent;
public RtControl RtControl; public RtControl RtControl;
public fixed uint Reserved1220[2]; public fixed uint Reserved1220[2];
public Size3D RtDepthStencilSize; public Size3D RtDepthStencilSize;
@@ -888,12 +890,13 @@ namespace Ryujinx.Graphics.Gpu.Engine.Threed
public fixed uint Reserved164C[95]; public fixed uint Reserved164C[95];
public IndexBufferState IndexBufferState; public IndexBufferState IndexBufferState;
public uint IndexBufferCount; public uint IndexBufferCount;
public uint DrawIndexedSmall; public uint DrawIndexBuffer32BeginEndInstanceFirst;
public uint DrawIndexedSmall2; public uint DrawIndexBuffer16BeginEndInstanceFirst;
public uint Reserved17EC; public uint DrawIndexBuffer8BeginEndInstanceFirst;
public uint DrawIndexedSmallIncInstance; public uint DrawIndexBuffer32BeginEndInstanceSubsequent;
public uint DrawIndexedSmallIncInstance2; public uint DrawIndexBuffer16BeginEndInstanceSubsequent;
public fixed uint Reserved17F8[33]; public uint DrawIndexBuffer8BeginEndInstanceSubsequent;
public fixed uint Reserved17FC[32];
public float DepthBiasClamp; public float DepthBiasClamp;
public Array16<Boolean32> VertexBufferInstanced; public Array16<Boolean32> VertexBufferInstanced;
public fixed uint Reserved18C0[20]; public fixed uint Reserved18C0[20];

View File

@@ -22,7 +22,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache
private const ushort FileFormatVersionMajor = 1; private const ushort FileFormatVersionMajor = 1;
private const ushort FileFormatVersionMinor = 2; private const ushort FileFormatVersionMinor = 2;
private const uint FileFormatVersionPacked = ((uint)FileFormatVersionMajor << 16) | FileFormatVersionMinor; private const uint FileFormatVersionPacked = ((uint)FileFormatVersionMajor << 16) | FileFormatVersionMinor;
private const uint CodeGenVersion = 4069; private const uint CodeGenVersion = 4106;
private const string SharedTocFileName = "shared.toc"; private const string SharedTocFileName = "shared.toc";
private const string SharedDataFileName = "shared.data"; private const string SharedDataFileName = "shared.data";

View File

@@ -53,7 +53,7 @@ namespace Ryujinx.Graphics.Gpu.Shader.DiskCache
{ {
CachedShaderStage currentStage = stages[i]; CachedShaderStage currentStage = stages[i];
if (currentStage != null && currentStage.Info.Stage == stage && currentStage.Info != null) if (currentStage?.Info != null && currentStage.Info.Stage == stage)
{ {
return ShaderCache.GetBindings(currentStage.Info); return ShaderCache.GetBindings(currentStage.Info);
} }

View File

@@ -5,7 +5,7 @@ using System.Runtime.InteropServices;
namespace Ryujinx.Graphics.Nvdec.FFmpeg.Native namespace Ryujinx.Graphics.Nvdec.FFmpeg.Native
{ {
static class FFmpegApi static partial class FFmpegApi
{ {
public const string AvCodecLibraryName = "avcodec"; public const string AvCodecLibraryName = "avcodec";
public const string AvUtilLibraryName = "avutil"; public const string AvUtilLibraryName = "avutil";
@@ -78,52 +78,52 @@ namespace Ryujinx.Graphics.Nvdec.FFmpeg.Native
public unsafe delegate void av_log_set_callback_callback(void* a0, AVLog level, [MarshalAs(UnmanagedType.LPUTF8Str)] string a2, byte* a3); public unsafe delegate void av_log_set_callback_callback(void* a0, AVLog level, [MarshalAs(UnmanagedType.LPUTF8Str)] string a2, byte* a3);
[DllImport(AvUtilLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvUtilLibraryName)]
internal static unsafe extern AVFrame* av_frame_alloc(); internal static unsafe partial AVFrame* av_frame_alloc();
[DllImport(AvUtilLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvUtilLibraryName)]
internal static unsafe extern void av_frame_unref(AVFrame* frame); internal static unsafe partial void av_frame_unref(AVFrame* frame);
[DllImport(AvUtilLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvUtilLibraryName)]
internal static unsafe extern void av_free(AVFrame* frame); internal static unsafe partial void av_free(AVFrame* frame);
[DllImport(AvUtilLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvUtilLibraryName)]
internal static unsafe extern void av_log_set_level(AVLog level); internal static unsafe partial void av_log_set_level(AVLog level);
[DllImport(AvUtilLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvUtilLibraryName)]
internal static unsafe extern void av_log_set_callback(av_log_set_callback_callback callback); internal static unsafe partial void av_log_set_callback(av_log_set_callback_callback callback);
[DllImport(AvUtilLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvUtilLibraryName)]
internal static unsafe extern AVLog av_log_get_level(); internal static unsafe partial AVLog av_log_get_level();
[DllImport(AvUtilLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvUtilLibraryName)]
internal static unsafe extern void av_log_format_line(void* ptr, AVLog level, [MarshalAs(UnmanagedType.LPUTF8Str)] string fmt, byte* vl, byte* line, int lineSize, int* printPrefix); internal static unsafe partial void av_log_format_line(void* ptr, AVLog level, [MarshalAs(UnmanagedType.LPUTF8Str)] string fmt, byte* vl, byte* line, int lineSize, int* printPrefix);
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern AVCodec* avcodec_find_decoder(AVCodecID id); internal static unsafe partial AVCodec* avcodec_find_decoder(AVCodecID id);
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern AVCodecContext* avcodec_alloc_context3(AVCodec* codec); internal static unsafe partial AVCodecContext* avcodec_alloc_context3(AVCodec* codec);
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern int avcodec_open2(AVCodecContext* avctx, AVCodec* codec, void **options); internal static unsafe partial int avcodec_open2(AVCodecContext* avctx, AVCodec* codec, void **options);
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern int avcodec_close(AVCodecContext* avctx); internal static unsafe partial int avcodec_close(AVCodecContext* avctx);
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern void avcodec_free_context(AVCodecContext** avctx); internal static unsafe partial void avcodec_free_context(AVCodecContext** avctx);
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern AVPacket* av_packet_alloc(); internal static unsafe partial AVPacket* av_packet_alloc();
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern void av_packet_unref(AVPacket* pkt); internal static unsafe partial void av_packet_unref(AVPacket* pkt);
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern void av_packet_free(AVPacket** pkt); internal static unsafe partial void av_packet_free(AVPacket** pkt);
[DllImport(AvCodecLibraryName, CallingConvention = CallingConvention.Cdecl)] [LibraryImport(AvCodecLibraryName)]
internal static unsafe extern int avcodec_version(); internal static unsafe partial int avcodec_version();
} }
} }

View File

@@ -5,7 +5,7 @@ using System.Runtime.Versioning;
namespace Ryujinx.Graphics.OpenGL.Helper namespace Ryujinx.Graphics.OpenGL.Helper
{ {
[SupportedOSPlatform("linux")] [SupportedOSPlatform("linux")]
internal static class GLXHelper internal static partial class GLXHelper
{ {
private const string LibraryName = "glx.dll"; private const string LibraryName = "glx.dll";
@@ -30,7 +30,7 @@ namespace Ryujinx.Graphics.OpenGL.Helper
}); });
} }
[DllImport(LibraryName, EntryPoint = "glXGetCurrentContext")] [LibraryImport(LibraryName, EntryPoint = "glXGetCurrentContext")]
public static extern IntPtr GetCurrentContext(); public static partial IntPtr GetCurrentContext();
} }
} }

View File

@@ -5,11 +5,11 @@ using System.Runtime.Versioning;
namespace Ryujinx.Graphics.OpenGL.Helper namespace Ryujinx.Graphics.OpenGL.Helper
{ {
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
internal static class WGLHelper internal static partial class WGLHelper
{ {
private const string LibraryName = "OPENGL32.DLL"; private const string LibraryName = "OPENGL32.DLL";
[DllImport(LibraryName, EntryPoint = "wglGetCurrentContext")] [LibraryImport(LibraryName, EntryPoint = "wglGetCurrentContext")]
public extern static IntPtr GetCurrentContext(); public static partial IntPtr GetCurrentContext();
} }
} }

View File

@@ -6,7 +6,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="OpenTK.Graphics" Version="4.7.5" /> <PackageReference Include="OpenTK.Graphics" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -262,7 +262,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
value = (value >> operation.Index * 16) & 0xffff; value = (value >> operation.Index * 16) & 0xffff;
operation.TurnIntoCopy(ConstF(HalfConversion.HalfToSingle(value))); operation.TurnIntoCopy(ConstF((float)BitConverter.UInt16BitsToHalf((ushort)value)));
} }
private static void FPNegate(Operation operation) private static void FPNegate(Operation operation)

View File

@@ -1,47 +0,0 @@
using System;
namespace Ryujinx.Graphics.Shader.Translation.Optimizations
{
static class HalfConversion
{
public static float HalfToSingle(int value)
{
int mantissa = (value >> 0) & 0x3ff;
int exponent = (value >> 10) & 0x1f;
int sign = (value >> 15) & 0x1;
if (exponent == 0x1f)
{
// NaN or Infinity.
mantissa <<= 13;
exponent = 0xff;
}
else if (exponent != 0 || mantissa != 0 )
{
if (exponent == 0)
{
// Denormal.
int e = -1;
int m = mantissa;
do
{
e++;
m <<= 1;
}
while ((m & 0x400) == 0);
mantissa = m & 0x3ff;
exponent = e;
}
mantissa <<= 13;
exponent = 127 - 15 + exponent;
}
int output = (sign << 31) | (exponent << 23) | mantissa;
return BitConverter.Int32BitsToSingle(output);
}
}
}

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
@@ -13,14 +13,14 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="OpenTK.Windowing.GraphicsLibraryFramework" Version="4.7.5" /> <PackageReference Include="OpenTK.Windowing.GraphicsLibraryFramework" />
<PackageReference Include="shaderc.net" Version="0.1.0" /> <PackageReference Include="shaderc.net" />
<PackageReference Include="Silk.NET.Vulkan" Version="2.16.0" /> <PackageReference Include="Silk.NET.Vulkan" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.EXT" Version="2.16.0" /> <PackageReference Include="Silk.NET.Vulkan.Extensions.EXT" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.16.0" /> <PackageReference Include="Silk.NET.Vulkan.Extensions.KHR" />
<PackageReference Include="System.IO.FileSystem.Primitives" Version="4.3.0" /> <PackageReference Include="System.IO.FileSystem.Primitives" />
<PackageReference Include="System.Net.NameResolution" Version="4.3.0" /> <PackageReference Include="System.Net.NameResolution" />
<PackageReference Include="System.Threading.ThreadPool" Version="4.3.0" /> <PackageReference Include="System.Threading.ThreadPool" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -374,7 +374,24 @@ namespace Ryujinx.Graphics.Vulkan
api.GetPhysicalDeviceProperties(physicalDevice, out var properties); api.GetPhysicalDeviceProperties(physicalDevice, out var properties);
bool useRobustBufferAccess = VendorUtils.FromId(properties.VendorID) == Vendor.Nvidia; bool useRobustBufferAccess = VendorUtils.FromId(properties.VendorID) == Vendor.Nvidia;
var supportedFeatures = api.GetPhysicalDeviceFeature(physicalDevice); PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
{
SType = StructureType.PhysicalDeviceFeatures2
};
PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColorSupported = new PhysicalDeviceCustomBorderColorFeaturesEXT()
{
SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt
};
if (supportedExtensions.Contains("VK_EXT_custom_border_color"))
{
features2.PNext = &featuresCustomBorderColorSupported;
}
api.GetPhysicalDeviceFeatures2(physicalDevice, &features2);
var supportedFeatures = features2.Features;
var features = new PhysicalDeviceFeatures() var features = new PhysicalDeviceFeatures()
{ {
@@ -491,6 +508,23 @@ namespace Ryujinx.Graphics.Vulkan
pExtendedFeatures = &featuresSubgroupSizeControl; pExtendedFeatures = &featuresSubgroupSizeControl;
} }
PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor;
if (supportedExtensions.Contains("VK_EXT_custom_border_color") &&
featuresCustomBorderColorSupported.CustomBorderColors &&
featuresCustomBorderColorSupported.CustomBorderColorWithoutFormat)
{
featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
{
SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt,
PNext = pExtendedFeatures,
CustomBorderColors = true,
CustomBorderColorWithoutFormat = true,
};
pExtendedFeatures = &featuresCustomBorderColor;
}
var enabledExtensions = RequiredExtensions.Union(DesirableExtensions.Intersect(supportedExtensions)).ToArray(); var enabledExtensions = RequiredExtensions.Union(DesirableExtensions.Intersect(supportedExtensions)).ToArray();
IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length]; IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length];

View File

@@ -177,6 +177,11 @@ namespace Ryujinx.Graphics.Vulkan
SType = StructureType.PhysicalDeviceShaderFloat16Int8Features SType = StructureType.PhysicalDeviceShaderFloat16Int8Features
}; };
PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
{
SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt
};
if (supportedExtensions.Contains("VK_EXT_robustness2")) if (supportedExtensions.Contains("VK_EXT_robustness2"))
{ {
features2.PNext = &featuresRobustness2; features2.PNext = &featuresRobustness2;
@@ -188,8 +193,18 @@ namespace Ryujinx.Graphics.Vulkan
features2.PNext = &featuresShaderInt8; features2.PNext = &featuresShaderInt8;
} }
if (supportedExtensions.Contains("VK_EXT_custom_border_color"))
{
featuresCustomBorderColor.PNext = features2.PNext;
features2.PNext = &featuresCustomBorderColor;
}
Api.GetPhysicalDeviceFeatures2(_physicalDevice, &features2); Api.GetPhysicalDeviceFeatures2(_physicalDevice, &features2);
bool customBorderColorSupported = supportedExtensions.Contains("VK_EXT_custom_border_color") &&
featuresCustomBorderColor.CustomBorderColors &&
featuresCustomBorderColor.CustomBorderColorWithoutFormat;
ref var properties = ref properties2.Properties; ref var properties = ref properties2.Properties;
SampleCountFlags supportedSampleCounts = SampleCountFlags supportedSampleCounts =
@@ -199,7 +214,7 @@ namespace Ryujinx.Graphics.Vulkan
Capabilities = new HardwareCapabilities( Capabilities = new HardwareCapabilities(
supportedExtensions.Contains("VK_EXT_index_type_uint8"), supportedExtensions.Contains("VK_EXT_index_type_uint8"),
supportedExtensions.Contains("VK_EXT_custom_border_color"), customBorderColorSupported,
supportedExtensions.Contains(KhrDrawIndirectCount.ExtensionName), supportedExtensions.Contains(KhrDrawIndirectCount.ExtensionName),
supportedExtensions.Contains("VK_EXT_fragment_shader_interlock"), supportedExtensions.Contains("VK_EXT_fragment_shader_interlock"),
supportedExtensions.Contains("VK_NV_geometry_shader_passthrough"), supportedExtensions.Contains("VK_NV_geometry_shader_passthrough"),

View File

@@ -47,7 +47,7 @@ namespace Ryujinx.HLE.HOS.Applets.Error
_errorStorage = _normalSession.Pop(); _errorStorage = _normalSession.Pop();
_errorCommonHeader = IApplet.ReadStruct<ErrorCommonHeader>(_errorStorage); _errorCommonHeader = IApplet.ReadStruct<ErrorCommonHeader>(_errorStorage);
_errorStorage = _errorStorage.Skip(Marshal.SizeOf(typeof(ErrorCommonHeader))).ToArray(); _errorStorage = _errorStorage.Skip(Marshal.SizeOf<ErrorCommonHeader>()).ToArray();
switch (_errorCommonHeader.Type) switch (_errorCommonHeader.Type)
{ {

View File

@@ -9,6 +9,7 @@ using Ryujinx.HLE.Ui.Input;
using Ryujinx.Memory; using Ryujinx.Memory;
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@@ -797,7 +798,7 @@ namespace Ryujinx.HLE.HOS.Applets
return sb.ToString(); return sb.ToString();
} }
private static T ReadStruct<T>(byte[] data) private static T ReadStruct<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(byte[] data)
where T : struct where T : struct
{ {
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);

View File

@@ -2,7 +2,6 @@
using Ryujinx.HLE.HOS.Services.Account.Acc; using Ryujinx.HLE.HOS.Services.Account.Acc;
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text;
namespace Ryujinx.HLE.HOS.Services.Friend.ServiceCreator.FriendService namespace Ryujinx.HLE.HOS.Services.Friend.ServiceCreator.FriendService
{ {
@@ -29,7 +28,7 @@ namespace Ryujinx.HLE.HOS.Services.Friend.ServiceCreator.FriendService
public override string ToString() public override string ToString()
{ {
return $"UserPresence {{ UserId: {UserId}, LastTimeOnlineTimestamp: {LastTimeOnlineTimestamp}, Status: {Status}, AppKeyValueStorage: {Encoding.ASCII.GetString(AppKeyValueStorage)} }}"; return $"UserPresence {{ UserId: {UserId}, LastTimeOnlineTimestamp: {LastTimeOnlineTimestamp}, Status: {Status} }}";
} }
} }
} }

View File

@@ -589,9 +589,9 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
ulong outputPosition = context.Request.RecvListBuff[0].Position; ulong outputPosition = context.Request.RecvListBuff[0].Position;
context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize((uint)Marshal.SizeOf(typeof(TagInfo))); context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize((uint)Marshal.SizeOf<TagInfo>());
MemoryHelper.FillWithZeros(context.Memory, outputPosition, Marshal.SizeOf(typeof(TagInfo))); MemoryHelper.FillWithZeros(context.Memory, outputPosition, Marshal.SizeOf<TagInfo>());
uint deviceHandle = (uint)context.RequestData.ReadUInt64(); uint deviceHandle = (uint)context.RequestData.ReadUInt64();
@@ -665,9 +665,9 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
ulong outputPosition = context.Request.RecvListBuff[0].Position; ulong outputPosition = context.Request.RecvListBuff[0].Position;
context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize((uint)Marshal.SizeOf(typeof(RegisterInfo))); context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize((uint)Marshal.SizeOf<RegisterInfo>());
MemoryHelper.FillWithZeros(context.Memory, outputPosition, Marshal.SizeOf(typeof(RegisterInfo))); MemoryHelper.FillWithZeros(context.Memory, outputPosition, Marshal.SizeOf<RegisterInfo>());
uint deviceHandle = (uint)context.RequestData.ReadUInt64(); uint deviceHandle = (uint)context.RequestData.ReadUInt64();
@@ -728,9 +728,9 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
ulong outputPosition = context.Request.RecvListBuff[0].Position; ulong outputPosition = context.Request.RecvListBuff[0].Position;
context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize((uint)Marshal.SizeOf(typeof(CommonInfo))); context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize((uint)Marshal.SizeOf<CommonInfo>());
MemoryHelper.FillWithZeros(context.Memory, outputPosition, Marshal.SizeOf(typeof(CommonInfo))); MemoryHelper.FillWithZeros(context.Memory, outputPosition, Marshal.SizeOf<CommonInfo>());
uint deviceHandle = (uint)context.RequestData.ReadUInt64(); uint deviceHandle = (uint)context.RequestData.ReadUInt64();
@@ -788,9 +788,9 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
ulong outputPosition = context.Request.RecvListBuff[0].Position; ulong outputPosition = context.Request.RecvListBuff[0].Position;
context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize((uint)Marshal.SizeOf(typeof(ModelInfo))); context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize((uint)Marshal.SizeOf<ModelInfo>());
MemoryHelper.FillWithZeros(context.Memory, outputPosition, Marshal.SizeOf(typeof(ModelInfo))); MemoryHelper.FillWithZeros(context.Memory, outputPosition, Marshal.SizeOf<ModelInfo>());
uint deviceHandle = (uint)context.RequestData.ReadUInt64(); uint deviceHandle = (uint)context.RequestData.ReadUInt64();

View File

@@ -1,5 +1,8 @@
using System.Collections.Concurrent; using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
{ {
@@ -41,6 +44,27 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
return null; return null;
} }
public List<IFileDescriptor> RetrieveFileDescriptorsFromMask(ReadOnlySpan<byte> mask)
{
List<IFileDescriptor> fds = new();
for (int i = 0; i < mask.Length; i++)
{
byte current = mask[i];
while (current != 0)
{
int bit = BitOperations.TrailingZeroCount(current);
current &= (byte)~(1 << bit);
int fd = i * 8 + bit;
fds.Add(RetrieveFileDescriptor(fd));
}
}
return fds;
}
public int RegisterFileDescriptor(IFileDescriptor file) public int RegisterFileDescriptor(IFileDescriptor file)
{ {
lock (_lock) lock (_lock)
@@ -61,6 +85,16 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
} }
} }
public void BuildMask(List<IFileDescriptor> fds, Span<byte> mask)
{
foreach (IFileDescriptor descriptor in fds)
{
int fd = _fds.IndexOf(descriptor);
mask[fd >> 3] |= (byte)(1 << (fd & 7));
}
}
public int DuplicateFileDescriptor(int fd) public int DuplicateFileDescriptor(int fd)
{ {
IFileDescriptor oldFile = RetrieveFileDescriptor(fd); IFileDescriptor oldFile = RetrieveFileDescriptor(fd);

View File

@@ -1,10 +1,13 @@
using Ryujinx.Common; using Ryujinx.Common;
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl;
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using Ryujinx.Memory; using Ryujinx.Memory;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
@@ -202,12 +205,122 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
} }
[CommandHipc(5)] [CommandHipc(5)]
// Select(u32 nfds, nn::socket::timeout timeout, buffer<nn::socket::fd_set, 0x21, 0> readfds_in, buffer<nn::socket::fd_set, 0x21, 0> writefds_in, buffer<nn::socket::fd_set, 0x21, 0> errorfds_in) -> (i32 ret, u32 bsd_errno, buffer<nn::socket::fd_set, 0x22, 0> readfds_out, buffer<nn::socket::fd_set, 0x22, 0> writefds_out, buffer<nn::socket::fd_set, 0x22, 0> errorfds_out) // Select(u32 nfds, nn::socket::timeval timeout, buffer<nn::socket::fd_set, 0x21, 0> readfds_in, buffer<nn::socket::fd_set, 0x21, 0> writefds_in, buffer<nn::socket::fd_set, 0x21, 0> errorfds_in)
// -> (i32 ret, u32 bsd_errno, buffer<nn::socket::fd_set, 0x22, 0> readfds_out, buffer<nn::socket::fd_set, 0x22, 0> writefds_out, buffer<nn::socket::fd_set, 0x22, 0> errorfds_out)
public ResultCode Select(ServiceCtx context) public ResultCode Select(ServiceCtx context)
{ {
WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP); int fdsCount = context.RequestData.ReadInt32();
int timeout = context.RequestData.ReadInt32();
Logger.Stub?.PrintStub(LogClass.ServiceBsd); (ulong readFdsInBufferPosition, ulong readFdsInBufferSize) = context.Request.GetBufferType0x21(0);
(ulong writeFdsInBufferPosition, ulong writeFdsInBufferSize) = context.Request.GetBufferType0x21(1);
(ulong errorFdsInBufferPosition, ulong errorFdsInBufferSize) = context.Request.GetBufferType0x21(2);
(ulong readFdsOutBufferPosition, ulong readFdsOutBufferSize) = context.Request.GetBufferType0x22(0);
(ulong writeFdsOutBufferPosition, ulong writeFdsOutBufferSize) = context.Request.GetBufferType0x22(1);
(ulong errorFdsOutBufferPosition, ulong errorFdsOutBufferSize) = context.Request.GetBufferType0x22(2);
List<IFileDescriptor> readFds = _context.RetrieveFileDescriptorsFromMask(context.Memory.GetSpan(readFdsInBufferPosition, (int)readFdsInBufferSize));
List<IFileDescriptor> writeFds = _context.RetrieveFileDescriptorsFromMask(context.Memory.GetSpan(writeFdsInBufferPosition, (int)writeFdsInBufferSize));
List<IFileDescriptor> errorFds = _context.RetrieveFileDescriptorsFromMask(context.Memory.GetSpan(errorFdsInBufferPosition, (int)errorFdsInBufferSize));
int actualFdsCount = readFds.Count + writeFds.Count + errorFds.Count;
if (fdsCount == 0 || actualFdsCount == 0)
{
WriteBsdResult(context, 0);
return ResultCode.Success;
}
PollEvent[] events = new PollEvent[actualFdsCount];
int index = 0;
foreach (IFileDescriptor fd in readFds)
{
events[index] = new PollEvent(new PollEventData { InputEvents = PollEventTypeMask.Input }, fd);
index++;
}
foreach (IFileDescriptor fd in writeFds)
{
events[index] = new PollEvent(new PollEventData { InputEvents = PollEventTypeMask.Output }, fd);
index++;
}
foreach (IFileDescriptor fd in errorFds)
{
events[index] = new PollEvent(new PollEventData { InputEvents = PollEventTypeMask.Error }, fd);
index++;
}
List<PollEvent>[] eventsByPollManager = new List<PollEvent>[_pollManagers.Count];
for (int i = 0; i < eventsByPollManager.Length; i++)
{
eventsByPollManager[i] = new List<PollEvent>();
foreach (PollEvent evnt in events)
{
if (_pollManagers[i].IsCompatible(evnt))
{
eventsByPollManager[i].Add(evnt);
}
}
}
int updatedCount = 0;
for (int i = 0; i < _pollManagers.Count; i++)
{
if (eventsByPollManager[i].Count > 0)
{
_pollManagers[i].Select(eventsByPollManager[i], timeout, out int updatedPollCount);
updatedCount += updatedPollCount;
}
}
readFds.Clear();
writeFds.Clear();
errorFds.Clear();
foreach (PollEvent pollEvent in events)
{
for (int i = 0; i < _pollManagers.Count; i++)
{
if (eventsByPollManager[i].Contains(pollEvent))
{
if (pollEvent.Data.OutputEvents.HasFlag(PollEventTypeMask.Input))
{
readFds.Add(pollEvent.FileDescriptor);
}
if (pollEvent.Data.OutputEvents.HasFlag(PollEventTypeMask.Output))
{
writeFds.Add(pollEvent.FileDescriptor);
}
if (pollEvent.Data.OutputEvents.HasFlag(PollEventTypeMask.Error))
{
errorFds.Add(pollEvent.FileDescriptor);
}
}
}
}
using var readFdsOut = context.Memory.GetWritableRegion(readFdsOutBufferPosition, (int)readFdsOutBufferSize);
using var writeFdsOut = context.Memory.GetWritableRegion(writeFdsOutBufferPosition, (int)writeFdsOutBufferSize);
using var errorFdsOut = context.Memory.GetWritableRegion(errorFdsOutBufferPosition, (int)errorFdsOutBufferSize);
_context.BuildMask(readFds, readFdsOut.Memory.Span);
_context.BuildMask(writeFds, writeFdsOut.Memory.Span);
_context.BuildMask(errorFds, errorFdsOut.Memory.Span);
WriteBsdResult(context, updatedCount);
return ResultCode.Success; return ResultCode.Success;
} }
@@ -320,14 +433,14 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
break; break;
} }
// If we are here, that mean nothing was availaible, sleep for 50ms // If we are here, that mean nothing was available, sleep for 50ms
context.Device.System.KernelContext.Syscall.SleepThread(50 * 1000000); context.Device.System.KernelContext.Syscall.SleepThread(50 * 1000000);
} }
while (PerformanceCounter.ElapsedMilliseconds < budgetLeftMilliseconds); while (PerformanceCounter.ElapsedMilliseconds < budgetLeftMilliseconds);
} }
else if (timeout == -1) else if (timeout == -1)
{ {
// FIXME: If we get a timeout of -1 and there is no fds to wait on, this should kill the KProces. (need to check that with re) // FIXME: If we get a timeout of -1 and there is no fds to wait on, this should kill the KProcess. (need to check that with re)
throw new InvalidOperationException(); throw new InvalidOperationException();
} }
else else

View File

@@ -1,4 +1,5 @@
using System; using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
{ {

View File

@@ -1,4 +1,5 @@
using System; using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;

View File

@@ -1,8 +1,9 @@
using System; using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{ {
class EventFileDescriptor : IFileDescriptor class EventFileDescriptor : IFileDescriptor
{ {

View File

@@ -1,8 +1,9 @@
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{ {
class EventFileDescriptorPollManager : IPollManager class EventFileDescriptorPollManager : IPollManager
{ {
@@ -109,5 +110,13 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
return LinuxError.SUCCESS; return LinuxError.SUCCESS;
} }
public LinuxError Select(List<PollEvent> events, int timeout, out int updatedCount)
{
// TODO: Implement Select for event file descriptors
updatedCount = 0;
return LinuxError.EOPNOTSUPP;
}
} }
} }

View File

@@ -1,4 +1,5 @@
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
@@ -6,7 +7,7 @@ using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{ {
class ManagedSocket : ISocket class ManagedSocket : ISocket
{ {

View File

@@ -1,8 +1,9 @@
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Sockets; using System.Net.Sockets;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{ {
class ManagedSocketPollManager : IPollManager class ManagedSocketPollManager : IPollManager
{ {
@@ -117,5 +118,60 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
return LinuxError.SUCCESS; return LinuxError.SUCCESS;
} }
public LinuxError Select(List<PollEvent> events, int timeout, out int updatedCount)
{
List<Socket> readEvents = new();
List<Socket> writeEvents = new();
List<Socket> errorEvents = new();
updatedCount = 0;
foreach (PollEvent pollEvent in events)
{
ManagedSocket socket = (ManagedSocket)pollEvent.FileDescriptor;
if (pollEvent.Data.InputEvents.HasFlag(PollEventTypeMask.Input))
{
readEvents.Add(socket.Socket);
}
if (pollEvent.Data.InputEvents.HasFlag(PollEventTypeMask.Output))
{
writeEvents.Add(socket.Socket);
}
if (pollEvent.Data.InputEvents.HasFlag(PollEventTypeMask.Error))
{
errorEvents.Add(socket.Socket);
}
}
Socket.Select(readEvents, writeEvents, errorEvents, timeout);
updatedCount = readEvents.Count + writeEvents.Count + errorEvents.Count;
foreach (PollEvent pollEvent in events)
{
ManagedSocket socket = (ManagedSocket)pollEvent.FileDescriptor;
if (readEvents.Contains(socket.Socket))
{
pollEvent.Data.OutputEvents |= PollEventTypeMask.Input;
}
if (writeEvents.Contains(socket.Socket))
{
pollEvent.Data.OutputEvents |= PollEventTypeMask.Output;
}
if (errorEvents.Contains(socket.Socket))
{
pollEvent.Data.OutputEvents |= PollEventTypeMask.Error;
}
}
return LinuxError.SUCCESS;
}
} }
} }

View File

@@ -1,6 +1,6 @@
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{ {
[SuppressMessage("ReSharper", "InconsistentNaming")] [SuppressMessage("ReSharper", "InconsistentNaming")]
enum WsaError enum WsaError

View File

@@ -1,7 +1,8 @@
using System.Collections.Generic; using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System.Collections.Generic;
using System.Net.Sockets; using System.Net.Sockets;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{ {
static class WinSockHelper static class WinSockHelper
{ {

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
enum BsdAddressFamily : uint enum BsdAddressFamily : uint
{ {

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
enum BsdIoctl enum BsdIoctl
{ {

View File

@@ -1,6 +1,6 @@
using System; using System;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
class BsdMMsgHdr class BsdMMsgHdr
{ {

View File

@@ -1,7 +1,7 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
class BsdMsgHdr class BsdMsgHdr
{ {

View File

@@ -3,7 +3,7 @@ using System;
using System.Net; using System.Net;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
[StructLayout(LayoutKind.Sequential, Pack = 1, Size = 0x10)] [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 0x10)]
struct BsdSockAddr struct BsdSockAddr

View File

@@ -1,6 +1,6 @@
using System; using System;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
[Flags] [Flags]
enum BsdSocketCreationFlags enum BsdSocketCreationFlags

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
enum BsdSocketFlags enum BsdSocketFlags
{ {

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
enum BsdSocketOption enum BsdSocketOption
{ {

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
enum BsdSocketShutdownFlags enum BsdSocketShutdownFlags
{ {

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
enum BsdSocketType enum BsdSocketType
{ {

View File

@@ -1,6 +1,6 @@
using System; using System;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
[Flags] [Flags]
enum EventFdFlags : uint enum EventFdFlags : uint

View File

@@ -1,11 +1,13 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
interface IPollManager interface IPollManager
{ {
bool IsCompatible(PollEvent evnt); bool IsCompatible(PollEvent evnt);
LinuxError Poll(List<PollEvent> events, int timeoutMilliseconds, out int updatedCount); LinuxError Poll(List<PollEvent> events, int timeoutMilliseconds, out int updatedCount);
LinuxError Select(List<PollEvent> events, int timeout, out int updatedCount);
} }
} }

View File

@@ -1,6 +1,6 @@
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
[SuppressMessage("ReSharper", "InconsistentNaming")] [SuppressMessage("ReSharper", "InconsistentNaming")]
enum LinuxError enum LinuxError

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
class PollEvent class PollEvent
{ {

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
struct PollEventData struct PollEventData
{ {

View File

@@ -1,6 +1,6 @@
using System; using System;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
[Flags] [Flags]
enum PollEventTypeMask : ushort enum PollEventTypeMask : ushort

View File

@@ -1,4 +1,4 @@
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{ {
public struct TimeVal public struct TimeVal
{ {

View File

@@ -18,7 +18,10 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres
[Service("sfdnsres")] [Service("sfdnsres")]
class IResolver : IpcService class IResolver : IpcService
{ {
public IResolver(ServiceCtx context) { } public IResolver(ServiceCtx context)
{
DnsMitmResolver.Instance.ReloadEntries(context);
}
[CommandHipc(0)] [CommandHipc(0)]
// SetDnsAddressesPrivateRequest(u32, buffer<unknown, 5, 0>) // SetDnsAddressesPrivateRequest(u32, buffer<unknown, 5, 0>)
@@ -259,6 +262,16 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres
return ResultCode.Success; return ResultCode.Success;
} }
// Atmosphère extension for dns_mitm
[CommandHipc(65000)]
// AtmosphereReloadHostsFile()
public ResultCode AtmosphereReloadHostsFile(ServiceCtx context)
{
DnsMitmResolver.Instance.ReloadEntries(context);
return ResultCode.Success;
}
private static ResultCode GetHostByNameRequestImpl( private static ResultCode GetHostByNameRequestImpl(
ServiceCtx context, ServiceCtx context,
ulong inputBufferPosition, ulong inputBufferPosition,
@@ -321,7 +334,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres
try try
{ {
hostEntry = Dns.GetHostEntry(targetHost); hostEntry = DnsMitmResolver.Instance.ResolveAddress(targetHost);
} }
catch (SocketException exception) catch (SocketException exception)
{ {
@@ -537,7 +550,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres
try try
{ {
hostEntry = Dns.GetHostEntry(targetHost); hostEntry = DnsMitmResolver.Instance.ResolveAddress(targetHost);
} }
catch (SocketException exception) catch (SocketException exception)
{ {

View File

@@ -0,0 +1,106 @@
using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Services.Sockets.Nsd;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Enumeration;
using System.Net;
namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres.Proxy
{
class DnsMitmResolver
{
private const string HostsFilePath = "/atmosphere/hosts/default.txt";
private static DnsMitmResolver _instance;
public static DnsMitmResolver Instance => _instance ??= new DnsMitmResolver();
private readonly Dictionary<string, IPAddress> _mitmHostEntries = new();
public void ReloadEntries(ServiceCtx context)
{
string sdPath = context.Device.Configuration.VirtualFileSystem.GetSdCardPath();
string filePath = context.Device.Configuration.VirtualFileSystem.GetFullPath(sdPath, HostsFilePath);
_mitmHostEntries.Clear();
if (File.Exists(filePath))
{
using FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read);
using StreamReader reader = new(fileStream);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line == null)
{
break;
}
// Ignore comments and empty lines
if (line.StartsWith("#") || line.Trim().Length == 0)
{
continue;
}
string[] entry = line.Split(new[] { ' ', '\t' }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
// Hosts file example entry:
// 127.0.0.1 localhost loopback
// 0. Check the size of the array
if (entry.Length < 2)
{
Logger.Warning?.PrintMsg(LogClass.ServiceBsd, $"Invalid entry in hosts file: {line}");
continue;
}
// 1. Parse the address
if (!IPAddress.TryParse(entry[0], out IPAddress address))
{
Logger.Warning?.PrintMsg(LogClass.ServiceBsd, $"Failed to parse IP address in hosts file: {entry[0]}");
continue;
}
// 2. Check for AMS hosts file extension: "%"
for (int i = 1; i < entry.Length; i++)
{
entry[i] = entry[i].Replace("%", IManager.NsdSettings.Environment);
}
// 3. Add hostname to entry dictionary (updating duplicate entries)
foreach (string hostname in entry[1..])
{
_mitmHostEntries[hostname] = address;
}
}
}
}
public IPHostEntry ResolveAddress(string host)
{
foreach (var hostEntry in _mitmHostEntries)
{
// Check for AMS hosts file extension: "*"
// NOTE: MatchesSimpleExpression also allows "?" as a wildcard
if (FileSystemName.MatchesSimpleExpression(hostEntry.Key, host))
{
Logger.Info?.PrintMsg(LogClass.ServiceBsd, $"Redirecting '{host}' to: {hostEntry.Value}");
return new IPHostEntry
{
AddressList = new[] { hostEntry.Value },
HostName = hostEntry.Key,
Aliases = Array.Empty<string>()
};
}
}
// No match has been found, resolve the host using regular dns
return Dns.GetHostEntry(host);
}
}
}

View File

@@ -1,4 +1,5 @@
using Ryujinx.HLE.HOS.Services.Sockets.Bsd; using Ryujinx.HLE.HOS.Services.Sockets.Bsd;
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl;
using Ryujinx.HLE.HOS.Services.Ssl.Types; using Ryujinx.HLE.HOS.Services.Ssl.Types;
using System; using System;
using System.IO; using System.IO;

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
@@ -21,12 +21,12 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Concentus" Version="1.1.7" /> <PackageReference Include="Concentus" />
<PackageReference Include="LibHac" Version="0.17.0" /> <PackageReference Include="LibHac" />
<PackageReference Include="MsgPack.Cli" Version="1.0.1" /> <PackageReference Include="MsgPack.Cli" />
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.4" /> <PackageReference Include="SixLabors.ImageSharp" />
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta11" /> <PackageReference Include="SixLabors.ImageSharp.Drawing" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.25.1" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" />
</ItemGroup> </ItemGroup>
<!-- Due to Concentus. --> <!-- Due to Concentus. -->

View File

@@ -10,7 +10,7 @@ using Ryujinx.Common.Configuration.Hid.Controller;
using Ryujinx.Common.Configuration.Hid.Controller.Motion; using Ryujinx.Common.Configuration.Hid.Controller.Motion;
using Ryujinx.Common.Configuration.Hid.Keyboard; using Ryujinx.Common.Configuration.Hid.Keyboard;
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.Common.System; using Ryujinx.Common.SystemInterop;
using Ryujinx.Common.Utilities; using Ryujinx.Common.Utilities;
using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.GAL.Multithreading; using Ryujinx.Graphics.GAL.Multithreading;

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
@@ -11,8 +11,8 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="OpenTK.Core" Version="4.7.5" /> <PackageReference Include="OpenTK.Core" />
<PackageReference Include="Ryujinx.Graphics.Nvdec.Dependencies" Version="5.0.1-build12" /> <PackageReference Include="Ryujinx.Graphics.Nvdec.Dependencies" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -28,7 +28,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.9.1" /> <PackageReference Include="CommandLineParser" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -5,11 +5,11 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3"> <PackageReference Include="Microsoft.CodeAnalysis.Analyzers">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.4.0" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -6,7 +6,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Crc32.NET" Version="1.2.0" /> <PackageReference Include="Crc32.NET" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -6,9 +6,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NUnit" Version="3.13.3" /> <PackageReference Include="NUnit" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -3,7 +3,7 @@ using System.Runtime.InteropServices;
namespace Ryujinx.Memory namespace Ryujinx.Memory
{ {
public static class MemoryManagerUnixHelper public static partial class MemoryManagerUnixHelper
{ {
[Flags] [Flags]
public enum MmapProts : uint public enum MmapProts : uint
@@ -51,38 +51,38 @@ namespace Ryujinx.Memory
public const int MADV_DONTNEED = 4; public const int MADV_DONTNEED = 4;
public const int MADV_REMOVE = 9; public const int MADV_REMOVE = 9;
[DllImport("libc", EntryPoint = "mmap", SetLastError = true)] [LibraryImport("libc", EntryPoint = "mmap", SetLastError = true)]
private static extern IntPtr Internal_mmap(IntPtr address, ulong length, MmapProts prot, int flags, int fd, long offset); private static partial IntPtr Internal_mmap(IntPtr address, ulong length, MmapProts prot, int flags, int fd, long offset);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int mprotect(IntPtr address, ulong length, MmapProts prot); public static partial int mprotect(IntPtr address, ulong length, MmapProts prot);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int munmap(IntPtr address, ulong length); public static partial int munmap(IntPtr address, ulong length);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern IntPtr mremap(IntPtr old_address, ulong old_size, ulong new_size, int flags, IntPtr new_address); public static partial IntPtr mremap(IntPtr old_address, ulong old_size, ulong new_size, int flags, IntPtr new_address);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int madvise(IntPtr address, ulong size, int advice); public static partial int madvise(IntPtr address, ulong size, int advice);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int mkstemp(IntPtr template); public static partial int mkstemp(IntPtr template);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int unlink(IntPtr pathname); public static partial int unlink(IntPtr pathname);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int ftruncate(int fildes, IntPtr length); public static partial int ftruncate(int fildes, IntPtr length);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int close(int fd); public static partial int close(int fd);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int shm_open(IntPtr name, int oflag, uint mode); public static partial int shm_open(IntPtr name, int oflag, uint mode);
[DllImport("libc", SetLastError = true)] [LibraryImport("libc", SetLastError = true)]
public static extern int shm_unlink(IntPtr name); public static partial int shm_unlink(IntPtr name);
private static int MmapFlagsToSystemFlags(MmapFlags flags) private static int MmapFlagsToSystemFlags(MmapFlags flags)
{ {

View File

@@ -3,20 +3,20 @@ using System.Runtime.InteropServices;
namespace Ryujinx.Memory.WindowsShared namespace Ryujinx.Memory.WindowsShared
{ {
static class WindowsApi static partial class WindowsApi
{ {
public static readonly IntPtr InvalidHandleValue = new IntPtr(-1); public static readonly IntPtr InvalidHandleValue = new IntPtr(-1);
public static readonly IntPtr CurrentProcessHandle = new IntPtr(-1); public static readonly IntPtr CurrentProcessHandle = new IntPtr(-1);
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr VirtualAlloc( public static partial IntPtr VirtualAlloc(
IntPtr lpAddress, IntPtr lpAddress,
IntPtr dwSize, IntPtr dwSize,
AllocationType flAllocationType, AllocationType flAllocationType,
MemoryProtection flProtect); MemoryProtection flProtect);
[DllImport("KernelBase.dll", SetLastError = true)] [LibraryImport("KernelBase.dll", SetLastError = true)]
public static extern IntPtr VirtualAlloc2( public static partial IntPtr VirtualAlloc2(
IntPtr process, IntPtr process,
IntPtr lpAddress, IntPtr lpAddress,
IntPtr dwSize, IntPtr dwSize,
@@ -25,18 +25,20 @@ namespace Ryujinx.Memory.WindowsShared
IntPtr extendedParameters, IntPtr extendedParameters,
ulong parameterCount); ulong parameterCount);
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
public static extern bool VirtualProtect( [return: MarshalAs(UnmanagedType.Bool)]
public static partial bool VirtualProtect(
IntPtr lpAddress, IntPtr lpAddress,
IntPtr dwSize, IntPtr dwSize,
MemoryProtection flNewProtect, MemoryProtection flNewProtect,
out MemoryProtection lpflOldProtect); out MemoryProtection lpflOldProtect);
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
public static extern bool VirtualFree(IntPtr lpAddress, IntPtr dwSize, AllocationType dwFreeType); [return: MarshalAs(UnmanagedType.Bool)]
public static partial bool VirtualFree(IntPtr lpAddress, IntPtr dwSize, AllocationType dwFreeType);
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true, EntryPoint = "CreateFileMappingW")]
public static extern IntPtr CreateFileMapping( public static partial IntPtr CreateFileMapping(
IntPtr hFile, IntPtr hFile,
IntPtr lpFileMappingAttributes, IntPtr lpFileMappingAttributes,
FileMapProtection flProtect, FileMapProtection flProtect,
@@ -44,19 +46,20 @@ namespace Ryujinx.Memory.WindowsShared
uint dwMaximumSizeLow, uint dwMaximumSizeLow,
[MarshalAs(UnmanagedType.LPWStr)] string lpName); [MarshalAs(UnmanagedType.LPWStr)] string lpName);
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject); [return: MarshalAs(UnmanagedType.Bool)]
public static partial bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr MapViewOfFile( public static partial IntPtr MapViewOfFile(
IntPtr hFileMappingObject, IntPtr hFileMappingObject,
uint dwDesiredAccess, uint dwDesiredAccess,
uint dwFileOffsetHigh, uint dwFileOffsetHigh,
uint dwFileOffsetLow, uint dwFileOffsetLow,
IntPtr dwNumberOfBytesToMap); IntPtr dwNumberOfBytesToMap);
[DllImport("KernelBase.dll", SetLastError = true)] [LibraryImport("KernelBase.dll", SetLastError = true)]
public static extern IntPtr MapViewOfFile3( public static partial IntPtr MapViewOfFile3(
IntPtr hFileMappingObject, IntPtr hFileMappingObject,
IntPtr process, IntPtr process,
IntPtr baseAddress, IntPtr baseAddress,
@@ -67,17 +70,19 @@ namespace Ryujinx.Memory.WindowsShared
IntPtr extendedParameters, IntPtr extendedParameters,
ulong parameterCount); ulong parameterCount);
[DllImport("kernel32.dll", SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)]
public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress); [return: MarshalAs(UnmanagedType.Bool)]
public static partial bool UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport("KernelBase.dll", SetLastError = true)] [LibraryImport("KernelBase.dll", SetLastError = true)]
public static extern bool UnmapViewOfFile2(IntPtr process, IntPtr lpBaseAddress, ulong unmapFlags); [return: MarshalAs(UnmanagedType.Bool)]
public static partial bool UnmapViewOfFile2(IntPtr process, IntPtr lpBaseAddress, ulong unmapFlags);
[DllImport("kernel32.dll")] [LibraryImport("kernel32.dll")]
public static extern uint GetLastError(); public static partial uint GetLastError();
[DllImport("kernel32.dll")] [LibraryImport("kernel32.dll")]
public static extern int GetCurrentThreadId(); public static partial int GetCurrentThreadId();
public static MemoryProtection GetProtection(MemoryPermission permission) public static MemoryProtection GetProtection(MemoryPermission permission)
{ {

View File

@@ -5,7 +5,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Ryujinx.SDL2-CS" Version="2.24.2-build21" /> <PackageReference Include="Ryujinx.SDL2-CS" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -11,7 +11,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.9.1" /> <PackageReference Include="CommandLineParser" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,12 +1,14 @@
using Ryujinx.Tests.Unicorn.Native.Const; using Ryujinx.Tests.Unicorn.Native.Const;
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Ryujinx.Tests.Unicorn.Native namespace Ryujinx.Tests.Unicorn.Native
{ {
public static class Interface public static partial class Interface
{ {
public static bool IsUnicornAvailable { get; private set; } = true; public static bool IsUnicornAvailable { get; private set; } = true;
@@ -43,9 +45,9 @@ namespace Ryujinx.Tests.Unicorn.Native
} }
} }
public static void MarshalArrayOf<T>(IntPtr input, int length, out T[] output) public static void MarshalArrayOf<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(IntPtr input, int length, out T[] output)
{ {
int size = Marshal.SizeOf(typeof(T)); int size = Marshal.SizeOf<T>();
output = new T[length]; output = new T[length];
@@ -57,43 +59,43 @@ namespace Ryujinx.Tests.Unicorn.Native
} }
} }
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern uint uc_version(out uint major, out uint minor); public static partial uint uc_version(out uint major, out uint minor);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_open(Arch arch, Mode mode, out IntPtr uc); public static partial Error uc_open(Arch arch, Mode mode, out IntPtr uc);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_close(IntPtr uc); public static partial Error uc_close(IntPtr uc);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern IntPtr uc_strerror(Error err); public static partial IntPtr uc_strerror(Error err);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_reg_write(IntPtr uc, int regid, byte[] value); public static partial Error uc_reg_write(IntPtr uc, int regid, byte[] value);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_reg_read(IntPtr uc, int regid, byte[] value); public static partial Error uc_reg_read(IntPtr uc, int regid, byte[] value);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_mem_write(IntPtr uc, ulong address, byte[] bytes, ulong size); public static partial Error uc_mem_write(IntPtr uc, ulong address, byte[] bytes, ulong size);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_mem_read(IntPtr uc, ulong address, byte[] bytes, ulong size); public static partial Error uc_mem_read(IntPtr uc, ulong address, byte[] bytes, ulong size);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_emu_start(IntPtr uc, ulong begin, ulong until, ulong timeout, ulong count); public static partial Error uc_emu_start(IntPtr uc, ulong begin, ulong until, ulong timeout, ulong count);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_mem_map(IntPtr uc, ulong address, ulong size, uint perms); public static partial Error uc_mem_map(IntPtr uc, ulong address, ulong size, uint perms);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_mem_unmap(IntPtr uc, ulong address, ulong size); public static partial Error uc_mem_unmap(IntPtr uc, ulong address, ulong size);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_mem_protect(IntPtr uc, ulong address, ulong size, uint perms); public static partial Error uc_mem_protect(IntPtr uc, ulong address, ulong size, uint perms);
[DllImport("unicorn", CallingConvention = CallingConvention.Cdecl)] [LibraryImport("unicorn")]
public static extern Error uc_mem_regions(IntPtr uc, out IntPtr regions, out uint count); public static partial Error uc_mem_regions(IntPtr uc, out IntPtr regions, out uint count);
} }
} }

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
@@ -18,9 +18,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NUnit" Version="3.13.3" /> <PackageReference Include="NUnit" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -35,14 +35,14 @@
<Target Name="CopyUnicorn" AfterTargets="Build"> <Target Name="CopyUnicorn" AfterTargets="Build">
<ItemGroup> <ItemGroup>
<UnicornLib Include="..\Ryujinx.Tests.Unicorn\libs\$(TargetOS)\*unicorn.*"/> <UnicornLib Include="..\Ryujinx.Tests.Unicorn\libs\$(TargetOS)\*unicorn.*" />
</ItemGroup> </ItemGroup>
<Copy SourceFiles="@(UnicornLib)" DestinationFolder="$(OutputPath)" ContinueOnError="true" /> <Copy SourceFiles="@(UnicornLib)" DestinationFolder="$(OutputPath)" ContinueOnError="true" />
</Target> </Target>
<Target Name="CleanUnicorn" BeforeTargets="Clean"> <Target Name="CleanUnicorn" BeforeTargets="Clean">
<ItemGroup> <ItemGroup>
<UnicornLib Include="$(OutputPath)/unicorn.*"/> <UnicornLib Include="$(OutputPath)/unicorn.*" />
</ItemGroup> </ItemGroup>
<Delete Files="@(UnicornLib)" /> <Delete Files="@(UnicornLib)" />
</Target> </Target>

View File

@@ -5,7 +5,7 @@ using System.Runtime.Versioning;
namespace Ryujinx.Ui.Common.Helper namespace Ryujinx.Ui.Common.Helper
{ {
public static class ConsoleHelper public static partial class ConsoleHelper
{ {
public static bool SetConsoleWindowStateSupported => OperatingSystem.IsWindows(); public static bool SetConsoleWindowStateSupported => OperatingSystem.IsWindows();
@@ -39,11 +39,12 @@ namespace Ryujinx.Ui.Common.Helper
} }
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
[DllImport("kernel32")] [LibraryImport("kernel32")]
static extern IntPtr GetConsoleWindow(); private static partial IntPtr GetConsoleWindow();
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
[DllImport("user32")] [LibraryImport("user32")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [return: MarshalAs(UnmanagedType.Bool)]
private static partial bool ShowWindow(IntPtr hWnd, int nCmdShow);
} }
} }

View File

@@ -2,6 +2,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -41,7 +42,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="DiscordRichPresence" Version="1.1.3.18" /> <PackageReference Include="DiscordRichPresence" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

Some files were not shown because too many files have changed in this diff Show More