diff --git a/.editorconfig b/.editorconfig
index de87d7b5b48..65a5481b0ce 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -12,9 +12,11 @@ csharp_indent_switch_labels = true
csharp_indent_case_contents = true
csharp_indent_labels = one_less_than_current
+# Globalization rules
+dotnet_code_quality.CA1305.excluded_symbol_names = T:System.Byte|T:System.SByte|T:System.Int16|T:System.UInt16|T:System.Int32|T:System.UInt32|T:System.Int64|T:System.UInt64|T:System.String|T:System.Text.StringBuilder|T:System.Convert
+
# Style rules
# Can't be in .globalconfig because dotnet format doesn't respect that https://github.com/dotnet/format/issues/1643
-
# Remove unnecessary cast
dotnet_diagnostic.IDE0004.severity = warning
# Remove unnecessary import
@@ -49,6 +51,8 @@ dotnet_diagnostic.IDE0032.severity = suggestion
dotnet_diagnostic.IDE0034.severity = suggestion
# Use pattern matching to avoid is check followed by a cast (without variable)
dotnet_diagnostic.IDE0038.severity = warning
+# Use a local function instead of an anonymous function
+dotnet_diagnostic.IDE0039.severity = none
# Use is null check
dotnet_diagnostic.IDE0041.severity = warning
# Deconstruct variable declaration
@@ -109,7 +113,7 @@ dotnet_diagnostic.IDE0260.severity = suggestion
# Use nameof
dotnet_diagnostic.IDE0280.severity = error
-csharp_style_var_when_type_is_apparent = true
+csharp_style_var_when_type_is_apparent = false
csharp_style_var_elsewhere = true
csharp_style_expression_bodied_methods = when_on_single_line
diff --git a/Common.ruleset b/Common.ruleset
index c0d05e8bfa2..b7517afcf77 100644
--- a/Common.ruleset
+++ b/Common.ruleset
@@ -14,7 +14,7 @@
-
+
diff --git a/contributing.md b/contributing.md
index ff94122ffea..72b1533b2c1 100644
--- a/contributing.md
+++ b/contributing.md
@@ -76,7 +76,9 @@ It's probably a good idea to get the .NET SDK, even if you're not working on a .
For EmuHawk and libraries in the main solution, which do not target .NET 6, we have [this page](https://github.com/TASEmulators/BizHawk/wiki/Available-C%23-and-.NET-features) documenting which features are actually available to use.
+### Code Analysis
+Visual Studio can detect and show issues and possible optimizations in the IDE before build time. In the Analyze menu pick Run Code Analysis -> On Solution. From there you can open the Error list in the bottom left and highlight issues of different severity level Errors/Warnings/Messages and adjust the scope as small as the open documents and as wide as the entire solution. Developers should target to have no code introduced flagging the Error and Warning levels. It's also good to minimize warnings at the Message severity level either by adopting the suggested fixes or by ignoring irrelevant Messages with `#pragma` directives. Many warnings can be auto-fixed by the `dotnet format` command or by the quick actions menu found on the left next to a line number when hovering a line.
## blip_buf
> Audio resampling library.
diff --git a/src/BizHawk.BizInvoke/BizExvoker.cs b/src/BizHawk.BizInvoke/BizExvoker.cs
index 9afc683e5e7..3920284e1c1 100644
--- a/src/BizHawk.BizInvoke/BizExvoker.cs
+++ b/src/BizHawk.BizInvoke/BizExvoker.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
@@ -23,7 +23,7 @@ public static class BizExvoker
static BizExvoker()
{
- var aname = new AssemblyName("BizExvokeProxyAssembly");
+ AssemblyName aname = new("BizExvokeProxyAssembly");
ImplAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(aname, AssemblyBuilderAccess.Run);
ImplModuleBuilder = ImplAssemblyBuilder.DefineDynamicModule("BizExvokerModule");
}
@@ -65,10 +65,10 @@ public DelegateStorage(Type type)
var typeBuilder = ImplModuleBuilder.DefineType($"Bizhawk.BizExvokeHolder{type.Name}", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed);
- foreach (var a in methods)
+ foreach (var (Info, Attr) in methods)
{
- var delegateType = BizInvokeUtilities.CreateDelegateType(a.Info, a.Attr!.CallingConvention, typeBuilder, out _).CreateType()!;
- DelegateTypes.Add(new StoredDelegateInfo(a.Info, delegateType, a.Attr.EntryPoint ?? a.Info.Name));
+ var delegateType = BizInvokeUtilities.CreateDelegateType(Info, Attr!.CallingConvention, typeBuilder, out _).CreateType()!;
+ DelegateTypes.Add(new StoredDelegateInfo(Info, delegateType, Attr.EntryPoint ?? Info.Name));
}
StorageType = typeBuilder.CreateType()!;
OriginalType = type;
@@ -77,15 +77,15 @@ public DelegateStorage(Type type)
private class ExvokerImpl : IImportResolver
{
- private readonly Dictionary EntryPoints = new Dictionary();
+ private readonly Dictionary EntryPoints = new();
- private readonly List Delegates = new List();
+ private readonly List Delegates = new();
public ExvokerImpl(object o, DelegateStorage d, ICallingConventionAdapter a)
{
foreach (var sdt in d.DelegateTypes)
{
- var del = Delegate.CreateDelegate(sdt.DelegateType, o, sdt.Method);
+ Delegate del = Delegate.CreateDelegate(sdt.DelegateType, o, sdt.Method);
Delegates.Add(del); // prevent garbage collection of the delegate, which would invalidate the pointer
EntryPoints.Add(sdt.EntryPointName, a.GetFunctionPointerForDelegate(del));
}
@@ -96,7 +96,7 @@ public ExvokerImpl(object o, DelegateStorage d, ICallingConventionAdapter a)
public IntPtr GetProcAddrOrThrow(string entryPoint) => EntryPoints.TryGetValue(entryPoint, out var ret) ? ret : throw new InvalidOperationException($"could not find {entryPoint} in exports");
}
- private static readonly Dictionary Impls = new Dictionary();
+ private static readonly Dictionary Impls = new();
public static IImportResolver GetExvoker(object o, ICallingConventionAdapter a)
diff --git a/src/BizHawk.BizInvoke/BizInvokeUtilities.cs b/src/BizHawk.BizInvoke/BizInvokeUtilities.cs
index 0b9893bba19..dc2ae4fbeb5 100644
--- a/src/BizHawk.BizInvoke/BizInvokeUtilities.cs
+++ b/src/BizHawk.BizInvoke/BizInvokeUtilities.cs
@@ -47,7 +47,7 @@ public static TypeBuilder CreateDelegateType(MethodInfo method, CallingConventio
for (int i = 0; i < paramInfos.Length; i++)
{
var p = delegateInvoke.DefineParameter(i + 1, ParameterAttributes.None, paramInfos[i].Name);
- foreach (var a in paramInfos[i].GetCustomAttributes(false))
+ foreach (object? a in paramInfos[i].GetCustomAttributes(false))
{
p.SetCustomAttribute(GetAttributeBuilder(a));
}
@@ -55,16 +55,16 @@ public static TypeBuilder CreateDelegateType(MethodInfo method, CallingConventio
{
var p = delegateInvoke.DefineParameter(0, ParameterAttributes.Retval, method.ReturnParameter!.Name);
- foreach (var a in method.ReturnParameter.GetCustomAttributes(false))
+ foreach (object? a in method.ReturnParameter.GetCustomAttributes(false))
{
p.SetCustomAttribute(GetAttributeBuilder(a));
}
}
- delegateInvoke.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
-
- // add the [UnmanagedFunctionPointer] to the delegate so interop will know how to call it
- var attr = new CustomAttributeBuilder(
+ delegateInvoke.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
+
+ // add the [UnmanagedFunctionPointer] to the delegate so interop will know how to call it
+ CustomAttributeBuilder attr = new(
typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new[] { typeof(CallingConvention) })!,
new object[] { nativeCall });
delegateType.SetCustomAttribute(attr);
diff --git a/src/BizHawk.BizInvoke/BizInvoker.cs b/src/BizHawk.BizInvoke/BizInvoker.cs
index 8e1351fa76c..37ba23a4e8c 100644
--- a/src/BizHawk.BizInvoke/BizInvoker.cs
+++ b/src/BizHawk.BizInvoke/BizInvoker.cs
@@ -52,7 +52,7 @@ public InvokerImpl(
public object Create(IImportResolver dll, IMonitor? monitor, ICallingConventionAdapter adapter)
{
- var ret = Activator.CreateInstance(_implType)!;
+ object ret = Activator.CreateInstance(_implType)!;
_connectCallingConventionAdapter(ret, adapter);
foreach (var f in _hooks)
{
@@ -93,7 +93,7 @@ public object Create(IImportResolver dll, IMonitor? monitor, ICallingConventionA
static BizInvoker()
{
- var aname = new AssemblyName("BizInvokeProxyAssembly");
+ AssemblyName aname = new("BizInvokeProxyAssembly");
ImplAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(aname, AssemblyBuilderAccess.Run);
ImplModuleBuilder = ImplAssemblyBuilder.DefineDynamicModule("BizInvokerModule");
ClassFieldOffset = BizInvokerUtilities.ComputeClassFirstFieldOffset();
@@ -109,7 +109,7 @@ static BizInvoker()
public static T GetInvoker(IImportResolver dll, ICallingConventionAdapter adapter)
where T : class
{
- var nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType();
+ bool nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType();
InvokerImpl impl;
lock (Impls) impl = Impls.GetValueOrPut(
typeof(T),
@@ -126,7 +126,7 @@ public static T GetInvoker(IImportResolver dll, ICallingConventionAdapter ada
public static T GetInvoker(IImportResolver dll, IMonitor monitor, ICallingConventionAdapter adapter)
where T : class
{
- var nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType();
+ bool nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType();
InvokerImpl impl;
lock (Impls) impl = Impls.GetValueOrPut(
typeof(T),
@@ -152,13 +152,8 @@ private static InvokerImpl CreateProxy(Type baseType, bool monitor, bool nonTriv
throw new InvalidOperationException("Type must be public");
}
- var baseConstructor = baseType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
- if (baseConstructor == null)
- {
- throw new InvalidOperationException("Base type must have a zero arg constructor");
- }
-
- var baseMethods = baseType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
+ var baseConstructor = baseType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null) ?? throw new InvalidOperationException("Base type must have a zero arg constructor");
+ List<(MethodInfo Info, BizImportAttribute Attr)> baseMethods = baseType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Select(static m => (Info: m, Attr: m.GetCustomAttributes(true).OfType().FirstOrDefault()))
.Where(a => a.Attr != null)
.ToList();
@@ -179,7 +174,7 @@ private static InvokerImpl CreateProxy(Type baseType, bool monitor, bool nonTriv
}
// hooks that will be run on the created proxy object
- var postCreateHooks = new List>();
+ List> postCreateHooks = new();
var type = ImplModuleBuilder.DefineType($"Bizhawk.BizInvokeProxy{baseType.Name}", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed, baseType);
@@ -187,13 +182,13 @@ private static InvokerImpl CreateProxy(Type baseType, bool monitor, bool nonTriv
var adapterField = type.DefineField("CallingConvention", typeof(ICallingConventionAdapter), FieldAttributes.Public);
- foreach (var mi in baseMethods)
+ foreach (var (Info, Attr) in baseMethods)
{
- var entryPointName = mi.Attr!.EntryPoint ?? mi.Info.Name;
+ string entryPointName = Attr!.EntryPoint ?? Info.Name;
- var hook = mi.Attr.Compatibility
- ? ImplementMethodDelegate(type, mi.Info, mi.Attr.CallingConvention, entryPointName, monitorField, nonTrivialAdapter)
- : ImplementMethodCalli(type, mi.Info, mi.Attr.CallingConvention, entryPointName, monitorField, adapterField);
+ var hook = Attr.Compatibility
+ ? ImplementMethodDelegate(type, Info, Attr.CallingConvention, entryPointName, monitorField, nonTrivialAdapter)
+ : ImplementMethodCalli(type, Info, Attr.CallingConvention, entryPointName, monitorField, adapterField);
postCreateHooks.Add(hook);
}
@@ -336,7 +331,7 @@ private static Action Implem
{
var paramInfos = baseMethod.GetParameters();
var paramTypes = paramInfos.Select(p => p.ParameterType).ToArray();
- var paramLoadInfos = new List();
+ List paramLoadInfos = new();
var returnType = baseMethod.ReturnType;
if (returnType != typeof(void) && !returnType.IsPrimitive && !returnType.IsPointer && !returnType.IsEnum)
{
@@ -381,7 +376,7 @@ private static Action Implem
bool WantsWinAPIBool()
{
- var attrs = baseMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(MarshalAsAttribute), false);
+ object[] attrs = baseMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(MarshalAsAttribute), false);
return attrs.Length > 0 && ((MarshalAsAttribute)attrs[0]).Value is UnmanagedType.Bool;
}
diff --git a/src/BizHawk.BizInvoke/BizInvokerUtilities.cs b/src/BizHawk.BizInvoke/BizInvokerUtilities.cs
index 502fab09914..d3436d14626 100644
--- a/src/BizHawk.BizInvoke/BizInvokerUtilities.cs
+++ b/src/BizHawk.BizInvoke/BizInvokerUtilities.cs
@@ -50,10 +50,7 @@ private class CF
/// Computes the byte offset of the first field of any class relative to a class pointer.
///
///
- public static int ComputeClassFirstFieldOffset()
- {
- return ComputeFieldOffset(typeof(CF).GetField("FirstField"));
- }
+ public static int ComputeClassFirstFieldOffset() => ComputeFieldOffset(typeof(CF).GetField("FirstField"));
///
/// Compute the byte offset of the first byte of string data (UTF16) relative to a pointer to the string.
@@ -61,7 +58,7 @@ public static int ComputeClassFirstFieldOffset()
///
public static int ComputeStringOffset()
{
- var s = new string(Array.Empty());
+ string s = new(Array.Empty());
int ret;
fixed(char* fx = s)
{
@@ -77,7 +74,7 @@ public static int ComputeStringOffset()
///
public static int ComputeValueArrayElementOffset()
{
- var arr = new int[4];
+ int[] arr = new int[4];
int ret;
fixed (int* p = arr)
{
@@ -94,8 +91,8 @@ public static int ComputeValueArrayElementOffset()
///
public static int ComputeObjectArrayElementOffset()
{
- var obj = new object[4];
- var method = new DynamicMethod("ComputeObjectArrayElementOffsetHelper", typeof(int), new[] { typeof(object[]) }, typeof(string).Module, true);
+ object[] obj = new object[4];
+ DynamicMethod method = new("ComputeObjectArrayElementOffsetHelper", typeof(int), new[] { typeof(object[]) }, typeof(string).Module, true);
var il = method.GetILGenerator();
var local = il.DeclareLocal(typeof(object[]), true);
il.Emit(OpCodes.Ldarg_0);
@@ -109,7 +106,7 @@ public static int ComputeObjectArrayElementOffset()
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Conv_I4);
il.Emit(OpCodes.Ret);
- var del = (Func)method.CreateDelegate(typeof(Func));
+ Func del = (Func)method.CreateDelegate(typeof(Func));
return del(obj);
}
@@ -124,8 +121,8 @@ public static int ComputeFieldOffset(FieldInfo fi)
throw new NotImplementedException("Only supported for class fields right now");
}
- var obj = FormatterServices.GetUninitializedObject(fi.DeclaringType);
- var method = new DynamicMethod("ComputeFieldOffsetHelper", typeof(int), new[] { typeof(object) }, typeof(string).Module, true);
+ object obj = FormatterServices.GetUninitializedObject(fi.DeclaringType);
+ DynamicMethod method = new("ComputeFieldOffsetHelper", typeof(int), new[] { typeof(object) }, typeof(string).Module, true);
var il = method.GetILGenerator();
var local = il.DeclareLocal(fi.DeclaringType, true);
il.Emit(OpCodes.Ldarg_0);
@@ -138,7 +135,7 @@ public static int ComputeFieldOffset(FieldInfo fi)
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Conv_I4);
il.Emit(OpCodes.Ret);
- var del = (Func)method.CreateDelegate(typeof(Func));
+ Func del = (Func)method.CreateDelegate(typeof(Func));
return del(obj);
}
}
diff --git a/src/BizHawk.BizInvoke/CallingConventionAdapter.cs b/src/BizHawk.BizInvoke/CallingConventionAdapter.cs
index 24b7b5e5219..2f72f622ea5 100644
--- a/src/BizHawk.BizInvoke/CallingConventionAdapter.cs
+++ b/src/BizHawk.BizInvoke/CallingConventionAdapter.cs
@@ -95,25 +95,13 @@ public static class CallingConventionAdapters
{
private class NativeConvention : ICallingConventionAdapter
{
- public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime)
- {
- return p;
- }
+ public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime) => p;
- public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType)
- {
- return Marshal.GetDelegateForFunctionPointer(p, delegateType);
- }
+ public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType) => Marshal.GetDelegateForFunctionPointer(p, delegateType);
- public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime)
- {
- return p;
- }
+ public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime) => p;
- public IntPtr GetFunctionPointerForDelegate(Delegate d)
- {
- return Marshal.GetFunctionPointerForDelegate(d);
- }
+ public IntPtr GetFunctionPointerForDelegate(Delegate d) => Marshal.GetFunctionPointerForDelegate(d);
}
///
@@ -124,17 +112,11 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d)
///
/// waterbox calling convention, including thunk handling for stack marshalling
///
- public static ICallingConventionAdapter MakeWaterbox(IEnumerable slots, ICallbackAdjuster waterboxHost)
- {
- return new WaterboxAdapter(slots, waterboxHost);
- }
+ public static ICallingConventionAdapter MakeWaterbox(IEnumerable slots, ICallbackAdjuster waterboxHost) => new WaterboxAdapter(slots, waterboxHost);
///
/// waterbox calling convention, including thunk handling for stack marshalling. Can only do callins, not callouts
///
- public static ICallingConventionAdapter MakeWaterboxDepartureOnly(ICallbackAdjuster waterboxHost)
- {
- return new WaterboxAdapter(null, waterboxHost);
- }
+ public static ICallingConventionAdapter MakeWaterboxDepartureOnly(ICallbackAdjuster waterboxHost) => new WaterboxAdapter(null, waterboxHost);
///
/// Get a waterbox calling convention adapater, except no wrapping is done for stack marshalling and callback support.
@@ -142,24 +124,15 @@ public static ICallingConventionAdapter MakeWaterboxDepartureOnly(ICallbackAdjus
/// DO NOT USE THIS.
///
///
- public static ICallingConventionAdapter GetWaterboxUnsafeUnwrapped()
- {
- return WaterboxAdapter.WaterboxWrapper;
- }
+ public static ICallingConventionAdapter GetWaterboxUnsafeUnwrapped() => WaterboxAdapter.WaterboxWrapper;
private class WaterboxAdapter : ICallingConventionAdapter
{
private class ReferenceEqualityComparer : IEqualityComparer
{
- public bool Equals(Delegate x, Delegate y)
- {
- return x == y;
- }
+ public bool Equals(Delegate x, Delegate y) => x == y;
- public int GetHashCode(Delegate obj)
- {
- return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
- }
+ public int GetHashCode(Delegate obj) => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
internal static readonly ICallingConventionAdapter WaterboxWrapper;
@@ -190,7 +163,7 @@ public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifet
throw new InvalidOperationException("This calling convention adapter was created for departure only! Pass known delegate slots when constructing to enable arrival");
}
if (lifetime is not Delegate d) throw new ArgumentException(message: "For this calling convention adapter, lifetimes must be delegate so guest slot can be inferred", paramName: nameof(lifetime));
- if (!_slots.TryGetValue(d, out var slot))
+ if (!_slots.TryGetValue(d, out int slot))
{
throw new InvalidOperationException("All callback delegates must be registered at load");
}
@@ -215,7 +188,7 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d)
{
throw new InvalidOperationException("This calling convention adapter was created for departure only! Pass known delegate slots when constructing to enable arrival");
}
- if (!_slots.TryGetValue(d, out var slot))
+ if (!_slots.TryGetValue(d, out int slot))
{
throw new InvalidOperationException("All callback delegates must be registered at load");
}
@@ -288,8 +261,8 @@ private static int VerifyDelegateSignature(ParameterInfo pp)
VerifyParameter(pp.ReturnType);
foreach (var ppp in pp.ParameterTypes)
VerifyParameter(ppp);
- var ret = pp.ParameterTypes.Count(t => t != typeof(float) && t != typeof(double));
- var fargs = pp.ParameterTypes.Count - ret;
+ int ret = pp.ParameterTypes.Count(t => t != typeof(float) && t != typeof(double));
+ int fargs = pp.ParameterTypes.Count - ret;
if (ret > 6 || fargs > 4)
throw new InvalidOperationException("Too many parameters to marshal!");
// a function may only use exclusively floating point args or integer/pointer args
@@ -304,7 +277,7 @@ private void WriteThunk(IntPtr thunkFunctionAddress, IntPtr calleeAddress, int i
{
_memory.Protect(_memory.Start, _memory.Size, MemoryBlock.Protection.RW);
var ss = _memory.GetStream(_memory.Start + (ulong)index * BlockSize, BlockSize, true);
- var bw = new BinaryWriter(ss);
+ BinaryWriter bw = new(ss);
// The thunks all take the expected parameters in the expected places, but additionally take the parameter
// of the function to call as a hidden extra parameter in rax.
@@ -325,10 +298,7 @@ private void WriteThunk(IntPtr thunkFunctionAddress, IntPtr calleeAddress, int i
_memory.Protect(_memory.Start, _memory.Size, MemoryBlock.Protection.RX);
}
- private IntPtr GetThunkAddress(int index)
- {
- return Z.US(_memory.Start + (ulong)index * BlockSize);
- }
+ private IntPtr GetThunkAddress(int index) => Z.US(_memory.Start + (ulong)index * BlockSize);
private void SetLifetime(int index, object lifetime)
{
@@ -342,7 +312,7 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d)
// on the same delegate and not leak extra memory, so the result has to be cached
lock (_sync)
{
- var index = FindUsedIndex(d);
+ int index = FindUsedIndex(d);
if (index != -1)
{
return GetThunkAddress(index);
@@ -359,8 +329,8 @@ public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifet
{
lock (_sync)
{
- var index = FindFreeIndex();
- var count = VerifyDelegateSignature(pp);
+ int index = FindFreeIndex();
+ int count = VerifyDelegateSignature(pp);
WriteThunk(ThunkDll.GetProcAddrOrThrow($"arrive{count}"), p, index);
SetLifetime(index, lifetime);
return GetThunkAddress(index);
@@ -371,8 +341,8 @@ public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType)
{
lock (_sync)
{
- var index = FindFreeIndex();
- var count = VerifyDelegateSignature(new(delegateType));
+ int index = FindFreeIndex();
+ int count = VerifyDelegateSignature(new(delegateType));
WriteThunk(ThunkDll.GetProcAddrOrThrow($"depart{count}"), p, index);
var ret = Marshal.GetDelegateForFunctionPointer(GetThunkAddress(index), delegateType);
SetLifetime(index, ret);
@@ -384,8 +354,8 @@ public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lif
{
lock (_sync)
{
- var index = FindFreeIndex();
- var count = VerifyDelegateSignature(pp);
+ int index = FindFreeIndex();
+ int count = VerifyDelegateSignature(pp);
WriteThunk(ThunkDll.GetProcAddrOrThrow($"depart{count}"), p, index);
SetLifetime(index, lifetime);
return GetThunkAddress(index);
diff --git a/src/BizHawk.BizInvoke/FPCtrl.cs b/src/BizHawk.BizInvoke/FPCtrl.cs
index dff5efbaed3..7cd22407691 100644
--- a/src/BizHawk.BizInvoke/FPCtrl.cs
+++ b/src/BizHawk.BizInvoke/FPCtrl.cs
@@ -37,7 +37,7 @@ static FPCtrl()
_memory = new(4096);
_memory.Protect(_memory.Start, _memory.Size, MemoryBlock.Protection.RW);
var ss = _memory.GetStream(_memory.Start, 64, true);
- var bw = new BinaryWriter(ss);
+ BinaryWriter bw = new(ss);
// FYI: The push/pop is only needed on Windows, but doesn't do any harm on Linux
diff --git a/src/BizHawk.BizInvoke/MemoryBlock.cs b/src/BizHawk.BizInvoke/MemoryBlock.cs
index 56189105987..3d267d82f69 100644
--- a/src/BizHawk.BizInvoke/MemoryBlock.cs
+++ b/src/BizHawk.BizInvoke/MemoryBlock.cs
@@ -65,9 +65,9 @@ public void Protect(ulong start, ulong length, Protection prot)
// Note: asking for prot.none on memory that was not previously committed, commits it
- var computedStart = WaterboxUtils.AlignDown(start);
- var computedEnd = WaterboxUtils.AlignUp(start + length);
- var computedLength = computedEnd - computedStart;
+ ulong computedStart = WaterboxUtils.AlignDown(start);
+ ulong computedEnd = WaterboxUtils.AlignUp(start + length);
+ ulong computedLength = computedEnd - computedStart;
_pal.Protect(computedStart, computedLength, prot);
}
diff --git a/src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs b/src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs
index 1a4ac74c8b3..2f86cd17c54 100644
--- a/src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs
+++ b/src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs
@@ -20,7 +20,7 @@ internal sealed class MemoryBlockLinuxPal : IMemoryBlockPal
///
public MemoryBlockLinuxPal(ulong size)
{
- var ptr = (ulong)mmap(IntPtr.Zero, Z.UU(size), MemoryProtection.None, 0x22 /* MAP_PRIVATE | MAP_ANON */, -1, IntPtr.Zero);
+ ulong ptr = (ulong)mmap(IntPtr.Zero, Z.UU(size), MemoryProtection.None, 0x22 /* MAP_PRIVATE | MAP_ANON */, -1, IntPtr.Zero);
if (ptr == ulong.MaxValue)
throw new InvalidOperationException($"{nameof(mmap)}() failed with error {Marshal.GetLastWin32Error()}");
_size = size;
@@ -43,24 +43,19 @@ public void Dispose()
private static MemoryProtection ToMemoryProtection(Protection prot)
{
- switch (prot)
+ return prot switch
{
- case Protection.None:
- return MemoryProtection.None;
- case Protection.R:
- return MemoryProtection.Read;
- case Protection.RW:
- return MemoryProtection.Read | MemoryProtection.Write;
- case Protection.RX:
- return MemoryProtection.Read | MemoryProtection.Execute;
- default:
- throw new ArgumentOutOfRangeException(nameof(prot));
- }
+ Protection.None => MemoryProtection.None,
+ Protection.R => MemoryProtection.Read,
+ Protection.RW => MemoryProtection.Read | MemoryProtection.Write,
+ Protection.RX => MemoryProtection.Read | MemoryProtection.Execute,
+ _ => throw new ArgumentOutOfRangeException(nameof(prot)),
+ };
}
public void Protect(ulong start, ulong size, Protection prot)
{
- var errorCode = mprotect(
+ int errorCode = mprotect(
Z.US(start),
Z.UU(size),
ToMemoryProtection(prot)
diff --git a/src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs b/src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs
index bc6774b85f3..ce1b3677e30 100644
--- a/src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs
+++ b/src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs
@@ -12,7 +12,7 @@ internal sealed unsafe class MemoryBlockWindowsPal : IMemoryBlockPal
public MemoryBlockWindowsPal(ulong size)
{
- var ptr = (ulong)Kernel32.VirtualAlloc(
+ ulong ptr = (ulong)Kernel32.VirtualAlloc(
UIntPtr.Zero, Z.UU(size), Kernel32.AllocationType.MEM_RESERVE | Kernel32.AllocationType.MEM_COMMIT, Kernel32.MemoryProtection.NOACCESS);
if (ptr == 0)
throw new InvalidOperationException($"{nameof(Kernel32.VirtualAlloc)}() returned NULL");
@@ -28,15 +28,14 @@ public void Protect(ulong start, ulong size, Protection prot)
private static Kernel32.MemoryProtection GetKernelMemoryProtectionValue(Protection prot)
{
- Kernel32.MemoryProtection p;
- switch (prot)
+ var p = prot switch
{
- case Protection.None: p = Kernel32.MemoryProtection.NOACCESS; break;
- case Protection.R: p = Kernel32.MemoryProtection.READONLY; break;
- case Protection.RW: p = Kernel32.MemoryProtection.READWRITE; break;
- case Protection.RX: p = Kernel32.MemoryProtection.EXECUTE_READ; break;
- default: throw new ArgumentOutOfRangeException(nameof(prot));
- }
+ Protection.None => Kernel32.MemoryProtection.NOACCESS,
+ Protection.R => Kernel32.MemoryProtection.READONLY,
+ Protection.RW => Kernel32.MemoryProtection.READWRITE,
+ Protection.RX => Kernel32.MemoryProtection.EXECUTE_READ,
+ _ => throw new ArgumentOutOfRangeException(nameof(prot)),
+ };
return p;
}
diff --git a/src/BizHawk.BizInvoke/MemoryViewStream.cs b/src/BizHawk.BizInvoke/MemoryViewStream.cs
index cc5559d58eb..2183fa9457e 100644
--- a/src/BizHawk.BizInvoke/MemoryViewStream.cs
+++ b/src/BizHawk.BizInvoke/MemoryViewStream.cs
@@ -57,22 +57,19 @@ public int Read(Span buffer)
if (!_readable)
throw new IOException();
EnsureNotDisposed();
- var count = (int)Math.Min(buffer.Length, _length - _pos);
+ int count = (int)Math.Min(buffer.Length, _length - _pos);
new ReadOnlySpan(CurrentPointer(), count).CopyTo(buffer);
_pos += count;
return count;
}
- public override int Read(byte[] buffer, int offset, int count)
- {
- return Read(new Span(buffer, offset, count));
- }
+ public override int Read(byte[] buffer, int offset, int count) => Read(new Span(buffer, offset, count));
public override int ReadByte()
{
if (_pos < _length)
{
- var ret = *CurrentPointer();
+ byte ret = *CurrentPointer();
_pos++;
return ret;
}
@@ -84,28 +81,17 @@ public override int ReadByte()
public override long Seek(long offset, SeekOrigin origin)
{
- long newpos;
- switch (origin)
+ long newpos = origin switch
{
- default:
- case SeekOrigin.Begin:
- newpos = offset;
- break;
- case SeekOrigin.Current:
- newpos = _pos + offset;
- break;
- case SeekOrigin.End:
- newpos = _length + offset;
- break;
- }
+ SeekOrigin.Current => _pos + offset,
+ SeekOrigin.End => _length + offset,
+ _ => offset,
+ };
Position = newpos;
return newpos;
}
- public override void SetLength(long value)
- {
- throw new IOException();
- }
+ public override void SetLength(long value) => throw new IOException();
public void Write(ReadOnlySpan buffer)
{
@@ -118,10 +104,7 @@ public void Write(ReadOnlySpan buffer)
_pos += buffer.Length;
}
- public override void Write(byte[] buffer, int offset, int count)
- {
- Write(new ReadOnlySpan(buffer, offset, count));
- }
+ public override void Write(byte[] buffer, int offset, int count) => Write(new ReadOnlySpan(buffer, offset, count));
public override void WriteByte(byte value)
{
diff --git a/src/BizHawk.BizInvoke/WaterboxUtils.cs b/src/BizHawk.BizInvoke/WaterboxUtils.cs
index a0c2c11f835..9a1d8bc5afa 100644
--- a/src/BizHawk.BizInvoke/WaterboxUtils.cs
+++ b/src/BizHawk.BizInvoke/WaterboxUtils.cs
@@ -10,7 +10,7 @@ public static class WaterboxUtils
///
public static void CopySome(Stream src, Stream dst, long len)
{
- var buff = new byte[65536];
+ byte[] buff = new byte[65536];
while (len > 0)
{
int r = src.Read(buff, 0, (int)Math.Min(len, 65536));
@@ -31,10 +31,7 @@ public static unsafe void ZeroMemory(IntPtr mem, long length)
}
}
- public static long Timestamp()
- {
- return DateTime.UtcNow.Ticks;
- }
+ public static long Timestamp() => DateTime.UtcNow.Ticks;
///
/// system page size
@@ -62,34 +59,22 @@ static WaterboxUtils()
///
/// true if addr is aligned
///
- public static bool Aligned(ulong addr)
- {
- return (addr & PageMask) == 0;
- }
+ public static bool Aligned(ulong addr) => (addr & PageMask) == 0;
///
/// align address down to previous page boundary
///
- public static ulong AlignDown(ulong addr)
- {
- return addr & ~PageMask;
- }
+ public static ulong AlignDown(ulong addr) => addr & ~PageMask;
///
/// align address up to next page boundary
///
- public static ulong AlignUp(ulong addr)
- {
- return ((addr - 1) | PageMask) + 1;
- }
+ public static ulong AlignUp(ulong addr) => ((addr - 1) | PageMask) + 1;
///
/// return the minimum number of pages needed to hold size
///
- public static int PagesNeeded(ulong size)
- {
- return (int)((size + PageMask) >> PageShift);
- }
+ public static int PagesNeeded(ulong size) => (int)((size + PageMask) >> PageShift);
}
// C# is annoying: arithmetic operators for native ints are not exposed.
diff --git a/src/BizHawk.Bizware.Audio/DirectSoundSoundOutput.cs b/src/BizHawk.Bizware.Audio/DirectSoundSoundOutput.cs
index 7a42a29f5de..b555c577d96 100644
--- a/src/BizHawk.Bizware.Audio/DirectSoundSoundOutput.cs
+++ b/src/BizHawk.Bizware.Audio/DirectSoundSoundOutput.cs
@@ -44,10 +44,7 @@ public void Dispose()
_disposed = true;
}
- public static IEnumerable GetDeviceNames()
- {
- return DirectSound.GetDevices().Select(d => d.Description);
- }
+ public static IEnumerable GetDeviceNames() => DirectSound.GetDevices().Select(d => d.Description);
private int BufferSizeSamples { get; set; }
@@ -65,7 +62,7 @@ private void StartPlaying()
_filledBufferSizeBytes = 0;
_lastWriteTime = 0;
_lastWriteCursor = 0;
- var attempts = _retryCounter;
+ int attempts = _retryCounter;
while (!IsPlaying && attempts > 0)
{
attempts--;
@@ -73,7 +70,7 @@ private void StartPlaying()
{
if (_deviceBuffer == null)
{
- var format = WaveFormat.CreateCustomFormat(
+ WaveFormat format = WaveFormat.CreateCustomFormat(
tag: WaveFormatEncoding.Pcm,
sampleRate: _sound.SampleRate,
channels: _sound.ChannelCount,
@@ -81,7 +78,7 @@ private void StartPlaying()
blockAlign: _sound.BlockAlign,
bitsPerSample: _sound.BytesPerSample * 8);
- var desc = new SoundBufferDescription
+ SoundBufferDescription desc = new()
{
Format = format,
Flags =
@@ -143,7 +140,7 @@ public void StartSound()
// severe glitches. At least on my Windows 8 machines, the distance between the
// play and write cursors can be up to 30 milliseconds, so that would be the
// absolute minimum we could use here.
- var minBufferFullnessMs = Math.Min(35 + (_sound.ConfigBufferSizeMs - 60) / 2, 65);
+ int minBufferFullnessMs = Math.Min(35 + (_sound.ConfigBufferSizeMs - 60) / 2, 65);
MaxSamplesDeficit = BufferSizeSamples - _sound.MillisecondsToSamples(minBufferFullnessMs);
StartPlaying();
@@ -169,20 +166,20 @@ public void StopSound()
public int CalculateSamplesNeeded()
{
- var samplesNeeded = 0;
+ int samplesNeeded = 0;
if (IsPlaying)
{
try
{
- var currentWriteTime = Stopwatch.GetTimestamp();
- _deviceBuffer.GetCurrentPosition(out var playCursor, out var writeCursor);
- var isInitializing = _actualWriteOffsetBytes == -1;
- var detectedUnderrun = false;
+ long currentWriteTime = Stopwatch.GetTimestamp();
+ _deviceBuffer.GetCurrentPosition(out int playCursor, out int writeCursor);
+ bool isInitializing = _actualWriteOffsetBytes == -1;
+ bool detectedUnderrun = false;
if (!isInitializing)
{
- var elapsedSeconds = (currentWriteTime - _lastWriteTime) / (double)Stopwatch.Frequency;
- var bufferSizeSeconds = (double) BufferSizeSamples / _sound.SampleRate;
- var cursorDelta = CircularDistance(_lastWriteCursor, writeCursor, BufferSizeBytes);
+ double elapsedSeconds = (currentWriteTime - _lastWriteTime) / (double)Stopwatch.Frequency;
+ double bufferSizeSeconds = (double) BufferSizeSamples / _sound.SampleRate;
+ int cursorDelta = CircularDistance(_lastWriteCursor, writeCursor, BufferSizeBytes);
cursorDelta += BufferSizeBytes * (int) Math.Round((elapsedSeconds - (cursorDelta / (double) (_sound.SampleRate * _sound.BlockAlign))) / bufferSizeSeconds);
_filledBufferSizeBytes -= cursorDelta;
detectedUnderrun = _filledBufferSizeBytes < 0;
@@ -208,10 +205,7 @@ public int CalculateSamplesNeeded()
return samplesNeeded;
}
- private static int CircularDistance(int start, int end, int size)
- {
- return (end - start + size) % size;
- }
+ private static int CircularDistance(int start, int end, int size) => (end - start + size) % size;
public void WriteSamples(short[] samples, int sampleOffset, int sampleCount)
{
diff --git a/src/BizHawk.Bizware.Audio/OpenALSoundOutput.cs b/src/BizHawk.Bizware.Audio/OpenALSoundOutput.cs
index fc9eff3af3b..cf08b65f09a 100644
--- a/src/BizHawk.Bizware.Audio/OpenALSoundOutput.cs
+++ b/src/BizHawk.Bizware.Audio/OpenALSoundOutput.cs
@@ -58,10 +58,7 @@ public static IEnumerable GetDeviceNames()
public int MaxSamplesDeficit { get; private set; }
- public void ApplyVolumeSettings(double volume)
- {
- _al.SetSourceProperty(_sourceID, SourceFloat.Gain, (float)volume);
- }
+ public void ApplyVolumeSettings(double volume) => _al.SetSourceProperty(_sourceID, SourceFloat.Gain, (float)volume);
public void StartSound()
{
@@ -87,18 +84,18 @@ public void StopSound()
public int CalculateSamplesNeeded()
{
- var currentSamplesPlayed = GetSource(GetSourceInteger.SampleOffset);
+ int currentSamplesPlayed = GetSource(GetSourceInteger.SampleOffset);
var sourceState = GetSourceState();
- var isInitializing = sourceState == SourceState.Initial;
- var detectedUnderrun = sourceState == SourceState.Stopped;
+ bool isInitializing = sourceState == SourceState.Initial;
+ bool detectedUnderrun = sourceState == SourceState.Stopped;
if (detectedUnderrun)
{
// SampleOffset should reset to 0 when stopped; update the queued sample count to match
UnqueueProcessedBuffers();
currentSamplesPlayed = 0;
}
- var samplesAwaitingPlayback = _currentSamplesQueued - currentSamplesPlayed;
- var samplesNeeded = Math.Max(BufferSizeSamples - samplesAwaitingPlayback, 0);
+ int samplesAwaitingPlayback = _currentSamplesQueued - currentSamplesPlayed;
+ int samplesNeeded = Math.Max(BufferSizeSamples - samplesAwaitingPlayback, 0);
if (isInitializing || detectedUnderrun)
{
_sound.HandleInitializationOrUnderrun(detectedUnderrun, ref samplesNeeded);
@@ -110,7 +107,7 @@ public unsafe void WriteSamples(short[] samples, int sampleOffset, int sampleCou
{
if (sampleCount == 0) return;
UnqueueProcessedBuffers();
- var byteCount = sampleCount * _sound.BlockAlign;
+ int byteCount = sampleCount * _sound.BlockAlign;
if (sampleOffset != 0)
{
AllocateTempSampleBuffer(sampleCount);
@@ -123,7 +120,7 @@ public unsafe void WriteSamples(short[] samples, int sampleOffset, int sampleCou
{
_al.BufferData(buffer.BufferID, BufferFormat.Stereo16, sptr, byteCount, _sound.SampleRate);
}
- var bid = buffer.BufferID;
+ uint bid = buffer.BufferID;
_al.SourceQueueBuffers(_sourceID, 1, &bid);
_currentSamplesQueued += sampleCount;
if (GetSourceState() != SourceState.Playing)
@@ -134,10 +131,10 @@ public unsafe void WriteSamples(short[] samples, int sampleOffset, int sampleCou
private unsafe void UnqueueProcessedBuffers()
{
- var releaseCount = GetSource(GetSourceInteger.BuffersProcessed);
- var bids = stackalloc uint[releaseCount];
+ int releaseCount = GetSource(GetSourceInteger.BuffersProcessed);
+ uint* bids = stackalloc uint[releaseCount];
_al.SourceUnqueueBuffers(_sourceID, releaseCount, bids);
- for (var i = 0; i < releaseCount; i++)
+ for (int i = 0; i < releaseCount; i++)
{
var releasedBuffer = _bufferPool.ReleaseOne();
_currentSamplesQueued -= releasedBuffer.Length / _sound.BlockAlign;
@@ -146,7 +143,7 @@ private unsafe void UnqueueProcessedBuffers()
private int GetSource(GetSourceInteger param)
{
- _al.GetSourceProperty(_sourceID, param, out var value);
+ _al.GetSourceProperty(_sourceID, param, out int value);
return value;
}
@@ -155,7 +152,7 @@ private SourceState GetSourceState()
private void AllocateTempSampleBuffer(int sampleCount)
{
- var length = sampleCount * _sound.ChannelCount;
+ int length = sampleCount * _sound.ChannelCount;
if (_tempSampleBuffer == null || _tempSampleBuffer.Length < length)
{
_tempSampleBuffer = new short[length];
diff --git a/src/BizHawk.Bizware.Audio/XAudio2SoundOutput.cs b/src/BizHawk.Bizware.Audio/XAudio2SoundOutput.cs
index caf89ffc932..fc4cb3430db 100644
--- a/src/BizHawk.Bizware.Audio/XAudio2SoundOutput.cs
+++ b/src/BizHawk.Bizware.Audio/XAudio2SoundOutput.cs
@@ -27,7 +27,7 @@ private static string GetDeviceId(string deviceName)
return null;
}
- using var enumerator = new IMMDeviceEnumerator();
+ using IMMDeviceEnumerator enumerator = new();
var devices = enumerator.EnumAudioEndpoints(DataFlow.Render);
var device = devices.FirstOrDefault(capDevice => capDevice.FriendlyName == deviceName);
if (device is null)
@@ -62,7 +62,7 @@ public void Dispose()
public static IEnumerable GetDeviceNames()
{
- using var enumerator = new IMMDeviceEnumerator();
+ using IMMDeviceEnumerator enumerator = new();
var devices = enumerator.EnumAudioEndpoints(DataFlow.Render);
return devices.Select(capDevice => capDevice.FriendlyName);
}
@@ -71,17 +71,14 @@ public static IEnumerable GetDeviceNames()
public int MaxSamplesDeficit { get; private set; }
- public void ApplyVolumeSettings(double volume)
- {
- _sourceVoice.Volume = (float)volume;
- }
+ public void ApplyVolumeSettings(double volume) => _sourceVoice.Volume = (float)volume;
public void StartSound()
{
BufferSizeSamples = _sound.MillisecondsToSamples(_sound.ConfigBufferSizeMs);
MaxSamplesDeficit = BufferSizeSamples;
- var format = new WaveFormat(_sound.SampleRate, _sound.BytesPerSample * 8, _sound.ChannelCount);
+ WaveFormat format = new(_sound.SampleRate, _sound.BytesPerSample * 8, _sound.ChannelCount);
_sourceVoice = _device.CreateSourceVoice(format);
_bufferPool = new();
@@ -104,10 +101,10 @@ public void StopSound()
public int CalculateSamplesNeeded()
{
- var isInitializing = _runningSamplesQueued == 0;
- var detectedUnderrun = !isInitializing && _sourceVoice.State.BuffersQueued == 0;
- var samplesAwaitingPlayback = _runningSamplesQueued - (long)_sourceVoice.State.SamplesPlayed;
- var samplesNeeded = (int)Math.Max(BufferSizeSamples - samplesAwaitingPlayback, 0);
+ bool isInitializing = _runningSamplesQueued == 0;
+ bool detectedUnderrun = !isInitializing && _sourceVoice.State.BuffersQueued == 0;
+ long samplesAwaitingPlayback = _runningSamplesQueued - (long)_sourceVoice.State.SamplesPlayed;
+ int samplesNeeded = (int)Math.Max(BufferSizeSamples - samplesAwaitingPlayback, 0);
if (isInitializing || detectedUnderrun)
{
_sound.HandleInitializationOrUnderrun(detectedUnderrun, ref samplesNeeded);
@@ -119,7 +116,7 @@ public void WriteSamples(short[] samples, int sampleOffset, int sampleCount)
{
if (sampleCount == 0) return;
_bufferPool.Release(_sourceVoice.State.BuffersQueued);
- var byteCount = sampleCount * _sound.BlockAlign;
+ int byteCount = sampleCount * _sound.BlockAlign;
var item = _bufferPool.Obtain(byteCount);
samples.AsSpan(sampleOffset * _sound.BlockAlign / 2, byteCount / 2)
.CopyTo(item.AudioBuffer.AsSpan());
@@ -152,8 +149,8 @@ public BufferPoolItem Obtain(int length)
private BufferPoolItem GetAvailableItem(int length)
{
- var foundIndex = -1;
- for (var i = 0; i < _availableItems.Count; i++)
+ int foundIndex = -1;
+ for (int i = 0; i < _availableItems.Count; i++)
{
if (_availableItems[i].MaxLength >= length && (foundIndex == -1 || _availableItems[i].MaxLength < _availableItems[foundIndex].MaxLength))
foundIndex = i;
diff --git a/src/BizHawk.Bizware.BizwareGL/ArtManager.cs b/src/BizHawk.Bizware.BizwareGL/ArtManager.cs
index 2fee78e871f..503b6bde371 100644
--- a/src/BizHawk.Bizware.BizwareGL/ArtManager.cs
+++ b/src/BizHawk.Bizware.BizwareGL/ArtManager.cs
@@ -39,17 +39,14 @@ public void Open()
///
/// Loads the given stream as an Art instance
///
- public Art LoadArt(Stream stream)
- {
- return LoadArtInternal(new BitmapBuffer(stream, new BitmapLoadOptions()));
- }
+ public Art LoadArt(Stream stream) => LoadArtInternal(new BitmapBuffer(stream, new BitmapLoadOptions()));
///
/// Loads the given path as an Art instance.
///
public Art LoadArt(string path)
{
- using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read);
return LoadArtInternal(new BitmapBuffer(path, new BitmapLoadOptions()));
}
@@ -57,7 +54,7 @@ private Art LoadArtInternal(BitmapBuffer tex)
{
AssertIsOpen(true);
- var a = new Art(this);
+ Art a = new(this);
ArtLooseTextureAssociation.Add((a, tex));
ManagedArts.Add(a);
@@ -84,7 +81,7 @@ public void Close(bool forever = true)
// prepare input for atlas process and perform atlas
// add 2 extra pixels for padding on all sides
- var atlasItems = ArtLooseTextureAssociation
+ List atlasItems = ArtLooseTextureAssociation
.Select(kvp => new TexAtlas.RectItem(kvp.Bitmap.Width + 2, kvp.Bitmap.Height + 2, kvp))
.ToList();
var results = TexAtlas.PackAtlas(atlasItems);
@@ -94,28 +91,28 @@ public void Close(bool forever = true)
throw new InvalidOperationException("Art files too big for atlas");
// prepare the output buffer
- var bmpResult = new BitmapBuffer(results[0].Size);
+ BitmapBuffer bmpResult = new(results[0].Size);
//for each item, copy it into the output buffer and set the tex parameters on them
- for (var i = 0; i < atlasItems.Count; i++)
+ for (int i = 0; i < atlasItems.Count; i++)
{
var item = results[0].Items[i];
var (art, bitmap) = ((Art, BitmapBuffer)) item.Item;
- var w = bitmap.Width;
- var h = bitmap.Height;
- var dx = item.X + 1;
- var dy = item.Y + 1;
- for (var y = 0; y < h; y++)
+ int w = bitmap.Width;
+ int h = bitmap.Height;
+ int dx = item.X + 1;
+ int dy = item.Y + 1;
+ for (int y = 0; y < h; y++)
{
- for (var x = 0; x < w; x++)
+ for (int x = 0; x < w; x++)
{
- var pixel = bitmap.GetPixel(x, y);
+ int pixel = bitmap.GetPixel(x, y);
bmpResult.SetPixel(x+dx,y+dy,pixel);
}
}
- var myDestWidth = (float)bmpResult.Width;
- var myDestHeight = (float)bmpResult.Height;
+ float myDestWidth = bmpResult.Width;
+ float myDestHeight = bmpResult.Height;
art.u0 = dx / myDestWidth;
art.v0 = dy / myDestHeight;
diff --git a/src/BizHawk.Bizware.BizwareGL/BitmapBuffer.cs b/src/BizHawk.Bizware.BizwareGL/BitmapBuffer.cs
index 7e03c06cde8..956543b4cf1 100644
--- a/src/BizHawk.Bizware.BizwareGL/BitmapBuffer.cs
+++ b/src/BizHawk.Bizware.BizwareGL/BitmapBuffer.cs
@@ -83,13 +83,13 @@ public void YFlip()
{
// TODO - could be faster
var bmpdata = LockBits();
- var newPixels = new int[Width * Height];
- var s = (int*)bmpdata.Scan0.ToPointer();
+ int[] newPixels = new int[Width * Height];
+ int* s = (int*)bmpdata.Scan0.ToPointer();
fixed (int* d = newPixels)
{
for (int y = 0, si = 0, di = (Height - 1) * Width; y < Height; y++)
{
- for (var x = 0; x < Width; x++, si++, di++)
+ for (int x = 0; x < Width; x++, si++, di++)
{
d[di] = s[si];
}
@@ -108,15 +108,15 @@ public void YFlip()
public void Normalize(bool yflip)
{
var bmpdata = LockBits();
- var newPixels = new int[Width * Height];
- var s = (int*)bmpdata.Scan0.ToPointer();
+ int[] newPixels = new int[Width * Height];
+ int* s = (int*)bmpdata.Scan0.ToPointer();
fixed (int* d = newPixels)
{
if (yflip)
{
for (int y = 0, si = 0, di = (Height - 1) * Width; y < Height; y++)
{
- for (var x = 0; x < Width; x++, si++, di++)
+ for (int x = 0; x < Width; x++, si++, di++)
{
d[di] = s[si] | unchecked((int)0xFF000000);
}
@@ -127,7 +127,7 @@ public void Normalize(bool yflip)
{
for (int y = 0, i=0; y < Height; y++)
{
- for (var x = 0; x < Width; x++, i++)
+ for (int x = 0; x < Width; x++, i++)
{
d[i] = s[i] | unchecked((int)0xFF000000);
}
@@ -140,19 +140,13 @@ public void Normalize(bool yflip)
Pixels = newPixels;
}
- public int GetPixel(int x, int y)
- {
- return Pixels[Width * y + x];
- }
+ public int GetPixel(int x, int y) => Pixels[Width * y + x];
- public void SetPixel(int x, int y, int value)
- {
- Pixels[Width * y + x] = value;
- }
+ public void SetPixel(int x, int y, int value) => Pixels[Width * y + x] = value;
public Color GetPixelAsColor(int x, int y)
{
- var c = Pixels[Width * y + x];
+ int c = Pixels[Width * y + x];
return Color.FromArgb(c);
}
@@ -163,7 +157,7 @@ public void Alphafy(int tcol)
{
for (int y = 0, idx = 0; y < Height; y++)
{
- for (var x = 0; x < Width; x++, idx++)
+ for (int x = 0; x < Width; x++, idx++)
{
if (Pixels[idx] == tcol)
{
@@ -176,26 +170,23 @@ public void Alphafy(int tcol)
///
/// copies this bitmap and trims out transparent pixels, returning the offset to the topleft pixel
///
- public BitmapBuffer Trim()
- {
- return Trim(out _, out _);
- }
+ public BitmapBuffer Trim() => Trim(out _, out _);
///
/// copies this bitmap and trims out transparent pixels, returning the offset to the topleft pixel
///
public BitmapBuffer Trim(out int xofs, out int yofs)
{
- var minx = int.MaxValue;
- var maxx = int.MinValue;
- var miny = int.MaxValue;
- var maxy = int.MinValue;
- for (var y = 0; y < Height; y++)
+ int minx = int.MaxValue;
+ int maxx = int.MinValue;
+ int miny = int.MaxValue;
+ int maxy = int.MinValue;
+ for (int y = 0; y < Height; y++)
{
- for (var x = 0; x < Width; x++)
+ for (int x = 0; x < Width; x++)
{
- var pixel = GetPixel(x, y);
- var a = (pixel >> 24) & 0xFF;
+ int pixel = GetPixel(x, y);
+ int a = (pixel >> 24) & 0xFF;
if (a != 0)
{
minx = Math.Min(minx, x);
@@ -212,12 +203,12 @@ public BitmapBuffer Trim(out int xofs, out int yofs)
return new(0, 0);
}
- var w = maxx - minx + 1;
- var h = maxy - miny + 1;
- var bbRet = new BitmapBuffer(w, h);
- for (var y = 0; y < h; y++)
+ int w = maxx - minx + 1;
+ int h = maxy - miny + 1;
+ BitmapBuffer bbRet = new(w, h);
+ for (int y = 0; y < h; y++)
{
- for (var x = 0; x < w; x++)
+ for (int x = 0; x < w; x++)
{
bbRet.SetPixel(x, y, GetPixel(x + minx, y + miny));
}
@@ -233,14 +224,14 @@ public BitmapBuffer Trim(out int xofs, out int yofs)
///
public void Pad()
{
- var widthRound = NextHigher(Width);
- var heightRound = NextHigher(Height);
+ int widthRound = NextHigher(Width);
+ int heightRound = NextHigher(Height);
if (widthRound == Width && heightRound == Height) return;
- var NewPixels = new int[heightRound * widthRound];
+ int[] NewPixels = new int[heightRound * widthRound];
for (int y = 0, sptr = 0, dptr = 0; y < Height; y++)
{
- for (var x = 0; x < Width; x++)
+ for (int x = 0; x < Width; x++)
{
NewPixels[dptr++] = Pixels[sptr++];
}
@@ -258,7 +249,7 @@ public void Pad()
///
public BitmapBuffer(string fname, BitmapLoadOptions options)
{
- using var fs = new FileStream(fname, FileMode.Open, FileAccess.Read, FileShare.Read);
+ using FileStream fs = new(fname, FileMode.Open, FileAccess.Read, FileShare.Read);
LoadInternal(fs, null, options);
}
@@ -301,15 +292,12 @@ public BitmapBuffer(int width, int height, int[] pixels)
/// Suggests that this BitmapBuffer is now XRGB instead of ARGB but doesn't actually change any of the pixels data.
/// Should affect how things get exported from here, though, I think
///
- public void DiscardAlpha()
- {
- HasAlpha = false;
- }
+ public void DiscardAlpha() => HasAlpha = false;
private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions options)
{
- var cleanup = options.CleanupAlpha0;
- var needsPad = true;
+ bool cleanup = options.CleanupAlpha0;
+ bool needsPad = true;
var colorKey24bpp = options.ColorKey24bpp;
using (var loadedBmp = bitmap == null ? new Bitmap(stream) : null) // sneaky!
@@ -319,19 +307,19 @@ private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions option
// if we have a 24bpp image and a colorkey callback, the callback can choose a colorkey color and we'll use that
if (bmp.PixelFormat == PixelFormat.Format24bppRgb && colorKey24bpp != null)
{
- var colorKey = colorKey24bpp(bmp);
- var w = bmp.Width;
- var h = bmp.Height;
+ int colorKey = colorKey24bpp(bmp);
+ int w = bmp.Width;
+ int h = bmp.Height;
InitSize(w, h);
var bmpdata = bmp.LockBits(new(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
- var ptr = (int*)bmpdata.Scan0.ToPointer();
+ int* ptr = (int*)bmpdata.Scan0.ToPointer();
fixed (int* pPtr = &Pixels[0])
{
for (int idx = 0, y = 0; y < h; y++)
{
- for (var x = 0; x < w; x++)
+ for (int x = 0; x < w; x++)
{
- var srcPixel = ptr[idx];
+ int srcPixel = ptr[idx];
if (srcPixel == colorKey)
{
srcPixel = 0;
@@ -346,22 +334,22 @@ private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions option
}
if (bmp.PixelFormat is PixelFormat.Format8bppIndexed or PixelFormat.Format4bppIndexed)
{
- var w = bmp.Width;
- var h = bmp.Height;
+ int w = bmp.Width;
+ int h = bmp.Height;
InitSize(w, h);
var bmpdata = bmp.LockBits(new(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
var palette = bmp.Palette.Entries;
- var ptr = (byte*)bmpdata.Scan0.ToPointer();
+ byte* ptr = (byte*)bmpdata.Scan0.ToPointer();
fixed (int* pPtr = &Pixels[0])
{
for (int idx = 0, y = 0; y < h; y++)
{
- for (var x = 0; x < w; x++)
+ for (int x = 0; x < w; x++)
{
int srcPixel = ptr[idx];
if (srcPixel != 0)
{
- var color = palette[srcPixel].ToArgb();
+ int color = palette[srcPixel].ToArgb();
// make transparent pixels turn into black to avoid filtering issues and other annoying issues with stray junk in transparent pixels.
// (yes, we can have palette entries with transparency in them (PNGs support this, annoyingly))
@@ -385,12 +373,12 @@ private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions option
else
{
// dump the supplied bitmap into our pixels array
- var width = bmp.Width;
- var height = bmp.Height;
+ int width = bmp.Width;
+ int height = bmp.Height;
InitSize(width, height);
var bmpdata = bmp.LockBits(new(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
- var ptr = (int*)bmpdata.Scan0;
- var stride = bmpdata.Stride / 4;
+ int* ptr = (int*)bmpdata.Scan0;
+ int stride = bmpdata.Stride / 4;
LoadFrom(width, stride, height, (byte*)ptr, options);
bmp.UnlockBits(bmpdata);
needsPad = false;
@@ -409,7 +397,7 @@ private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions option
///
public void LoadFrom(int width, int stride, int height, byte* data, BitmapLoadOptions options)
{
- var cleanup = options.CleanupAlpha0;
+ bool cleanup = options.CleanupAlpha0;
Width = width;
Height = height;
Pixels = new int[width * height];
@@ -417,10 +405,10 @@ public void LoadFrom(int width, int stride, int height, byte* data, BitmapLoadOp
{
for (int idx = 0, y = 0; y < Height; y++)
{
- for (var x = 0; x < Width; x++)
+ for (int x = 0; x < Width; x++)
{
- var src = y * stride + x;
- var srcVal = ((int*)data)[src];
+ int src = y * stride + x;
+ int srcVal = ((int*)data)[src];
// make transparent pixels turn into black to avoid filtering issues and other annoying issues with stray junk in transparent pixels
if (cleanup)
@@ -447,10 +435,10 @@ public void LoadFrom(int width, int stride, int height, byte* data, BitmapLoadOp
///
public static int PremultiplyColor(int srcVal)
{
- var b = (srcVal >> 0) & 0xFF;
- var g = (srcVal >> 8) & 0xFF;
- var r = (srcVal >> 16) & 0xFF;
- var a = (srcVal >> 24) & 0xFF;
+ int b = (srcVal >> 0) & 0xFF;
+ int g = (srcVal >> 8) & 0xFF;
+ int r = (srcVal >> 16) & 0xFF;
+ int a = (srcVal >> 24) & 0xFF;
r = (r * a) >> 8;
g = (g * a) >> 8;
b = (b * a) >> 8;
@@ -489,21 +477,21 @@ public void ClearWithoutAlloc()
// http://techmikael.blogspot.com/2009/12/filling-array-with-default-value.html
// this guy says its faster
- var size = Width * Height;
+ int size = Width * Height;
const byte fillValue = 0;
const ulong fillValueLong = 0;
fixed (int* ptr = &Pixels[0])
{
- var dest = (ulong*)ptr;
- var length = size;
+ ulong* dest = (ulong*)ptr;
+ int length = size;
while (length >= 8)
{
*dest = fillValueLong;
dest++;
length -= 8;
}
- var bDest = (byte*)dest;
+ byte* bDest = (byte*)dest;
for (byte i = 0; i < length; i++)
{
*bDest = fillValue;
@@ -525,12 +513,12 @@ private void InitSize(int width, int height)
private static int NextHigher(int k)
{
k--;
- for (var i = 1; i < 32; i <<= 1)
+ for (int i = 1; i < 32; i <<= 1)
{
k |= k >> i;
}
- var candidate = k + 1;
+ int candidate = k + 1;
return candidate;
}
@@ -546,7 +534,7 @@ public Bitmap ToSysdrawingBitmap()
}
var pf = HasAlpha ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb;
- var bmp = new Bitmap(Width, Height, pf);
+ Bitmap bmp = new(Width, Height, pf);
ToSysdrawingBitmap(bmp);
return bmp;
}
@@ -559,7 +547,7 @@ public void ToSysdrawingBitmap(Bitmap bmp)
{
if (WrappedBitmap != null)
{
- using var g = Graphics.FromImage(bmp);
+ using Graphics g = Graphics.FromImage(bmp);
g.CompositingMode = CompositingMode.SourceCopy;
g.CompositingQuality = CompositingQuality.HighSpeed;
g.DrawImageUnscaled(WrappedBitmap, 0, 0);
@@ -575,14 +563,14 @@ public void ToSysdrawingBitmap(Bitmap bmp)
}
else if (bmp.Width != 0 && bmp.Height != 0)
{
- var ptr = (int*)bmpdata.Scan0.ToPointer();
+ int* ptr = (int*)bmpdata.Scan0.ToPointer();
fixed (int* pPtr = &Pixels[0])
{
for (int idx = 0, y = 0; y < Height; y++)
{
- for (var x = 0; x < Width; x++)
+ for (int x = 0; x < Width; x++)
{
- var srcPixel = pPtr[idx];
+ int srcPixel = pPtr[idx];
ptr[idx] = srcPixel;
idx++;
}
diff --git a/src/BizHawk.Bizware.BizwareGL/Pipeline.cs b/src/BizHawk.Bizware.BizwareGL/Pipeline.cs
index 92c0ecd02fe..fd5782c332c 100644
--- a/src/BizHawk.Bizware.BizwareGL/Pipeline.cs
+++ b/src/BizHawk.Bizware.BizwareGL/Pipeline.cs
@@ -49,7 +49,7 @@ public UniformWorkingDictionary(Pipeline owner)
Owner = owner;
}
- private Pipeline Owner;
+ private readonly Pipeline Owner;
public new PipelineUniform this[string key]
{
#if true
@@ -80,9 +80,6 @@ public PipelineUniform TryGetUniform(string name)
public bool Available { get; }
public string Errors { get; set; }
- public void Dispose()
- {
- Owner.FreePipeline(this);
- }
+ public void Dispose() => Owner.FreePipeline(this);
}
}
\ No newline at end of file
diff --git a/src/BizHawk.Bizware.BizwareGL/PipelineUniform.cs b/src/BizHawk.Bizware.BizwareGL/PipelineUniform.cs
index fb2464d80ec..392cd25644d 100644
--- a/src/BizHawk.Bizware.BizwareGL/PipelineUniform.cs
+++ b/src/BizHawk.Bizware.BizwareGL/PipelineUniform.cs
@@ -15,10 +15,7 @@ internal PipelineUniform(Pipeline owner)
Owner = owner;
}
- internal void AddUniformInfo(UniformInfo ui)
- {
- _uniformInfos.Add(ui);
- }
+ internal void AddUniformInfo(UniformInfo ui) => _uniformInfos.Add(ui);
public IEnumerable UniformInfos => _uniformInfos;
@@ -40,45 +37,21 @@ public UniformInfo Sole
}
public Pipeline Owner { get; }
-
- public void Set(Matrix4x4 mat, bool transpose = false)
- {
- Owner?.Owner.SetPipelineUniformMatrix(this, mat, transpose);
- }
- public void Set(Vector4 vec)
- {
- Owner?.Owner.SetPipelineUniform(this, vec);
- }
+ public void Set(Matrix4x4 mat, bool transpose = false) => Owner?.Owner.SetPipelineUniformMatrix(this, mat, transpose);
- public void Set(Vector2 vec)
- {
- Owner?.Owner.SetPipelineUniform(this, vec);
- }
+ public void Set(Vector4 vec) => Owner?.Owner.SetPipelineUniform(this, vec);
- public void Set(float f)
- {
- Owner?.Owner.SetPipelineUniform(this, f);
- }
+ public void Set(Vector2 vec) => Owner?.Owner.SetPipelineUniform(this, vec);
- public void Set(Vector4[] vecs)
- {
- Owner?.Owner.SetPipelineUniform(this, vecs);
- }
+ public void Set(float f) => Owner?.Owner.SetPipelineUniform(this, f);
- public void Set(ref Matrix4x4 mat, bool transpose = false)
- {
- Owner?.Owner.SetPipelineUniformMatrix(this, ref mat, transpose);
- }
+ public void Set(Vector4[] vecs) => Owner?.Owner.SetPipelineUniform(this, vecs);
- public void Set(bool value)
- {
- Owner?.Owner.SetPipelineUniform(this, value);
- }
+ public void Set(ref Matrix4x4 mat, bool transpose = false) => Owner?.Owner.SetPipelineUniformMatrix(this, ref mat, transpose);
- public void Set(Texture2d tex)
- {
- Owner?.Owner.SetPipelineUniformSampler(this, tex);
- }
+ public void Set(bool value) => Owner?.Owner.SetPipelineUniform(this, value);
+
+ public void Set(Texture2d tex) => Owner?.Owner.SetPipelineUniformSampler(this, tex);
}
}
\ No newline at end of file
diff --git a/src/BizHawk.Bizware.BizwareGL/RenderTarget.cs b/src/BizHawk.Bizware.BizwareGL/RenderTarget.cs
index 8285cbbfb3a..430c346e7f7 100644
--- a/src/BizHawk.Bizware.BizwareGL/RenderTarget.cs
+++ b/src/BizHawk.Bizware.BizwareGL/RenderTarget.cs
@@ -11,28 +11,16 @@ public RenderTarget(IGL owner, object opaque, Texture2d tex)
Texture2d = tex;
}
- public override string ToString()
- {
- return $"GL RT: {Texture2d.Width}x{Texture2d.Height}";
- }
+ public override string ToString() => $"GL RT: {Texture2d.Width}x{Texture2d.Height}";
public object Opaque { get; }
public IGL Owner { get; }
public Texture2d Texture2d { get; }
- public void Unbind()
- {
- Owner.BindRenderTarget(null);
- }
+ public void Unbind() => Owner.BindRenderTarget(null);
- public void Bind()
- {
- Owner.BindRenderTarget(this);
- }
+ public void Bind() => Owner.BindRenderTarget(this);
- public void Dispose()
- {
- Owner.FreeRenderTarget(this);
- }
+ public void Dispose() => Owner.FreeRenderTarget(this);
}
}
\ No newline at end of file
diff --git a/src/BizHawk.Bizware.BizwareGL/RetroShader.cs b/src/BizHawk.Bizware.BizwareGL/RetroShader.cs
index 2eb7f3446fb..702e53b8ba5 100644
--- a/src/BizHawk.Bizware.BizwareGL/RetroShader.cs
+++ b/src/BizHawk.Bizware.BizwareGL/RetroShader.cs
@@ -21,8 +21,8 @@ public RetroShader(IGL owner, string source, bool debug = false)
VertexLayout.DefineVertexAttribute("tex", 2, 2, VertexAttribPointerType.Float, AttribUsage.Texcoord0, false, 40, 32);
VertexLayout.Close();
- var vsSource = $"#define VERTEX\r\n{source}";
- var psSource = $"#define FRAGMENT\r\n{source}";
+ string vsSource = $"#define VERTEX\r\n{source}";
+ string psSource = $"#define FRAGMENT\r\n{source}";
var vs = owner.CreateVertexShader(vsSource, "main_vertex", debug);
var ps = owner.CreateFragmentShader(psSource, "main_fragment", debug);
Pipeline = Owner.CreatePipeline(VertexLayout, vs, ps, debug, "retro");
@@ -65,11 +65,9 @@ public void Dispose()
VertexLayout.Release();
}
- public void Bind()
- {
+ public void Bind() =>
// lame...
Owner.BindPipeline(Pipeline);
- }
public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip)
{
@@ -84,7 +82,7 @@ public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip
var Projection = Owner.CreateGuiProjectionMatrix(OutputSize);
var Modelview = Owner.CreateGuiViewMatrix(OutputSize);
- var mat = Matrix4x4.Transpose(Modelview * Projection);
+ Matrix4x4 mat = Matrix4x4.Transpose(Modelview * Projection);
Pipeline["modelViewProj"].Set(mat, true);
Owner.SetTextureWrapMode(tex, true);
@@ -92,11 +90,11 @@ public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip
sampler0.Set(tex);
Owner.SetViewport(OutputSize);
- var time = DateTime.Now.Second + (float)DateTime.Now.Millisecond / 1000;
+ float time = DateTime.Now.Second + (float)DateTime.Now.Millisecond / 1000;
Pipeline["Time"].Set(time);
- var w = OutputSize.Width;
- var h = OutputSize.Height;
+ int w = OutputSize.Width;
+ int h = OutputSize.Height;
float v0, v1;
if (flip)
@@ -110,8 +108,8 @@ public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip
v1 = 1;
}
- var pData = stackalloc float[10 * 4];
- var i = 0;
+ float* pData = stackalloc float[10 * 4];
+ int i = 0;
pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 1; //topleft vert
pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; //useless color
pData[i++] = 0; pData[i++] = v0;
diff --git a/src/BizHawk.Bizware.BizwareGL/Shader.cs b/src/BizHawk.Bizware.BizwareGL/Shader.cs
index 5e8b7ff587e..773bd2719f4 100644
--- a/src/BizHawk.Bizware.BizwareGL/Shader.cs
+++ b/src/BizHawk.Bizware.BizwareGL/Shader.cs
@@ -32,10 +32,7 @@ public void Release()
}
}
- public void AddRef()
- {
- RefCount++;
- }
+ public void AddRef() => RefCount++;
}
}
\ No newline at end of file
diff --git a/src/BizHawk.Bizware.BizwareGL/StringRenderer.cs b/src/BizHawk.Bizware.BizwareGL/StringRenderer.cs
index 21f423b0edf..47ae2d17e20 100644
--- a/src/BizHawk.Bizware.BizwareGL/StringRenderer.cs
+++ b/src/BizHawk.Bizware.BizwareGL/StringRenderer.cs
@@ -19,7 +19,7 @@ public StringRenderer(IGL owner, Stream xml, params Stream[] textures)
FontInfo.LoadXml(xml);
// load textures
- for (var i=0; i nodes = new List();
+ public readonly RectangleBinPack rbp = new();
+ public readonly List nodes = new();
}
public const int MaxSizeBits = 16;
@@ -50,14 +50,14 @@ static void AddAtlas(ICollection<(Size, List)> atlases, IEnumerable();
- for (var i = 3; i <= MaxSizeBits; i++)
+ List todoSizes = new();
+ for (int i = 3; i <= MaxSizeBits; i++)
{
- for (var j = 3; j <= MaxSizeBits; j++)
+ for (int j = 3; j <= MaxSizeBits; j++)
{
- var w = 1 << i;
- var h = 1 << j;
- var tfp = new TryFitParam(w, h);
+ int w = 1 << i;
+ int h = 1 << j;
+ TryFitParam tfp = new(w, h);
todoSizes.Add(tfp);
}
}
@@ -65,7 +65,7 @@ static void AddAtlas(ICollection<(Size, List)> atlases, IEnumerable
{
- var rbp = new RectangleBinPack();
+ RectangleBinPack rbp = new();
rbp.Init(16384, 16384);
param.rbp.Init(param.w, param.h);
@@ -86,7 +86,7 @@ static void AddAtlas(ICollection<(Size, List)> atlases, IEnumerable)> atlases, IEnumerable best)
{
continue; // larger than best, not interested
@@ -185,19 +185,18 @@ public void Init(int width, int height)
/// Inserts a new rectangle of the given size into the bin.
/// A pointer to the node that stores the newly added rectangle, or 0 if it didn't fit.
/// Running time is linear to the number of rectangles that have been already packed.
- public Node Insert(int width, int height)
- {
- return Insert(root, width, height);
- }
+ public Node Insert(int width, int height) => Insert(root, width, height);
+#pragma warning disable IDE0051
/// Computes the ratio of used surface area.
private float Occupancy()
{
- var totalSurfaceArea = binWidth * binHeight;
- var usedSurfaceArea = UsedSurfaceArea(root);
+ int totalSurfaceArea = binWidth * binHeight;
+ int usedSurfaceArea = UsedSurfaceArea(root);
return (float)usedSurfaceArea / totalSurfaceArea;
}
+ #pragma warning restore IDE0051
private Node root;
@@ -210,7 +209,7 @@ private static int UsedSurfaceArea(Node node)
{
if (node.left != null || node.right != null)
{
- var usedSurfaceArea = node.width * node.height;
+ int usedSurfaceArea = node.width * node.height;
if (node.left != null)
usedSurfaceArea += UsedSurfaceArea(node.left);
if (node.right != null)
@@ -253,8 +252,8 @@ private static Node Insert(Node node, int width, int height)
// The new cell will fit, split the remaining space along the shorter axis,
// that is probably more optimal.
- var w = node.width - width;
- var h = node.height - height;
+ int w = node.width - width;
+ int h = node.height - height;
node.left = new();
node.right = new();
if (w <= h) // Split the remaining space in horizontal direction.
diff --git a/src/BizHawk.Bizware.BizwareGL/Texture2d.cs b/src/BizHawk.Bizware.BizwareGL/Texture2d.cs
index 3040ce0a109..94902282832 100644
--- a/src/BizHawk.Bizware.BizwareGL/Texture2d.cs
+++ b/src/BizHawk.Bizware.BizwareGL/Texture2d.cs
@@ -12,10 +12,7 @@ public class Texture2d : IDisposable
///
/// resolves the texture into a new BitmapBuffer
///
- public BitmapBuffer Resolve()
- {
- return Owner.ResolveTexture2d(this);
- }
+ public BitmapBuffer Resolve() => Owner.ResolveTexture2d(this);
public void Dispose()
{
@@ -31,10 +28,7 @@ public Texture2d(IGL owner, object opaque, int width, int height)
Height = height;
}
- public override string ToString()
- {
- return $"GL Tex: {Width}x{Height}";
- }
+ public override string ToString() => $"GL Tex: {Width}x{Height}";
public void LoadFrom(BitmapBuffer buffer)
{
diff --git a/src/BizHawk.Bizware.BizwareGL/VertexLayout.cs b/src/BizHawk.Bizware.BizwareGL/VertexLayout.cs
index 6da0e46d3b2..f4aa93e7082 100644
--- a/src/BizHawk.Bizware.BizwareGL/VertexLayout.cs
+++ b/src/BizHawk.Bizware.BizwareGL/VertexLayout.cs
@@ -31,10 +31,7 @@ public void Release()
}
}
- public void AddRef()
- {
- RefCount++;
- }
+ public void AddRef() => RefCount++;
/// already closed (by call to )
public void DefineVertexAttribute(string name, int index, int components, VertexAttribPointerType attribType, AttribUsage usage, bool normalized, int stride, int offset = 0)
@@ -50,10 +47,7 @@ public void DefineVertexAttribute(string name, int index, int components, Vertex
///
/// finishes this VertexLayout and renders it immutable
///
- public void Close()
- {
- Closed = true;
- }
+ public void Close() => Closed = true;
public class LayoutItem
{
diff --git a/src/BizHawk.Bizware.Graphics.Controls/Controls/OpenGLControl.cs b/src/BizHawk.Bizware.Graphics.Controls/Controls/OpenGLControl.cs
index 3edc4984909..e11b4b1bda4 100644
--- a/src/BizHawk.Bizware.Graphics.Controls/Controls/OpenGLControl.cs
+++ b/src/BizHawk.Bizware.Graphics.Controls/Controls/OpenGLControl.cs
@@ -74,15 +74,9 @@ public override void SetVsync(bool state)
Context.SetVsync(state);
}
- public override void Begin()
- {
- MakeContextCurrent();
- }
+ public override void Begin() => MakeContextCurrent();
- public override void End()
- {
- SDL2OpenGLContext.MakeNoneCurrent();
- }
+ public override void End() => SDL2OpenGLContext.MakeNoneCurrent();
public override void SwapBuffers()
{
diff --git a/src/BizHawk.Bizware.Graphics/D3D9/IGL_D3D9.cs b/src/BizHawk.Bizware.Graphics/D3D9/IGL_D3D9.cs
index 194a41e42c8..d4dc622cee0 100644
--- a/src/BizHawk.Bizware.Graphics/D3D9/IGL_D3D9.cs
+++ b/src/BizHawk.Bizware.Graphics/D3D9/IGL_D3D9.cs
@@ -65,7 +65,7 @@ public IGL_D3D9()
}
// get the native window handle
- var wminfo = default(SDL_SysWMinfo);
+ SDL_SysWMinfo wminfo = default;
SDL_GetVersion(out wminfo.version);
SDL_GetWindowWMInfo(_offscreenSdl2Window, ref wminfo);
if (wminfo.subsystem != SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS)
@@ -93,7 +93,7 @@ public void AlternateVsyncPass(int pass)
private void CreateDevice()
{
// this object is only used for creating a device, it's not needed afterwards
- using var d3d9 = new Direct3D();
+ using Direct3D d3d9 = new();
var pp = MakePresentParameters();
@@ -213,7 +213,7 @@ public void ClearColor(Color color)
public void FreeTexture(Texture2d tex)
{
- var tw = (TextureWrapper)tex.Opaque;
+ TextureWrapper tw = (TextureWrapper)tex.Opaque;
tw.Texture.Dispose();
}
@@ -230,7 +230,7 @@ public Shader CreateFragmentShader(string source, string entry, bool required)
{
try
{
- var sw = new ShaderWrapper();
+ ShaderWrapper sw = new();
// ShaderFlags.EnableBackwardsCompatibility - used this once upon a time (please leave a note about why)
var result = ShaderBytecode.Compile(
@@ -242,7 +242,7 @@ public Shader CreateFragmentShader(string source, string entry, bool required)
sw.PS = new(_device, result);
sw.Bytecode = result;
- var s = new Shader(this, sw, true);
+ Shader s = new(this, sw, true);
sw.IGLShader = s;
return s;
@@ -263,7 +263,7 @@ public Shader CreateVertexShader(string source, string entry, bool required)
{
try
{
- var sw = new ShaderWrapper();
+ ShaderWrapper sw = new();
var result = ShaderBytecode.Compile(
shaderSource: source,
@@ -274,7 +274,7 @@ public Shader CreateVertexShader(string source, string entry, bool required)
sw.VS = new(_device, result);
sw.Bytecode = result;
- var s = new Shader(this, sw, true);
+ Shader s = new(this, sw, true);
sw.IGLShader = s;
return s;
@@ -315,7 +315,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S
{
if (!vertexShader.Available || !fragmentShader.Available)
{
- var errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}";
+ string errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}";
if (required)
{
throw new InvalidOperationException($"Couldn't build required GL pipeline:\r\n{errors}");
@@ -324,8 +324,8 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S
return new(this, null, false, null, null, null) { Errors = errors };
}
- var ves = new VertexElement[vertexLayout.Items.Count + 1];
- var stride = 0;
+ VertexElement[] ves = new VertexElement[vertexLayout.Items.Count + 1];
+ int stride = 0;
foreach (var (i, item) in vertexLayout.Items)
{
DeclarationType declType;
@@ -375,7 +375,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S
// must be placed at the end
ves[vertexLayout.Items.Count] = VertexElement.VertexDeclarationEnd;
- var pw = new PipelineWrapper
+ PipelineWrapper pw = new()
{
VertexDeclaration = new(_device, ves),
VertexShader = (ShaderWrapper)vertexShader.Opaque,
@@ -384,14 +384,14 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S
};
// scan uniforms from reflection
- var uniforms = new List();
+ List uniforms = new();
var vsct = pw.VertexShader.Bytecode.ConstantTable;
var psct = pw.FragmentShader.Bytecode.ConstantTable;
foreach (var ct in new[] { vsct, psct })
{
- var todo = new Queue<(string, EffectHandle)>();
- var n = ct.Description.Constants;
- for (var i = 0; i < n; i++)
+ Queue<(string, EffectHandle)> todo = new();
+ int n = ct.Description.Constants;
+ for (int i = 0; i < n; i++)
{
var handle = ct.GetConstant(null, i);
todo.Enqueue((string.Empty, handle));
@@ -406,8 +406,8 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S
if (descr.StructMembers != 0)
{
- var newPrefix = $"{prefix}{descr.Name}.";
- for (var j = 0; j < descr.StructMembers; j++)
+ string newPrefix = $"{prefix}{descr.Name}.";
+ for (int j = 0; j < descr.StructMembers; j++)
{
var subHandle = ct.GetConstant(handle, j);
todo.Enqueue((newPrefix, subHandle));
@@ -416,11 +416,11 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S
continue;
}
- var ui = new UniformInfo();
- var uw = new UniformWrapper();
+ UniformInfo ui = new();
+ UniformWrapper uw = new();
ui.Opaque = uw;
- var name = prefix + descr.Name;
+ string name = prefix + descr.Name;
// uniforms done through the entry point signature have $ in their names which isn't helpful, so get rid of that
name = name.RemovePrefix('$');
@@ -457,7 +457,7 @@ public void FreePipeline(Pipeline pipeline)
public void Internal_FreeShader(Shader shader)
{
- var sw = (ShaderWrapper)shader.Opaque;
+ ShaderWrapper sw = (ShaderWrapper)shader.Opaque;
sw.Bytecode.Dispose();
sw.PS?.Dispose();
sw.VS?.Dispose();
@@ -500,7 +500,7 @@ public void BindPipeline(Pipeline pipeline)
return;
}
- var pw = (PipelineWrapper)pipeline.Opaque;
+ PipelineWrapper pw = (PipelineWrapper)pipeline.Opaque;
_device.PixelShader = pw.FragmentShader.PS;
_device.VertexShader = pw.VertexShader.VS;
_device.VertexDeclaration = pw.VertexDeclaration;
@@ -510,7 +510,7 @@ public void SetPipelineUniform(PipelineUniform uniform, bool value)
{
foreach (var ui in uniform.UniformInfos)
{
- var uw = (UniformWrapper)ui.Opaque;
+ UniformWrapper uw = (UniformWrapper)ui.Opaque;
uw.CT.SetValue(_device, uw.EffectHandle, value);
}
}
@@ -522,7 +522,7 @@ public void SetPipelineUniformMatrix(PipelineUniform uniform, ref Matrix4x4 mat,
{
foreach (var ui in uniform.UniformInfos)
{
- var uw = (UniformWrapper)ui.Opaque;
+ UniformWrapper uw = (UniformWrapper)ui.Opaque;
uw.CT.SetValue(_device, uw.EffectHandle, mat.ToSharpDXMatrix(!transpose));
}
}
@@ -531,7 +531,7 @@ public void SetPipelineUniform(PipelineUniform uniform, Vector4 value)
{
foreach (var ui in uniform.UniformInfos)
{
- var uw = (UniformWrapper)ui.Opaque;
+ UniformWrapper uw = (UniformWrapper)ui.Opaque;
uw.CT.SetValue(_device, uw.EffectHandle, value.ToSharpDXVector4());
}
}
@@ -540,7 +540,7 @@ public void SetPipelineUniform(PipelineUniform uniform, Vector2 value)
{
foreach (var ui in uniform.UniformInfos)
{
- var uw = (UniformWrapper)ui.Opaque;
+ UniformWrapper uw = (UniformWrapper)ui.Opaque;
uw.CT.SetValue(_device, uw.EffectHandle, value.ToSharpDXVector2());
}
}
@@ -549,7 +549,7 @@ public void SetPipelineUniform(PipelineUniform uniform, float value)
{
foreach (var ui in uniform.UniformInfos)
{
- var uw = (UniformWrapper)ui.Opaque;
+ UniformWrapper uw = (UniformWrapper)ui.Opaque;
uw.CT.SetValue(_device, uw.EffectHandle, value);
}
}
@@ -559,7 +559,7 @@ public void SetPipelineUniform(PipelineUniform uniform, Vector4[] values)
var v = Array.ConvertAll(values, v => v.ToSharpDXVector4());
foreach (var ui in uniform.UniformInfos)
{
- var uw = (UniformWrapper)ui.Opaque;
+ UniformWrapper uw = (UniformWrapper)ui.Opaque;
uw.CT.SetValue(_device, uw.EffectHandle, v);
}
}
@@ -571,7 +571,7 @@ public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex)
return; // uniform was optimized out
}
- var tw = (TextureWrapper)tex.Opaque;
+ TextureWrapper tw = (TextureWrapper)tex.Opaque;
foreach (var ui in uniform.UniformInfos)
{
if (!ui.IsSampler)
@@ -590,7 +590,7 @@ public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex)
public void SetTextureWrapMode(Texture2d tex, bool clamp)
{
- var tw = (TextureWrapper)tex.Opaque;
+ TextureWrapper tw = (TextureWrapper)tex.Opaque;
tw.WrapClamp = clamp ? TextureAddress.Clamp : TextureAddress.Wrap;
}
@@ -606,34 +606,32 @@ public void SetMagFilter(Texture2d texture, TextureMagFilter magFilter)
public Texture2d LoadTexture(Bitmap bitmap)
{
- using var bmp = new BitmapBuffer(bitmap, new());
+ using BitmapBuffer bmp = new(bitmap, new());
return LoadTexture(bmp);
}
public Texture2d LoadTexture(Stream stream)
{
- using var bmp = new BitmapBuffer(stream, new());
+ using BitmapBuffer bmp = new(stream, new());
return LoadTexture(bmp);
}
public Texture2d CreateTexture(int width, int height)
{
- var tex = new Texture(_device, width, height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
- var tw = new TextureWrapper { Texture = tex };
- var ret = new Texture2d(this, tw, width, height);
+ Texture tex = new(_device, width, height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
+ TextureWrapper tw = new() { Texture = tex };
+ Texture2d ret = new(this, tw, width, height);
return ret;
}
- public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height)
- {
+ public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) =>
// only used for OpenGL
- return null;
- }
+ null;
/// GDI+ call returned unexpected data
public unsafe void LoadTextureData(Texture2d tex, BitmapBuffer bmp)
{
- var tw = (TextureWrapper)tex.Opaque;
+ TextureWrapper tw = (TextureWrapper)tex.Opaque;
var bmpData = bmp.LockBits();
try
@@ -646,8 +644,8 @@ public unsafe void LoadTextureData(Texture2d tex, BitmapBuffer bmp)
throw new InvalidOperationException();
}
- var srcSpan = new ReadOnlySpan(bmpData.Scan0.ToPointer(), bmpData.Stride * bmp.Height);
- var dstSpan = new Span(dr.DataPointer.ToPointer(), dr.Pitch * bmp.Height);
+ ReadOnlySpan srcSpan = new(bmpData.Scan0.ToPointer(), bmpData.Stride * bmp.Height);
+ Span dstSpan = new(dr.DataPointer.ToPointer(), dr.Pitch * bmp.Height);
srcSpan.CopyTo(dstSpan);
}
finally
@@ -668,8 +666,8 @@ public Texture2d LoadTexture(BitmapBuffer bmp)
public BitmapBuffer ResolveTexture2d(Texture2d tex)
{
// TODO - lazy create and cache resolving target in RT
- using var target = new Texture(_device, tex.IntWidth, tex.IntHeight, 1, Usage.None, Format.A8R8G8B8, Pool.SystemMemory);
- var tw = (TextureWrapper)tex.Opaque;
+ using Texture target = new(_device, tex.IntWidth, tex.IntHeight, 1, Usage.None, Format.A8R8G8B8, Pool.SystemMemory);
+ TextureWrapper tw = (TextureWrapper)tex.Opaque;
_device.GetRenderTargetData(tw.Texture.GetSurfaceLevel(0), target.GetSurfaceLevel(0));
@@ -681,8 +679,8 @@ public BitmapBuffer ResolveTexture2d(Texture2d tex)
{
throw new InvalidOperationException();
}
-
- var pixels = new int[tex.IntWidth * tex.IntHeight];
+
+ int[] pixels = new int[tex.IntWidth * tex.IntHeight];
Marshal.Copy(dr.DataPointer, pixels, 0, tex.IntWidth * tex.IntHeight);
return new(tex.IntWidth, tex.IntHeight, pixels);
}
@@ -694,19 +692,13 @@ public BitmapBuffer ResolveTexture2d(Texture2d tex)
public Texture2d LoadTexture(string path)
{
- using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read);
return LoadTexture(fs);
}
- public Matrix4x4 CreateGuiProjectionMatrix(int w, int h)
- {
- return CreateGuiProjectionMatrix(new(w, h));
- }
+ public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) => CreateGuiProjectionMatrix(new(w, h));
- public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoFlip)
- {
- return CreateGuiViewMatrix(new(w, h), autoFlip);
- }
+ public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoFlip) => CreateGuiViewMatrix(new(w, h), autoFlip);
public Matrix4x4 CreateGuiProjectionMatrix(Size dims)
{
@@ -733,19 +725,13 @@ public void SetViewport(int x, int y, int width, int height)
_device.ScissorRect = new(x, y, x + width, y + height);
}
- public void SetViewport(int width, int height)
- {
- SetViewport(0, 0, width, height);
- }
+ public void SetViewport(int width, int height) => SetViewport(0, 0, width, height);
- public void SetViewport(Size size)
- {
- SetViewport(size.Width, size.Height);
- }
+ public void SetViewport(Size size) => SetViewport(size.Width, size.Height);
public void FreeRenderTarget(RenderTarget rt)
{
- var tw = (TextureWrapper)rt.Texture2d.Opaque;
+ TextureWrapper tw = (TextureWrapper)rt.Texture2d.Opaque;
tw.Texture.Dispose();
tw.Texture = null;
_renderTargets.Remove(rt);
@@ -753,9 +739,9 @@ public void FreeRenderTarget(RenderTarget rt)
public RenderTarget CreateRenderTarget(int w, int h)
{
- var tw = new TextureWrapper { Texture = CreateRenderTargetTexture(w, h) };
- var tex = new Texture2d(this, tw, w, h);
- var rt = new RenderTarget(this, tw, tex);
+ TextureWrapper tw = new() { Texture = CreateRenderTargetTexture(w, h) };
+ Texture2d tex = new(this, tw, w, h);
+ RenderTarget rt = new(this, tw, tex);
_renderTargets.Add(rt);
return rt;
}
@@ -776,7 +762,7 @@ private void ResumeRenderTargets()
{
foreach (var rt in _renderTargets)
{
- var tw = (TextureWrapper)rt.Opaque;
+ TextureWrapper tw = (TextureWrapper)rt.Opaque;
tw.Texture = CreateRenderTargetTexture(rt.Texture2d.IntWidth, rt.Texture2d.IntHeight);
}
}
@@ -792,7 +778,7 @@ public void BindRenderTarget(RenderTarget rt)
}
// dispose doesn't seem necessary for reset here...
- var tw = (TextureWrapper)rt.Opaque;
+ TextureWrapper tw = (TextureWrapper)rt.Opaque;
using var texSurface = tw.Texture.GetSurfaceLevel(0);
_device.SetRenderTarget(0, texSurface);
_device.DepthStencilSurface = null;
@@ -811,7 +797,7 @@ private void DrawPrimitiveUP(PrimitiveType primitiveType, int primitiveCount, In
public void Draw(IntPtr data, int count)
{
- var pw = (PipelineWrapper)_currPipeline.Opaque;
+ PipelineWrapper pw = (PipelineWrapper)_currPipeline.Opaque;
// this is stupid, sharpdx only public exposes DrawUserPrimatives
// why is this bad? it takes in an array of T
diff --git a/src/BizHawk.Bizware.Graphics/GDIPlus/GDIPlusRenderTarget.cs b/src/BizHawk.Bizware.Graphics/GDIPlus/GDIPlusRenderTarget.cs
index 56aa376e9a6..f46da5afe37 100644
--- a/src/BizHawk.Bizware.Graphics/GDIPlus/GDIPlusRenderTarget.cs
+++ b/src/BizHawk.Bizware.Graphics/GDIPlus/GDIPlusRenderTarget.cs
@@ -50,7 +50,7 @@ public void CreateGraphics()
}
else
{
- var gtex = (GDIPlusTexture)Target.Texture2d.Opaque;
+ GDIPlusTexture gtex = (GDIPlusTexture)Target.Texture2d.Opaque;
CurGraphics?.Dispose();
CurGraphics = SDGraphics.FromImage(gtex.SDBitmap);
r = Target.Texture2d.Rectangle;
diff --git a/src/BizHawk.Bizware.Graphics/GDIPlus/IGL_GDIPlus.cs b/src/BizHawk.Bizware.Graphics/GDIPlus/IGL_GDIPlus.cs
index 12672eebc88..814ea0dbab5 100644
--- a/src/BizHawk.Bizware.Graphics/GDIPlus/IGL_GDIPlus.cs
+++ b/src/BizHawk.Bizware.Graphics/GDIPlus/IGL_GDIPlus.cs
@@ -16,10 +16,7 @@ public class IGL_GDIPlus : IGL
{
public EDispMethod DispMethodEnum => EDispMethod.GdiPlus;
- public void Dispose()
- {
- BufferedGraphicsContext.Dispose();
- }
+ public void Dispose() => BufferedGraphicsContext.Dispose();
public void ClearColor(Color color)
=> GetCurrentGraphics().Clear(color);
@@ -28,7 +25,7 @@ public void ClearColor(Color color)
public void FreeTexture(Texture2d tex)
{
- var gtex = (GDIPlusTexture)tex.Opaque;
+ GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque;
gtex.Dispose();
}
@@ -52,10 +49,7 @@ public void DisableBlending()
g.CompositingQuality = CompositingQuality.HighSpeed;
}
- public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required, string memo)
- {
- return null;
- }
+ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required, string memo) => null;
public void FreePipeline(Pipeline pipeline)
{
@@ -125,29 +119,27 @@ public void SetMagFilter(Texture2d texture, TextureMagFilter magFilter)
public Texture2d LoadTexture(Bitmap bitmap)
{
- var sdBitmap = (Bitmap)bitmap.Clone();
- var gtex = new GDIPlusTexture { SDBitmap = sdBitmap };
+ Bitmap sdBitmap = (Bitmap)bitmap.Clone();
+ GDIPlusTexture gtex = new() { SDBitmap = sdBitmap };
return new(this, gtex, bitmap.Width, bitmap.Height);
}
public Texture2d LoadTexture(Stream stream)
{
- using var bmp = new BitmapBuffer(stream, new());
+ using BitmapBuffer bmp = new(stream, new());
return LoadTexture(bmp);
}
public Texture2d CreateTexture(int width, int height)
=> null;
- public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height)
- {
+ public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) =>
// only used for OpenGL
- return null;
- }
+ null;
public void LoadTextureData(Texture2d tex, BitmapBuffer bmp)
{
- var gtex = (GDIPlusTexture)tex.Opaque;
+ GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque;
bmp.ToSysdrawingBitmap(gtex.SDBitmap);
}
@@ -155,51 +147,41 @@ public Texture2d LoadTexture(BitmapBuffer bmp)
{
// definitely needed (by TextureFrugalizer at least)
var sdBitmap = bmp.ToSysdrawingBitmap();
- var gtex = new GDIPlusTexture { SDBitmap = sdBitmap };
+ GDIPlusTexture gtex = new() { SDBitmap = sdBitmap };
return new(this, gtex, bmp.Width, bmp.Height);
}
public BitmapBuffer ResolveTexture2d(Texture2d tex)
{
- var gtex = (GDIPlusTexture)tex.Opaque;
- var blow = new BitmapLoadOptions
+ GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque;
+ BitmapLoadOptions blow = new()
{
AllowWrap = false // must be an independent resource
};
- var bb = new BitmapBuffer(gtex.SDBitmap, blow);
+ BitmapBuffer bb = new(gtex.SDBitmap, blow);
return bb;
}
public Texture2d LoadTexture(string path)
{
- using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read);
return LoadTexture(fs);
}
- public Matrix4x4 CreateGuiProjectionMatrix(int w, int h)
- {
- return CreateGuiProjectionMatrix(new(w, h));
- }
+ public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) => CreateGuiProjectionMatrix(new(w, h));
- public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoFlip)
- {
- return CreateGuiViewMatrix(new(w, h), autoFlip);
- }
+ public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoFlip) => CreateGuiViewMatrix(new(w, h), autoFlip);
- public Matrix4x4 CreateGuiProjectionMatrix(Size dims)
- {
+ public Matrix4x4 CreateGuiProjectionMatrix(Size dims) =>
// see CreateGuiViewMatrix for more
- return Matrix4x4.Identity;
- }
+ Matrix4x4.Identity;
- public Matrix4x4 CreateGuiViewMatrix(Size dims, bool autoFlip)
- {
+ public Matrix4x4 CreateGuiViewMatrix(Size dims, bool autoFlip) =>
// on account of gdi+ working internally with a default view exactly like we want, we don't need to setup a new one here
// furthermore, we _cant_, without inverting the GuiView and GuiProjection before drawing, to completely undo it
// this might be feasible, but its kind of slow and annoying and worse, seemingly numerically unstable
- return Matrix4x4.Identity;
- }
+ Matrix4x4.Identity;
public void SetViewport(int x, int y, int width, int height)
{
@@ -209,38 +191,33 @@ public void SetViewport(int width, int height)
{
}
- public void SetViewport(Size size)
- {
- SetViewport(size.Width, size.Height);
- }
+ public void SetViewport(Size size) => SetViewport(size.Width, size.Height);
public void BeginScene()
{
}
- public void EndScene()
- {
+ public void EndScene() =>
// maybe an inconsistent semantic with other implementations..
// but accomplishes the needed goal of getting the current RT to render
BindRenderTarget(null);
- }
public void FreeRenderTarget(RenderTarget rt)
{
- var grt = (GDIPlusRenderTarget)rt.Opaque;
+ GDIPlusRenderTarget grt = (GDIPlusRenderTarget)rt.Opaque;
grt.Dispose();
}
public RenderTarget CreateRenderTarget(int w, int h)
{
- var gtex = new GDIPlusTexture
+ GDIPlusTexture gtex = new()
{
SDBitmap = new(w, h, PixelFormat.Format32bppArgb)
};
- var tex = new Texture2d(this, gtex, w, h);
+ Texture2d tex = new(this, gtex, w, h);
- var grt = new GDIPlusRenderTarget(() => BufferedGraphicsContext);
- var rt = new RenderTarget(this, grt, tex);
+ GDIPlusRenderTarget grt = new(() => BufferedGraphicsContext);
+ RenderTarget rt = new(this, grt, tex);
grt.Target = rt;
return rt;
}
@@ -260,7 +237,7 @@ public void BindRenderTarget(RenderTarget rt)
}
else
{
- var gtex = (GDIPlusTexture)rt.Texture2d.Opaque;
+ GDIPlusTexture gtex = (GDIPlusTexture)rt.Texture2d.Opaque;
CurrentRenderTarget = (GDIPlusRenderTarget)rt.Opaque;
_currOffscreenGraphics = SDGraphics.FromImage(gtex.SDBitmap);
}
@@ -281,10 +258,7 @@ public GDIPlusRenderTarget CreateControlRenderTarget(Func<(SDGraphics Graphics,
private SDGraphics _currOffscreenGraphics;
- public SDGraphics GetCurrentGraphics()
- {
- return _currOffscreenGraphics ?? CurrentRenderTarget.BufferedGraphics.Graphics;
- }
+ public SDGraphics GetCurrentGraphics() => _currOffscreenGraphics ?? CurrentRenderTarget.BufferedGraphics.Graphics;
public GDIPlusRenderTarget CurrentRenderTarget;
diff --git a/src/BizHawk.Bizware.Graphics/OpenGL/IGL_OpenGL.cs b/src/BizHawk.Bizware.Graphics/OpenGL/IGL_OpenGL.cs
index c94e48e8dc3..0b199620531 100644
--- a/src/BizHawk.Bizware.Graphics/OpenGL/IGL_OpenGL.cs
+++ b/src/BizHawk.Bizware.Graphics/OpenGL/IGL_OpenGL.cs
@@ -64,10 +64,7 @@ public void EndScene()
{
}
- public void Dispose()
- {
- GL.Dispose();
- }
+ public void Dispose() => GL.Dispose();
public void ClearColor(Color color)
{
@@ -75,20 +72,11 @@ public void ClearColor(Color color)
GL.Clear(ClearBufferMask.ColorBufferBit);
}
- public void FreeTexture(Texture2d tex)
- {
- GL.DeleteTexture((uint)tex.Opaque);
- }
+ public void FreeTexture(Texture2d tex) => GL.DeleteTexture((uint)tex.Opaque);
- public BizShader CreateFragmentShader(string source, string entry, bool required)
- {
- return CreateShader(ShaderType.FragmentShader, source, required);
- }
+ public BizShader CreateFragmentShader(string source, string entry, bool required) => CreateShader(ShaderType.FragmentShader, source, required);
- public BizShader CreateVertexShader(string source, string entry, bool required)
- {
- return CreateShader(ShaderType.VertexShader, source, required);
- }
+ public BizShader CreateVertexShader(string source, string entry, bool required) => CreateShader(ShaderType.VertexShader, source, required);
public void EnableBlending()
{
@@ -121,7 +109,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader
// if the shaders aren't available, the pipeline isn't either
if (!vertexShader.Available || !fragmentShader.Available)
{
- var errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}";
+ string errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}";
if (required)
{
throw new InvalidOperationException($"Couldn't build required GL pipeline:\r\n{errors}");
@@ -130,20 +118,20 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader
return new(this, null, false, null, null, null) { Errors = errors };
}
- var success = true;
+ bool success = true;
- var vsw = (ShaderWrapper)vertexShader.Opaque;
- var fsw = (ShaderWrapper)fragmentShader.Opaque;
+ ShaderWrapper vsw = (ShaderWrapper)vertexShader.Opaque;
+ ShaderWrapper fsw = (ShaderWrapper)fragmentShader.Opaque;
- var pid = GL.CreateProgram();
+ uint pid = GL.CreateProgram();
GL.AttachShader(pid, vsw.sid);
GL.AttachShader(pid, fsw.sid);
_ = GL.GetError();
GL.LinkProgram(pid);
- var errcode = (ErrorCode)GL.GetError();
- var resultLog = GL.GetProgramInfoLog(pid);
+ ErrorCode errcode = (ErrorCode)GL.GetError();
+ string resultLog = GL.GetProgramInfoLog(pid);
if (errcode != ErrorCode.NoError)
{
@@ -155,7 +143,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader
success = false;
}
- GL.GetProgram(pid, GLEnum.LinkStatus, out var linkStatus);
+ GL.GetProgram(pid, GLEnum.LinkStatus, out int linkStatus);
if (linkStatus == 0)
{
if (required)
@@ -206,16 +194,16 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader
#endif
// get all the uniforms
- var uniforms = new List();
- GL.GetProgram(pid, GLEnum.ActiveUniforms, out var nUniforms);
- var samplers = new List();
+ List uniforms = new();
+ GL.GetProgram(pid, GLEnum.ActiveUniforms, out int nUniforms);
+ List samplers = new();
for (uint i = 0; i < nUniforms; i++)
{
GL.GetActiveUniform(pid, i, 1024, out _, out _, out UniformType type, out string name);
- var loc = GL.GetUniformLocation(pid, name);
+ int loc = GL.GetUniformLocation(pid, name);
- var ui = new UniformInfo { Name = name, Opaque = loc };
+ UniformInfo ui = new() { Name = name, Opaque = loc };
if (type == UniformType.Sampler2D)
{
@@ -234,7 +222,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader
if (!vertexShader.Available) success = false;
if (!fragmentShader.Available) success = false;
- var pw = new PipelineWrapper { pid = pid, VertexShader = vertexShader, FragmentShader = fragmentShader, SamplerLocs = samplers };
+ PipelineWrapper pw = new() { pid = pid, VertexShader = vertexShader, FragmentShader = fragmentShader, SamplerLocs = samplers };
return new(this, pw, success, vertexLayout, uniforms, memo);
}
@@ -255,7 +243,7 @@ public void FreePipeline(Pipeline pipeline)
public void Internal_FreeShader(BizShader shader)
{
- var sw = (ShaderWrapper)shader.Opaque;
+ ShaderWrapper sw = (ShaderWrapper)shader.Opaque;
GL.DeleteShader(sw.sid);
}
@@ -275,11 +263,11 @@ public void BindPipeline(Pipeline pipeline)
throw new InvalidOperationException("Attempt to bind unavailable pipeline");
}
- var pw = (PipelineWrapper)pipeline.Opaque;
+ PipelineWrapper pw = (PipelineWrapper)pipeline.Opaque;
GL.UseProgram(pw.pid);
// this is dumb and confusing, but we have to bind physical sampler numbers to sampler variables.
- for (var i = 0; i < pw.SamplerLocs.Count; i++)
+ for (int i = 0; i < pw.SamplerLocs.Count; i++)
{
GL.Uniform1(pw.SamplerLocs[i], i);
}
@@ -294,7 +282,7 @@ private class VertexLayoutWrapper
public VertexLayout CreateVertexLayout()
{
- var vlw = new VertexLayoutWrapper()
+ VertexLayoutWrapper vlw = new()
{
vao = GL.GenVertexArray(),
vbo = GL.GenBuffer(),
@@ -306,15 +294,12 @@ public VertexLayout CreateVertexLayout()
public void Internal_FreeVertexLayout(VertexLayout vl)
{
- var vlw = (VertexLayoutWrapper)vl.Opaque;
+ VertexLayoutWrapper vlw = (VertexLayoutWrapper)vl.Opaque;
GL.DeleteVertexArray(vlw.vao);
GL.DeleteBuffer(vlw.vbo);
}
- private void BindTexture2d(Texture2d tex)
- {
- GL.BindTexture(TextureTarget.Texture2D, (uint)tex.Opaque);
- }
+ private void BindTexture2d(Texture2d tex) => GL.BindTexture(TextureTarget.Texture2D, (uint)tex.Opaque);
public void SetTextureWrapMode(Texture2d tex, bool clamp)
{
@@ -338,7 +323,7 @@ private void LegacyBindArrayData(VertexLayout vertexLayout, IntPtr pData)
GL.DisableClientState(EnableCap.VertexArray);
GL.DisableClientState(EnableCap.ColorArray);
- for (var i = 1; i >= 0; i--)
+ for (int i = 1; i >= 0; i--)
{
GL.ClientActiveTexture(TextureUnit.Texture0 + i);
GL.DisableClientState(EnableCap.TextureCoordArray);
@@ -393,16 +378,16 @@ public void Draw(IntPtr data, int count)
return;
}
- var vlw = (VertexLayoutWrapper)vertexLayout.Opaque;
+ VertexLayoutWrapper vlw = (VertexLayoutWrapper)vertexLayout.Opaque;
GL.BindVertexArray(vlw.vao);
GL.BindBuffer(GLEnum.ArrayBuffer, vlw.vbo);
- var stride = vertexLayout.Items[0].Stride;
+ int stride = vertexLayout.Items[0].Stride;
Debug.Assert(vertexLayout.Items.All(i => i.Value.Stride == stride));
unsafe
{
- var vertexes = new ReadOnlySpan(data.ToPointer(), count * stride);
+ ReadOnlySpan vertexes = new(data.ToPointer(), count * stride);
// BufferData reallocs and BufferSubData doesn't, so only use the former if size changes
if (vertexes.Length != vlw.bufferLen)
@@ -441,15 +426,9 @@ public void Draw(IntPtr data, int count)
GL.BindVertexArray(0);
}
- public void SetPipelineUniform(PipelineUniform uniform, bool value)
- {
- GL.Uniform1((int)uniform.Sole.Opaque, value ? 1 : 0);
- }
+ public void SetPipelineUniform(PipelineUniform uniform, bool value) => GL.Uniform1((int)uniform.Sole.Opaque, value ? 1 : 0);
- public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, Matrix4x4 mat, bool transpose)
- {
- GL.UniformMatrix4((int)uniform.Sole.Opaque, 1, transpose, (float*)&mat);
- }
+ public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, Matrix4x4 mat, bool transpose) => GL.UniformMatrix4((int)uniform.Sole.Opaque, 1, transpose, (float*)&mat);
public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, ref Matrix4x4 mat, bool transpose)
{
@@ -459,15 +438,9 @@ public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, ref Matrix4
}
}
- public void SetPipelineUniform(PipelineUniform uniform, Vector4 value)
- {
- GL.Uniform4((int)uniform.Sole.Opaque, value.X, value.Y, value.Z, value.W);
- }
+ public void SetPipelineUniform(PipelineUniform uniform, Vector4 value) => GL.Uniform4((int)uniform.Sole.Opaque, value.X, value.Y, value.Z, value.W);
- public void SetPipelineUniform(PipelineUniform uniform, Vector2 value)
- {
- GL.Uniform2((int)uniform.Sole.Opaque, value.X, value.Y);
- }
+ public void SetPipelineUniform(PipelineUniform uniform, Vector2 value) => GL.Uniform2((int)uniform.Sole.Opaque, value.X, value.Y);
public void SetPipelineUniform(PipelineUniform uniform, float value)
{
@@ -489,7 +462,7 @@ public unsafe void SetPipelineUniform(PipelineUniform uniform, Vector4[] values)
public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex)
{
- var n = (int)uniform.Sole.Opaque >> 24;
+ int n = (int)uniform.Sole.Opaque >> 24;
// set the sampler index into the uniform first
GL.ActiveTexture(TextureUnit.Texture0 + n);
@@ -512,26 +485,23 @@ public void SetMagFilter(Texture2d texture, BizTextureMagFilter magFilter)
public Texture2d LoadTexture(Bitmap bitmap)
{
- using var bmp = new BitmapBuffer(bitmap, new());
+ using BitmapBuffer bmp = new(bitmap, new());
return LoadTexture(bmp);
}
public Texture2d LoadTexture(Stream stream)
{
- using var bmp = new BitmapBuffer(stream, new());
+ using BitmapBuffer bmp = new(stream, new());
return LoadTexture(bmp);
}
public Texture2d CreateTexture(int width, int height)
{
- var id = GL.GenTexture();
+ uint id = GL.GenTexture();
return new(this, id, width, height);
}
- public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height)
- {
- return new(this, (uint)glTexId.ToInt32(), width, height) { IsUpsideDown = true };
- }
+ public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) => new(this, (uint)glTexId.ToInt32(), width, height) { IsUpsideDown = true };
public unsafe void LoadTextureData(Texture2d tex, BitmapBuffer bmp)
{
@@ -557,8 +527,8 @@ public void FreeRenderTarget(RenderTarget rt)
public unsafe RenderTarget CreateRenderTarget(int w, int h)
{
// create a texture for it
- var texId = GL.GenTexture();
- var tex = new Texture2d(this, texId, w, h);
+ uint texId = GL.GenTexture();
+ Texture2d tex = new(this, texId, w, h);
GL.BindTexture(TextureTarget.Texture2D, texId);
GL.TexImage2D(TextureTarget.Texture2D, 0, InternalFormat.Rgba8, (uint)w, (uint)h, 0, PixelFormat.Bgra, PixelType.UnsignedByte, null);
@@ -566,7 +536,7 @@ public unsafe RenderTarget CreateRenderTarget(int w, int h)
tex.SetMinFilter(BizTextureMinFilter.Nearest);
// create the FBO
- var fbId = GL.GenFramebuffer();
+ uint fbId = GL.GenFramebuffer();
GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbId);
// bind the tex to the FBO
@@ -602,7 +572,7 @@ public void BindRenderTarget(RenderTarget rt)
public unsafe Texture2d LoadTexture(BitmapBuffer bmp)
{
Texture2d ret;
- var id = GL.GenTexture();
+ uint id = GL.GenTexture();
try
{
ret = new(this, id, bmp.Width, bmp.Height);
@@ -627,7 +597,7 @@ public unsafe BitmapBuffer ResolveTexture2d(Texture2d tex)
{
// note - this is dangerous since it changes the bound texture. could we save it?
BindTexture2d(tex);
- var bb = new BitmapBuffer(tex.IntWidth, tex.IntHeight);
+ BitmapBuffer bb = new(tex.IntWidth, tex.IntHeight);
var bmpdata = bb.LockBits();
GL.GetTexImage(TextureTarget.Texture2D, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmpdata.Scan0.ToPointer());
bb.UnlockBits(bmpdata);
@@ -636,19 +606,13 @@ public unsafe BitmapBuffer ResolveTexture2d(Texture2d tex)
public Texture2d LoadTexture(string path)
{
- using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read);
return LoadTexture(fs);
}
- public Matrix4x4 CreateGuiProjectionMatrix(int w, int h)
- {
- return CreateGuiProjectionMatrix(new(w, h));
- }
+ public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) => CreateGuiProjectionMatrix(new(w, h));
- public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoflip)
- {
- return CreateGuiViewMatrix(new(w, h), autoflip);
- }
+ public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoflip) => CreateGuiViewMatrix(new(w, h), autoflip);
public Matrix4x4 CreateGuiProjectionMatrix(Size dims)
{
@@ -680,24 +644,18 @@ public void SetViewport(int x, int y, int width, int height)
// BUT ALSO: new specifications.. viewport+scissor make sense together
}
- public void SetViewport(int width, int height)
- {
- SetViewport(0, 0, width, height);
- }
+ public void SetViewport(int width, int height) => SetViewport(0, 0, width, height);
- public void SetViewport(Size size)
- {
- SetViewport(size.Width, size.Height);
- }
+ public void SetViewport(Size size) => SetViewport(size.Width, size.Height);
private BizShader CreateShader(ShaderType type, string source, bool required)
{
- var sw = new ShaderWrapper();
- var info = string.Empty;
+ ShaderWrapper sw = new();
+ string info = string.Empty;
_ = GL.GetError();
- var sid = GL.CreateShader(type);
- var ok = CompileShaderSimple(sid, source, required);
+ uint sid = GL.CreateShader(type);
+ bool ok = CompileShaderSimple(sid, source, required);
if (!ok)
{
GL.GetShaderInfoLog(sid, out info);
@@ -705,7 +663,7 @@ private BizShader CreateShader(ShaderType type, string source, bool required)
sid = 0;
}
- var ret = new BizShader(this, sw, ok)
+ BizShader ret = new(this, sw, ok)
{
Errors = info
};
@@ -717,9 +675,9 @@ private BizShader CreateShader(ShaderType type, string source, bool required)
private bool CompileShaderSimple(uint sid, string source, bool required)
{
- var success = true;
+ bool success = true;
- var errcode = (ErrorCode)GL.GetError();
+ ErrorCode errcode = (ErrorCode)GL.GetError();
if (errcode != ErrorCode.NoError)
{
if (required)
@@ -746,10 +704,10 @@ private bool CompileShaderSimple(uint sid, string source, bool required)
GL.CompileShader(sid);
errcode = (ErrorCode)GL.GetError();
- var resultLog = GL.GetShaderInfoLog(sid);
+ string resultLog = GL.GetShaderInfoLog(sid);
if (errcode != ErrorCode.NoError)
{
- var message = $"Error compiling shader ({nameof(GL.CompileShader)}) {errcode}\r\n\r\n{resultLog}";
+ string message = $"Error compiling shader ({nameof(GL.CompileShader)}) {errcode}\r\n\r\n{resultLog}";
if (required)
{
throw new InvalidOperationException(message);
@@ -759,7 +717,7 @@ private bool CompileShaderSimple(uint sid, string source, bool required)
success = false;
}
- GL.GetShader(sid, ShaderParameterName.CompileStatus, out var n);
+ GL.GetShader(sid, ShaderParameterName.CompileStatus, out int n);
if (n == 0)
{
diff --git a/src/BizHawk.Bizware.Graphics/OpenGL/OpenGLVersion.cs b/src/BizHawk.Bizware.Graphics/OpenGL/OpenGLVersion.cs
index e1c0114a14d..19371d8bb3e 100644
--- a/src/BizHawk.Bizware.Graphics/OpenGL/OpenGLVersion.cs
+++ b/src/BizHawk.Bizware.Graphics/OpenGL/OpenGLVersion.cs
@@ -23,10 +23,7 @@ public SavedOpenGLContext()
_glContext = SDL_GL_GetCurrentContext();
}
- public void Dispose()
- {
- _ = SDL_GL_MakeCurrent(_sdlWindow, _glContext);
- }
+ public void Dispose() => _ = SDL_GL_MakeCurrent(_sdlWindow, _glContext);
}
private static readonly IDictionary _glSupport = new Dictionary();
@@ -42,11 +39,11 @@ private static bool CheckVersion(int requestedMajor, int requestedMinor)
{
using (new SDL2OpenGLContext(requestedMajor, requestedMinor, true, false))
{
- using var gl = GL.GetApi(SDL2OpenGLContext.GetGLProcAddress);
- var versionString = gl.GetStringS(StringName.Version);
- var versionParts = versionString!.Split('.');
- var major = int.Parse(versionParts[0]);
- var minor = int.Parse(versionParts[1][0].ToString());
+ using GL gl = GL.GetApi(SDL2OpenGLContext.GetGLProcAddress);
+ string versionString = gl.GetStringS(StringName.Version);
+ string[] versionParts = versionString!.Split('.');
+ int major = int.Parse(versionParts[0]);
+ int minor = int.Parse(versionParts[1][0].ToString());
return PackGLVersion(major, minor) >= PackGLVersion(requestedMajor, requestedMinor);
}
}
diff --git a/src/BizHawk.Bizware.Graphics/OpenGL/SDL2OpenGLContext.cs b/src/BizHawk.Bizware.Graphics/OpenGL/SDL2OpenGLContext.cs
index a81c39872be..bf04cd7eac1 100644
--- a/src/BizHawk.Bizware.Graphics/OpenGL/SDL2OpenGLContext.cs
+++ b/src/BizHawk.Bizware.Graphics/OpenGL/SDL2OpenGLContext.cs
@@ -133,17 +133,13 @@ public void Dispose()
public bool IsCurrent => SDL_GL_GetCurrentContext() == _glContext;
- public void MakeContextCurrent()
- {
+ public void MakeContextCurrent() =>
// no-op if already current
_ = SDL_GL_MakeCurrent(_sdlWindow, _glContext);
- }
- public static void MakeNoneCurrent()
- {
+ public static void MakeNoneCurrent() =>
// no-op if nothing is current
_ = SDL_GL_MakeCurrent(IntPtr.Zero, IntPtr.Zero);
- }
public static IntPtr GetGLProcAddress(string proc)
=> SDL_GL_GetProcAddress(proc);
diff --git a/src/BizHawk.Bizware.Graphics/Renderers/GDIPlusGuiRenderer.cs b/src/BizHawk.Bizware.Graphics/Renderers/GDIPlusGuiRenderer.cs
index 25d0fa66e25..38925efa2c4 100644
--- a/src/BizHawk.Bizware.Graphics/Renderers/GDIPlusGuiRenderer.cs
+++ b/src/BizHawk.Bizware.Graphics/Renderers/GDIPlusGuiRenderer.cs
@@ -27,10 +27,7 @@ public GDIPlusGuiRenderer(IGL_GDIPlus gdi)
new(1.0f, 1.0f, 1.0f, 1.0f)
};
- public void SetCornerColor(int which, Vector4 color)
- {
- CornerColors[which] = color;
- }
+ public void SetCornerColor(int which, Vector4 color) => CornerColors[which] = color;
/// does not have exactly 4 elements
public void SetCornerColors(Vector4[] colors)
@@ -42,16 +39,13 @@ public void SetCornerColors(Vector4[] colors)
throw new ArgumentException("array must be size 4", nameof(colors));
}
- for (var i = 0; i < 4; i++)
+ for (int i = 0; i < 4; i++)
{
CornerColors[i] = colors[i];
}
}
- public void Dispose()
- {
- CurrentImageAttributes?.Dispose();
- }
+ public void Dispose() => CurrentImageAttributes?.Dispose();
public void SetPipeline(Pipeline pipeline)
{
@@ -61,10 +55,7 @@ public void SetDefaultPipeline()
{
}
- public void SetModulateColorWhite()
- {
- SetModulateColor(Color.White);
- }
+ public void SetModulateColorWhite() => SetModulateColor(Color.White);
private ImageAttributes CurrentImageAttributes;
@@ -77,10 +68,10 @@ public void SetModulateColor(Color color)
return;
}
- var r = color.R / 255.0f;
- var g = color.G / 255.0f;
- var b = color.B / 255.0f;
- var a = color.A / 255.0f;
+ float r = color.R / 255.0f;
+ float g = color.G / 255.0f;
+ float b = color.B / 255.0f;
+ float a = color.A / 255.0f;
float[][] colorMatrixElements =
{
@@ -91,19 +82,13 @@ public void SetModulateColor(Color color)
new float[] { 0, 0, 0, 0, 1 },
};
- var colorMatrix = new ColorMatrix(colorMatrixElements);
+ ColorMatrix colorMatrix = new(colorMatrixElements);
CurrentImageAttributes.SetColorMatrix(colorMatrix,ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
}
- public void EnableBlending()
- {
- Owner.EnableBlending();
- }
+ public void EnableBlending() => Owner.EnableBlending();
- public void DisableBlending()
- {
- Owner.DisableBlending();
- }
+ public void DisableBlending() => Owner.DisableBlending();
private MatrixStack _Projection, _Modelview;
@@ -127,10 +112,7 @@ public MatrixStack Modelview
}
}
- public void Begin(Size size)
- {
- Begin(size.Width, size.Height);
- }
+ public void Begin(Size size) => Begin(size.Width, size.Height);
public void Begin(int width, int height)
{
@@ -176,16 +158,16 @@ public void RectFill(float x, float y, float w, float h)
public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1)
{
- var gtex = (GDIPlusTexture)tex.Opaque;
+ GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque;
var g = _gdi.GetCurrentGraphics();
PrepDraw(g, tex);
SetupMatrix(g);
- var x0 = u0 * tex.Width;
- var y0 = v0 * tex.Height;
- var x1 = u1 * tex.Width;
- var y1 = v1 * tex.Height;
+ float x0 = u0 * tex.Width;
+ float y0 = v0 * tex.Height;
+ float x1 = u1 * tex.Width;
+ float y1 = v1 * tex.Height;
PointF[] destPoints =
{
@@ -198,22 +180,19 @@ public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float
g.Transform = new(); // .Reset() doesnt work?
}
- public void Draw(Art art) { DrawInternal(art, 0, 0, art.Width, art.Height, false, false); }
- public void Draw(Art art, float x, float y) { DrawInternal(art, x, y, art.Width, art.Height, false, false); }
- public void Draw(Art art, float x, float y, float width, float height) { DrawInternal(art, x, y, width, height, false, false); }
- public void Draw(Art art, Vector2 pos) { DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false); }
- public void Draw(Texture2d tex) { DrawInternal(tex, 0, 0, tex.Width, tex.Height); }
- public void Draw(Texture2d tex, float x, float y) { DrawInternal(tex, x, y, tex.Width, tex.Height); }
- public void DrawFlipped(Art art, bool xflip, bool yflip) { DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip); }
+ public void Draw(Art art) => DrawInternal(art, 0, 0, art.Width, art.Height, false, false);
+ public void Draw(Art art, float x, float y) => DrawInternal(art, x, y, art.Width, art.Height, false, false);
+ public void Draw(Art art, float x, float y, float width, float height) => DrawInternal(art, x, y, width, height, false, false);
+ public void Draw(Art art, Vector2 pos) => DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false);
+ public void Draw(Texture2d tex) => DrawInternal(tex, 0, 0, tex.Width, tex.Height);
+ public void Draw(Texture2d tex, float x, float y) => DrawInternal(tex, x, y, tex.Width, tex.Height);
+ public void DrawFlipped(Art art, bool xflip, bool yflip) => DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip);
- public void Draw(Texture2d art, float x, float y, float width, float height)
- {
- DrawInternal(art, x, y, width, height);
- }
+ public void Draw(Texture2d art, float x, float y, float width, float height) => DrawInternal(art, x, y, width, height);
private static void PrepDraw(SDGraphics g, Texture2d tex)
{
- var tw = (GDIPlusTexture)tex.Opaque;
+ GDIPlusTexture tw = (GDIPlusTexture)tex.Opaque;
// TODO - we can support bicubic for the final presentation...
if ((int)tw.MagFilter != (int)tw.MinFilter)
@@ -237,15 +216,9 @@ private void SetupMatrix(SDGraphics g)
g.Transform = new(mat.M11, mat.M12, mat.M21, mat.M22, mat.M41, mat.M42);
}
- private void DrawInternal(Art art, float x, float y, float w, float h)
- {
- DrawInternal(art.BaseTexture, x, y, w, h, art.u0, art.v0, art.u1, art.v1);
- }
+ private void DrawInternal(Art art, float x, float y, float w, float h) => DrawInternal(art.BaseTexture, x, y, w, h, art.u0, art.v0, art.u1, art.v1);
- private void DrawInternal(Texture2d tex, float x, float y, float w, float h)
- {
- DrawInternal(tex, x, y, w, h, 0, 0, 1, 1);
- }
+ private void DrawInternal(Texture2d tex, float x, float y, float w, float h) => DrawInternal(tex, x, y, w, h, 0, 0, 1, 1);
private void DrawInternal(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1)
{
@@ -261,14 +234,14 @@ private void DrawInternal(Texture2d tex, float x, float y, float w, float h, flo
new(x, y+h),
};
- var sx = tex.Width * u0;
- var sy = tex.Height * v0;
- var sx2 = tex.Width * u1;
- var sy2 = tex.Height * v1;
- var sw = sx2 - sx;
- var sh = sy2 - sy;
+ float sx = tex.Width * u0;
+ float sy = tex.Height * v0;
+ float sx2 = tex.Width * u1;
+ float sy2 = tex.Height * v1;
+ float sw = sx2 - sx;
+ float sh = sy2 - sy;
- var gtex = (GDIPlusTexture)tex.Opaque;
+ GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque;
g.PixelOffsetMode = PixelOffsetMode.Half;
g.DrawImage(gtex.SDBitmap, destPoints, new(sx, sy, sw, sh), GraphicsUnit.Pixel, CurrentImageAttributes);
g.Transform = new(); // .Reset() doesn't work ? ?
diff --git a/src/BizHawk.Bizware.Graphics/Renderers/GuiRenderer.cs b/src/BizHawk.Bizware.Graphics/Renderers/GuiRenderer.cs
index 0d5df3a2bf3..fdb169185c2 100644
--- a/src/BizHawk.Bizware.Graphics/Renderers/GuiRenderer.cs
+++ b/src/BizHawk.Bizware.Graphics/Renderers/GuiRenderer.cs
@@ -66,7 +66,7 @@ public void SetCornerColors(Vector4[] colors)
{
Flush(); //don't really need to flush with current implementation. we might as well roll modulate color into it too.
if (colors.Length != 4) throw new ArgumentException("array must be size 4", nameof(colors));
- for (var i = 0; i < 4; i++)
+ for (int i = 0; i < 4; i++)
{
CornerColors[i] = colors[i];
}
@@ -92,15 +92,9 @@ public void SetPipeline(Pipeline pipeline)
// save the modulate color? user beware, I guess, for now.
}
- public void SetDefaultPipeline()
- {
- SetPipeline(DefaultPipeline);
- }
+ public void SetDefaultPipeline() => SetPipeline(DefaultPipeline);
- public void SetModulateColorWhite()
- {
- SetModulateColor(Color.White);
- }
+ public void SetModulateColorWhite() => SetModulateColor(Color.White);
public void SetModulateColor(Color color)
{
@@ -140,10 +134,7 @@ public MatrixStack Modelview
}
}
- public void Begin(Size size)
- {
- Begin(size.Width, size.Height);
- }
+ public void Begin(Size size) => Begin(size.Width, size.Height);
public void Begin(int width, int height)
{
@@ -201,54 +192,27 @@ public void RectFill(float x, float y, float w, float h)
}
- public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1)
- {
- DrawSubrectInternal(tex, x, y, w, h, u0, v0, u1, v1);
- }
+ public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1) => DrawSubrectInternal(tex, x, y, w, h, u0, v0, u1, v1);
- public void Draw(Art art)
- {
- DrawInternal(art, 0, 0, art.Width, art.Height, false, false);
- }
+ public void Draw(Art art) => DrawInternal(art, 0, 0, art.Width, art.Height, false, false);
- public void Draw(Art art, float x, float y)
- {
- DrawInternal(art, x, y, art.Width, art.Height, false, false);
- }
+ public void Draw(Art art, float x, float y) => DrawInternal(art, x, y, art.Width, art.Height, false, false);
- public void Draw(Art art, float x, float y, float width, float height)
- {
- DrawInternal(art, x, y, width, height, false, false);
- }
+ public void Draw(Art art, float x, float y, float width, float height) => DrawInternal(art, x, y, width, height, false, false);
- public void Draw(Art art, Vector2 pos)
- {
- DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false);
- }
+ public void Draw(Art art, Vector2 pos) => DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false);
- public void Draw(Texture2d tex)
- {
- DrawInternal(tex, 0, 0, tex.Width, tex.Height);
- }
+ public void Draw(Texture2d tex) => DrawInternal(tex, 0, 0, tex.Width, tex.Height);
- public void Draw(Texture2d tex, float x, float y)
- {
- DrawInternal(tex, x, y, tex.Width, tex.Height);
- }
+ public void Draw(Texture2d tex, float x, float y) => DrawInternal(tex, x, y, tex.Width, tex.Height);
- public void DrawFlipped(Art art, bool xflip, bool yflip)
- {
- DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip);
- }
+ public void DrawFlipped(Art art, bool xflip, bool yflip) => DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip);
- public void Draw(Texture2d art, float x, float y, float width, float height)
- {
- DrawInternal(art, x, y, width, height);
- }
+ public void Draw(Texture2d art, float x, float y, float width, float height) => DrawInternal(art, x, y, width, height);
private void DrawInternal(Texture2d tex, float x, float y, float w, float h)
{
- var art = new Art((ArtManager)null)
+ Art art = new((ArtManager)null)
{
Width = w,
Height = h
@@ -287,7 +251,7 @@ private unsafe void DrawInternal(Art art, float x, float y, float w, float h, bo
v1 = art.v1;
}
- var data = stackalloc float[32]
+ float* data = stackalloc float[32]
{
x, y, u0, v0,
CornerColors[0].X, CornerColors[0].Y, CornerColors[0].Z, CornerColors[0].W,
@@ -326,7 +290,7 @@ private void PrepDrawSubrectInternal(Texture2d tex)
private unsafe void EmitRectangleInternal(float x, float y, float w, float h, float u0, float v0, float u1, float v1)
{
- var pData = stackalloc float[32];
+ float* pData = stackalloc float[32];
pData[0] = x;
pData[1] = y;
pData[2] = u0;
diff --git a/src/BizHawk.Bizware.Input/DirectX/DGamepad.cs b/src/BizHawk.Bizware.Input/DirectX/DGamepad.cs
index 29d1d2d21a6..6f0c6090baf 100644
--- a/src/BizHawk.Bizware.Input/DirectX/DGamepad.cs
+++ b/src/BizHawk.Bizware.Input/DirectX/DGamepad.cs
@@ -49,7 +49,7 @@ public static void Initialize(IntPtr mainFormHandle)
}
#else
// hack due to the above problems
- var dict = (Dictionary)typeof(IDirectInputDevice8)
+ Dictionary dict = (Dictionary)typeof(IDirectInputDevice8)
.GetField("_mapNameToObjectFormat", BindingFlags.Instance | BindingFlags.NonPublic)!
.GetValue(joystick);
@@ -60,7 +60,7 @@ public static void Initialize(IntPtr mainFormHandle)
#endif
joystick.Acquire();
- var p = new DGamepad(joystick, Devices.Count);
+ DGamepad p = new(joystick, Devices.Count);
Devices.Add(p);
}
}
@@ -151,30 +151,18 @@ public void Update()
private static readonly ImmutableArray _axesPropertyInfos = typeof(JoystickState).GetProperties().Where(pi => pi.PropertyType == typeof(int)).ToImmutableArray();
- public IEnumerable<(string AxisID, float Value)> GetAxes()
- {
- return _axesPropertyInfos.Select(pi => (pi.Name, 10.0f * (int)pi.GetValue(_state)));
- }
+ public IEnumerable<(string AxisID, float Value)> GetAxes() => _axesPropertyInfos.Select(pi => (pi.Name, 10.0f * (int)pi.GetValue(_state)));
/// FOR DEBUGGING ONLY
- public JoystickState GetInternalState()
- {
- return _state;
- }
+ public JoystickState GetInternalState() => _state;
public int PlayerNumber { get; }
public readonly string InputNamePrefix;
- public string ButtonName(int index)
- {
- return _names[index];
- }
+ public string ButtonName(int index) => _names[index];
- public bool Pressed(int index)
- {
- return _actions[index]();
- }
+ public bool Pressed(int index) => _actions[index]();
public int NumButtons { get; private set; }
@@ -248,17 +236,17 @@ private void InitializeCallbacks()
// i don't know what the "Slider"s do, so they're omitted for the moment
- for (var i = 0; i < _state.Buttons.Length; i++)
+ for (int i = 0; i < _state.Buttons.Length; i++)
{
- var j = i;
+ int j = i;
AddItem($"B{i + 1}", () => _state.Buttons[j]);
}
- for (var i = 0; i < _state.PointOfViewControllers.Length; i++)
+ for (int i = 0; i < _state.PointOfViewControllers.Length; i++)
{
- var j = i;
+ int j = i;
AddItem($"POV{i + 1}U", () => {
- var t = _state.PointOfViewControllers[j];
+ int t = _state.PointOfViewControllers[j];
return 0.RangeTo(4500).Contains(t) || 31500.RangeToExclusive(36000).Contains(t);
});
AddItem($"POV{i + 1}D", () => 13500.RangeTo(22500).Contains(_state.PointOfViewControllers[j]));
@@ -273,7 +261,7 @@ public void SetVibration(int left, int right)
// my first clue that it doesn't work is that LEFT and RIGHT _AREN'T USED_
// I should just look for C++ examples instead of trying to look for SlimDX examples
- var parameters = new EffectParameters
+ EffectParameters parameters = new()
{
Duration = 0x2710,
Gain = 0x2710,
@@ -282,7 +270,7 @@ public void SetVibration(int left, int right)
TriggerRepeatInterval = 0x2710,
Flags = EffectFlags.None
};
- parameters.GetAxes(out var temp1, out var temp2);
+ parameters.GetAxes(out int[] temp1, out int[] temp2);
parameters.SetAxes(temp1, temp2);
var effect = _joystick.CreateEffect(EffectGuid.ConstantForce, parameters);
effect.Start(1);
diff --git a/src/BizHawk.Bizware.Input/DirectX/DKeyInput.cs b/src/BizHawk.Bizware.Input/DirectX/DKeyInput.cs
index c88a1e8a87c..b82697c66d9 100644
--- a/src/BizHawk.Bizware.Input/DirectX/DKeyInput.cs
+++ b/src/BizHawk.Bizware.Input/DirectX/DKeyInput.cs
@@ -57,7 +57,7 @@ public static IEnumerable Update(Config config)
{
if (_keyboard == null || _keyboard.Acquire().Failure || _keyboard.Poll().Failure) return Enumerable.Empty();
- var eventList = new List();
+ List eventList = new();
while (true)
{
try
@@ -78,7 +78,7 @@ private static DInputKey MapToRealKeyViaScanCode(DInputKey key)
{
const uint MAPVK_VSC_TO_VK_EX = 0x03;
// DInputKey is a scancode as is
- var virtualKey = MapVirtualKey((uint) key, MAPVK_VSC_TO_VK_EX);
+ uint virtualKey = MapVirtualKey((uint) key, MAPVK_VSC_TO_VK_EX);
return VKeyToDKeyMap.GetValueOrDefault(virtualKey, DInputKey.Unknown);
}
diff --git a/src/BizHawk.Bizware.Input/DirectX/DirectInputAdapter.cs b/src/BizHawk.Bizware.Input/DirectX/DirectInputAdapter.cs
index 3a836f34a68..fe9cd2cee35 100644
--- a/src/BizHawk.Bizware.Input/DirectX/DirectInputAdapter.cs
+++ b/src/BizHawk.Bizware.Input/DirectX/DirectInputAdapter.cs
@@ -55,8 +55,8 @@ public void ProcessHostGamepads(Action handleBu
continue;
for (int b = 0, n = pad.NumButtons; b < n; b++) handleButton(pad.InputNamePrefix + pad.ButtonName(b), pad.Pressed(b), ClientInputFocus.Pad);
foreach (var (axisName, f) in pad.GetAxes()) handleAxis(pad.InputNamePrefix + axisName, (int) f);
- var leftStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Left");
- var rightStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Right");
+ int leftStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Left");
+ int rightStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Right");
pad.SetVibration(leftStrength, rightStrength); // values will be 0 if not found
}
foreach (var pad in DGamepad.EnumerateDevices())
diff --git a/src/BizHawk.Bizware.Input/DirectX/XGamepad.cs b/src/BizHawk.Bizware.Input/DirectX/XGamepad.cs
index c6910ed044d..6f0a9d10588 100644
--- a/src/BizHawk.Bizware.Input/DirectX/XGamepad.cs
+++ b/src/BizHawk.Bizware.Input/DirectX/XGamepad.cs
@@ -144,8 +144,8 @@ public void Update()
const float f = 32768 / 10000.0f;
//since our whole input framework really only understands whole axes, let's make the triggers look like an axis
- var lTrig = g.LeftTrigger / 255.0f * 2 - 1;
- var rTrig = g.RightTrigger / 255.0f * 2 - 1;
+ float lTrig = g.LeftTrigger / 255.0f * 2 - 1;
+ float rTrig = g.RightTrigger / 255.0f * 2 - 1;
lTrig *= 10000;
rTrig *= 10000;
diff --git a/src/BizHawk.Bizware.Input/IPC/IPCKeyInput.cs b/src/BizHawk.Bizware.Input/IPC/IPCKeyInput.cs
index 431ec920851..0590a96ddc9 100644
--- a/src/BizHawk.Bizware.Input/IPC/IPCKeyInput.cs
+++ b/src/BizHawk.Bizware.Input/IPC/IPCKeyInput.cs
@@ -15,7 +15,7 @@ public static void Initialize()
{
if (!IPCActive)
{
- var t = new Thread(IPCThread) { IsBackground = true };
+ Thread t = new(IPCThread) { IsBackground = true };
t.Start();
IPCActive = true;
}
@@ -27,21 +27,21 @@ public static void Initialize()
private static void IPCThread()
{
- var pipeName = $"bizhawk-pid-{Process.GetCurrentProcess().Id}-IPCKeyInput";
+ string pipeName = $"bizhawk-pid-{Process.GetCurrentProcess().Id}-IPCKeyInput";
while (true)
{
- using var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024);
+ using NamedPipeServerStream pipe = new(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024);
try
{
pipe.WaitForConnection();
- var br = new BinaryReader(pipe);
+ BinaryReader br = new(pipe);
while (true)
{
- var e = br.ReadUInt32();
- var pressed = (e & 0x80000000) != 0;
+ uint e = br.ReadUInt32();
+ bool pressed = (e & 0x80000000) != 0;
lock (PendingEventList)
{
PendingEventList.Add(new((DistinctKey)(e & 0x7FFFFFFF), pressed));
diff --git a/src/BizHawk.Bizware.Input/SDL2/SDL2Gamepad.cs b/src/BizHawk.Bizware.Input/SDL2/SDL2Gamepad.cs
index c94eb182e4a..81b3212f6eb 100644
--- a/src/BizHawk.Bizware.Input/SDL2/SDL2Gamepad.cs
+++ b/src/BizHawk.Bizware.Input/SDL2/SDL2Gamepad.cs
@@ -62,10 +62,10 @@ public void Dispose()
private static void RefreshIndexes()
{
- var njoysticks = SDL_NumJoysticks();
- for (var i = 0; i < njoysticks; i++)
+ int njoysticks = SDL_NumJoysticks();
+ for (int i = 0; i < njoysticks; i++)
{
- var joystickId = SDL_JoystickGetDeviceInstanceID(i);
+ int joystickId = SDL_JoystickGetDeviceInstanceID(i);
if (Gamepads.TryGetValue(joystickId, out var gamepad))
{
gamepad.UpdateIndex(i);
@@ -75,10 +75,10 @@ private static void RefreshIndexes()
public static void AddDevice(int deviceIndex)
{
- var instanceId = SDL_JoystickGetDeviceInstanceID(deviceIndex);
+ int instanceId = SDL_JoystickGetDeviceInstanceID(deviceIndex);
if (!Gamepads.ContainsKey(instanceId))
{
- var gamepad = new SDL2Gamepad(deviceIndex);
+ SDL2Gamepad gamepad = new(deviceIndex);
Gamepads.Add(gamepad.InstanceID, gamepad);
}
else
@@ -183,27 +183,27 @@ public static IEnumerable EnumerateDevices()
buttonGetters.Add(("P-", () => SDL_JoystickGetAxis(Opaque, 7) <= dzn));
buttonGetters.Add(("N+", () => SDL_JoystickGetAxis(Opaque, 8) >= dzp));
buttonGetters.Add(("N-", () => SDL_JoystickGetAxis(Opaque, 8) <= dzn));
- var naxes = SDL_JoystickNumAxes(Opaque);
- for (var i = 9; i < naxes; i++)
+ int naxes = SDL_JoystickNumAxes(Opaque);
+ for (int i = 9; i < naxes; i++)
{
- var j = i;
+ int j = i;
buttonGetters.Add(($"Axis{j}+", () => SDL_JoystickGetAxis(Opaque, j) >= dzp));
buttonGetters.Add(($"Axis{j}-", () => SDL_JoystickGetAxis(Opaque, j) <= dzn));
}
// buttons
- var nbuttons = SDL_JoystickNumButtons(Opaque);
- for (var i = 0; i < nbuttons; i++)
+ int nbuttons = SDL_JoystickNumButtons(Opaque);
+ for (int i = 0; i < nbuttons; i++)
{
- var j = i;
+ int j = i;
buttonGetters.Add(($"B{i + 1}", () => SDL_JoystickGetButton(Opaque, j) == 1));
}
// hats
- var nhats = SDL_JoystickNumHats(Opaque);
- for (var i = 0; i < nhats; i++)
+ int nhats = SDL_JoystickNumHats(Opaque);
+ for (int i = 0; i < nhats; i++)
{
- var j = i;
+ int j = i;
buttonGetters.Add(($"POV{j}U", () => (SDL_JoystickGetHat(Opaque, j) & SDL_HAT_UP) == SDL_HAT_UP));
buttonGetters.Add(($"POV{j}D", () => (SDL_JoystickGetHat(Opaque, j) & SDL_HAT_DOWN) == SDL_HAT_DOWN));
buttonGetters.Add(($"POV{j}L", () => (SDL_JoystickGetHat(Opaque, j) & SDL_HAT_LEFT) == SDL_HAT_LEFT));
@@ -282,10 +282,10 @@ private SDL2Gamepad(int index)
("N", Conv(SDL_JoystickGetAxis(Opaque, 8))),
};
- var naxes = SDL_JoystickNumAxes(Opaque);
- for (var i = 9; i < naxes; i++)
+ int naxes = SDL_JoystickNumAxes(Opaque);
+ for (int i = 9; i < naxes; i++)
{
- var j = i;
+ int j = i;
values.Add(($"Axis{j}", Conv(SDL_JoystickGetAxis(Opaque, j))));
}
diff --git a/src/BizHawk.Bizware.Input/SDL2/SDL2InputAdapter.cs b/src/BizHawk.Bizware.Input/SDL2/SDL2InputAdapter.cs
index bad8f912eb0..9a0831429c0 100644
--- a/src/BizHawk.Bizware.Input/SDL2/SDL2InputAdapter.cs
+++ b/src/BizHawk.Bizware.Input/SDL2/SDL2InputAdapter.cs
@@ -38,7 +38,7 @@ static SDL2InputAdapter()
private static void DoSDLEventLoop()
{
- var e = new SDL_Event[1];
+ SDL_Event[] e = new SDL_Event[1];
// this loop somewhat models SDL_PollEvent
while (true)
{
@@ -155,9 +155,9 @@ public override void ProcessHostGamepads(Action
foreach (var pad in SDL2Gamepad.EnumerateDevices())
{
- foreach (var but in pad.ButtonGetters)
+ foreach (var (ButtonName, GetIsPressed) in pad.ButtonGetters)
{
- handleButton(pad.InputNamePrefix + but.ButtonName, but.GetIsPressed(), ClientInputFocus.Pad);
+ handleButton(pad.InputNamePrefix + ButtonName, GetIsPressed(), ClientInputFocus.Pad);
}
foreach (var (axisID, f) in pad.GetAxes())
@@ -167,8 +167,8 @@ public override void ProcessHostGamepads(Action
if (pad.HasRumble)
{
- var leftStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Left");
- var rightStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Right");
+ int leftStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Left");
+ int rightStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Right");
pad.SetVibration(leftStrength, rightStrength);
}
}
diff --git a/src/BizHawk.Bizware.Input/X11/X11KeyInput.cs b/src/BizHawk.Bizware.Input/X11/X11KeyInput.cs
index 7e8000d8503..ba06f609de9 100644
--- a/src/BizHawk.Bizware.Input/X11/X11KeyInput.cs
+++ b/src/BizHawk.Bizware.Input/X11/X11KeyInput.cs
@@ -37,7 +37,7 @@ public static void Initialize()
{
// check if we can use XKb
int major = 1, minor = 0;
- var supportsXkb = XkbQueryExtension(Display, out _, out _, out _, ref major, ref minor);
+ bool supportsXkb = XkbQueryExtension(Display, out _, out _, out _, ref major, ref minor);
if (supportsXkb)
{
@@ -66,7 +66,7 @@ public static unsafe IEnumerable Update()
{
lock (_syncObject)
{
- var keys = stackalloc byte[32];
+ byte* keys = stackalloc byte[32];
using (new XLock(Display))
{
@@ -74,10 +74,10 @@ public static unsafe IEnumerable Update()
_ = XQueryKeymap(Display, keys);
}
- var eventList = new List();
- for (var keycode = 0; keycode < 256; keycode++)
+ List eventList = new();
+ for (int keycode = 0; keycode < 256; keycode++)
{
- var keystate = (keys[keycode >> 3] >> (keycode & 0x07) & 0x01) != 0;
+ bool keystate = (keys[keycode >> 3] >> (keycode & 0x07) & 0x01) != 0;
if (LastKeyState[keycode] != keystate)
{
@@ -92,7 +92,7 @@ public static unsafe IEnumerable Update()
private static unsafe void CreateKeyMap(bool supportsXkb)
{
- for (var i = 0; i < KeyEnumMap.Length; i++)
+ for (int i = 0; i < KeyEnumMap.Length; i++)
{
KeyEnumMap[i] = DistinctKey.Unknown;
}
@@ -106,7 +106,7 @@ private static unsafe void CreateKeyMap(bool supportsXkb)
for (int i = keyboard->min_key_code; i <= keyboard->max_key_code; i++)
{
- var name = new string(keyboard->names->keys[i].name, 0, 4);
+ string name = new(keyboard->names->keys[i].name, 0, 4);
var key = name switch
{
"TLDE" => DistinctKey.OemTilde,
@@ -166,7 +166,7 @@ private static unsafe void CreateKeyMap(bool supportsXkb)
}
}
- for (var i = 0; i < KeyEnumMap.Length; i++)
+ for (int i = 0; i < KeyEnumMap.Length; i++)
{
if (KeyEnumMap[i] == DistinctKey.Unknown)
{
@@ -201,7 +201,7 @@ private static unsafe void CreateKeyMap(bool supportsXkb)
}
else
{
- var e = new XKeyEvent
+ XKeyEvent e = new()
{
display = Display,
keycode = i,
diff --git a/src/BizHawk.Client.Common/Api/ApiInjector.cs b/src/BizHawk.Client.Common/Api/ApiInjector.cs
index 352fee35669..244d2a7af2a 100644
--- a/src/BizHawk.Client.Common/Api/ApiInjector.cs
+++ b/src/BizHawk.Client.Common/Api/ApiInjector.cs
@@ -15,7 +15,7 @@ public static class ApiInjector
///
public static void ClearApis(object target)
{
- Type targetType = target.GetType();
+ var targetType = target.GetType();
object[] tmp = new object[1];
foreach (var mi in targetType.GetProperties(ReflectionExtensions.DI_TARGET_PROPS)
.Where(static pi => pi.PropertyType == typeof(ApiContainer))
@@ -37,7 +37,7 @@ public static void ClearApis(object target)
/// false if update failed
public static bool UpdateApis(IExternalApiProvider source, object target)
{
- Type targetType = target.GetType();
+ var targetType = target.GetType();
object[] tmp = new object[1];
foreach (var mi in targetType.GetProperties(ReflectionExtensions.DI_TARGET_PROPS)
diff --git a/src/BizHawk.Client.Common/Api/BizHawkSystemIdToCoreSystemEnumConverter.cs b/src/BizHawk.Client.Common/Api/BizHawkSystemIdToCoreSystemEnumConverter.cs
index 4776ff0de6c..484fd661fc0 100644
--- a/src/BizHawk.Client.Common/Api/BizHawkSystemIdToCoreSystemEnumConverter.cs
+++ b/src/BizHawk.Client.Common/Api/BizHawkSystemIdToCoreSystemEnumConverter.cs
@@ -76,10 +76,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn
/// you want to convert
/// A that is equivalent to BizHawk SystemId
/// Thrown when SystemId hasn't been found
- public CoreSystem Convert(string value)
- {
- return (CoreSystem)Convert(value, null, null, CultureInfo.CurrentCulture);
- }
+ public CoreSystem Convert(string value) => (CoreSystem)Convert(value, null, null, CultureInfo.CurrentCulture);
///
@@ -142,9 +139,6 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu
/// you want to convert
/// A that is used by BizHawk SystemId
/// Thrown when hasn't been found
- public string ConvertBack(CoreSystem value)
- {
- return (string)ConvertBack(value, null, null, CultureInfo.CurrentCulture);
- }
+ public string ConvertBack(CoreSystem value) => (string)ConvertBack(value, null, null, CultureInfo.CurrentCulture);
}
}
diff --git a/src/BizHawk.Client.Common/Api/Classes/CommApi.cs b/src/BizHawk.Client.Common/Api/Classes/CommApi.cs
index 9888dffc184..c201e2804bc 100644
--- a/src/BizHawk.Client.Common/Api/Classes/CommApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/CommApi.cs
@@ -4,7 +4,7 @@ namespace BizHawk.Client.Common
{
public sealed class CommApi : ICommApi
{
- private static readonly WebSocketServer _wsServer = new WebSocketServer();
+ private static readonly WebSocketServer _wsServer = new();
private readonly (HttpCommunication? HTTP, MemoryMappedFiles MMF, SocketServer? Sockets) _networkingHelpers;
diff --git a/src/BizHawk.Client.Common/Api/Classes/EmuClientApi.cs b/src/BizHawk.Client.Common/Api/Classes/EmuClientApi.cs
index 745bef098a5..969be547f2e 100644
--- a/src/BizHawk.Client.Common/Api/Classes/EmuClientApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/EmuClientApi.cs
@@ -114,7 +114,7 @@ public void OnBeforeQuickLoad(object sender, string quickSaveSlotName, out bool
eventHandled = false;
return;
}
- var e = new BeforeQuickLoadEventArgs(quickSaveSlotName);
+ BeforeQuickLoadEventArgs e = new(quickSaveSlotName);
BeforeQuickLoad(sender, e);
eventHandled = e.Handled;
}
@@ -126,15 +126,12 @@ public void OnBeforeQuickSave(object sender, string quickSaveSlotName, out bool
eventHandled = false;
return;
}
- var e = new BeforeQuickSaveEventArgs(quickSaveSlotName);
+ BeforeQuickSaveEventArgs e = new(quickSaveSlotName);
BeforeQuickSave(sender, e);
eventHandled = e.Handled;
}
- public void OnRomLoaded()
- {
- RomLoaded?.Invoke(null, EventArgs.Empty);
- }
+ public void OnRomLoaded() => RomLoaded?.Invoke(null, EventArgs.Empty);
public void OnStateLoaded(object sender, string stateName) => StateLoaded?.Invoke(sender, new StateLoadedEventArgs(stateName));
@@ -167,7 +164,7 @@ public void Screenshot(string path)
public void SeekFrame(int frame)
{
- var wasPaused = _mainForm.EmulatorPaused;
+ bool wasPaused = _mainForm.EmulatorPaused;
while (Emulator.Frame != frame) _mainForm.SeekFrameAdvance();
if (!wasPaused) _mainForm.UnpauseEmulator();
}
@@ -195,7 +192,7 @@ public void SetSoundOn(bool enable)
public void SetWindowSize(int size)
{
- if (size == 1 || size == 2 || size == 3 || size == 4 || size == 5 || size == 10)
+ if (size is 1 or 2 or 3 or 4 or 5 or 10)
{
_config.TargetZoomFactors[Emulator.SystemId] = size;
_mainForm.FrameBufferResized();
diff --git a/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs b/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs
index a7b43629806..69107b09c96 100644
--- a/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs
@@ -79,10 +79,10 @@ public int FrameCount()
{
if (DisassemblableCore != null)
{
- var disasm = DisassemblableCore.Disassemble(
+ string disasm = DisassemblableCore.Disassemble(
string.IsNullOrEmpty(name) ? MemoryDomains!.SystemBus : MemoryDomains![name!]!,
pc,
- out var l
+ out int l
);
return (disasm, l);
}
@@ -113,7 +113,7 @@ public IReadOnlyDictionary GetRegisters()
{
if (DebuggableCore != null)
{
- var table = new Dictionary();
+ Dictionary table = new();
foreach (var (name, rv) in DebuggableCore.GetCpuFlagsAndRegisters()) table[name] = rv.Value;
return table;
}
@@ -290,7 +290,7 @@ void SetQuickNES(QuickNES quicknes)
{
var s = quicknes.GetSettings();
// this core doesn't support disabling BG
- var showSp = GetSetting(args, 0);
+ bool showSp = GetSetting(args, 0);
if (showSp && s.NumSprites == 0) s.NumSprites = 8;
else if (!showSp && s.NumSprites > 0) s.NumSprites = 0;
quicknes.PutSettings(s);
diff --git a/src/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs b/src/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs
index 6e6dedc5f01..5dccfaf7018 100644
--- a/src/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs
@@ -27,7 +27,7 @@ public string GetBoardType()
public IReadOnlyDictionary GetOptions()
{
- var options = new Dictionary();
+ Dictionary options = new();
if (_game == null) return options;
foreach (var (k, v) in ((GameInfo) _game).GetOptions()) options[k] = v;
return options;
diff --git a/src/BizHawk.Client.Common/Api/Classes/GuiApi.cs b/src/BizHawk.Client.Common/Api/Classes/GuiApi.cs
index 3d1357b4ef1..ef230b2608b 100644
--- a/src/BizHawk.Client.Common/Api/Classes/GuiApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/GuiApi.cs
@@ -25,15 +25,15 @@ public sealed class GuiApi : IGuiApi
private readonly DisplayManagerBase _displayManager;
- private readonly Dictionary _imageCache = new Dictionary();
+ private readonly Dictionary _imageCache = new();
- private readonly Bitmap _nullGraphicsBitmap = new Bitmap(1, 1);
+ private readonly Bitmap _nullGraphicsBitmap = new(1, 1);
- private readonly Dictionary _pens = new Dictionary();
+ private readonly Dictionary _pens = new();
- private readonly Dictionary _solidBrushes = new Dictionary();
+ private readonly Dictionary _solidBrushes = new();
- private ImageAttributes _attributes = new ImageAttributes();
+ private ImageAttributes _attributes = new();
private CompositingMode _compositingMode = CompositingMode.SourceOver;
@@ -478,8 +478,8 @@ public void DrawPolygon(Point[] points, Color? line = null, Color? background =
public void DrawRectangle(int x, int y, int width, int height, Color? line = null, Color? background = null, DisplaySurfaceID? surfaceID = null)
{
using var g = GetGraphics(surfaceID);
- var w = Math.Max(width, 0.1F);
- var h = Math.Max(height, 0.1F);
+ float w = Math.Max(width, 0.1F);
+ float h = Math.Max(height, 0.1F);
g.DrawRectangle(GetPen(line ?? _defaultForeground), x, y, w, h);
var bg = background ?? _defaultBackground;
if (bg != null) g.FillRectangle(GetBrush(bg.Value), x + 1, y + 1, Math.Max(w - 1, 0), Math.Max(h - 1, 0));
@@ -504,8 +504,8 @@ public void DrawString(int x, int y, string message, Color? forecolor = null, Co
// The text isn't written out using GenericTypographic, so measuring it using GenericTypographic seemed to make it worse.
// And writing it out with GenericTypographic just made it uglier. :p
- var font = new Font(family, fontsize ?? 12, fstyle, GraphicsUnit.Pixel);
- var sizeOfText = g.MeasureString(message, font, 0, new StringFormat(StringFormat.GenericDefault)).ToSize();
+ Font font = new(family, fontsize ?? 12, fstyle, GraphicsUnit.Pixel);
+ Size sizeOfText = g.MeasureString(message, font, 0, new StringFormat(StringFormat.GenericDefault)).ToSize();
switch (horizalign?.ToLowerInvariant())
{
@@ -539,7 +539,7 @@ public void DrawString(int x, int y, string message, Color? forecolor = null, Co
if (bg != null)
{
var brush = GetBrush(bg.Value);
- for (var xd = -1; xd <= 1; xd++) for (var yd = -1; yd <= 1; yd++)
+ for (int xd = -1; xd <= 1; xd++) for (int yd = -1; yd <= 1; yd++)
{
g.DrawString(message, font, brush, x + xd, y + yd);
}
@@ -595,8 +595,8 @@ public void PixelText(
break;
}
using var g = GetGraphics(surfaceID);
- var font = new Font(_displayManager.CustomFonts.Families[index], 8, FontStyle.Regular, GraphicsUnit.Pixel);
- var sizeOfText = g.MeasureString(message, font, width: 0, PixelTextFormat).ToSize();
+ Font font = new(_displayManager.CustomFonts.Families[index], 8, FontStyle.Regular, GraphicsUnit.Pixel);
+ Size sizeOfText = g.MeasureString(message, font, width: 0, PixelTextFormat).ToSize();
if (backcolor.HasValue) g.FillRectangle(GetBrush(backcolor.Value), new Rectangle(new Point(x, y), sizeOfText + new Size(1, 0)));
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
g.DrawString(message, font, GetBrush(forecolor ?? _defaultForeground), x + 1, y, PixelTextFormat);
@@ -632,7 +632,7 @@ public void Text(int x, int y, string message, Color? forecolor = null, string a
y -= oy;
}
- var pos = new MessagePosition{ X = x, Y = y, Anchor = (MessagePosition.AnchorType)a };
+ MessagePosition pos = new() { X = x, Y = y, Anchor = (MessagePosition.AnchorType)a };
_displayManager.OSD.AddGuiText(message, pos, Color.Black, forecolor ?? Color.White);
}
diff --git a/src/BizHawk.Client.Common/Api/Classes/InputApi.cs b/src/BizHawk.Client.Common/Api/Classes/InputApi.cs
index 9b7d2676c4e..c61d27e28a8 100644
--- a/src/BizHawk.Client.Common/Api/Classes/InputApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/InputApi.cs
@@ -19,7 +19,7 @@ public InputApi(DisplayManagerBase displayManager, InputManager inputManager)
public Dictionary Get()
{
- var buttons = new Dictionary();
+ Dictionary buttons = new();
foreach (var (button, _) in _inputManager.ControllerInputCoalescer.BoolButtons().Where(kvp => kvp.Value)) buttons[button] = true;
return buttons;
}
diff --git a/src/BizHawk.Client.Common/Api/Classes/JoypadApi.cs b/src/BizHawk.Client.Common/Api/Classes/JoypadApi.cs
index 91b6aebb3d7..e5aeb0ad6de 100644
--- a/src/BizHawk.Client.Common/Api/Classes/JoypadApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/JoypadApi.cs
@@ -21,20 +21,11 @@ public JoypadApi(Action logCallback, InputManager inputManager, IMovieSe
_movieSession = movieSession;
}
- public IReadOnlyDictionary Get(int? controller = null)
- {
- return _inputManager.AutofireStickyXorAdapter.ToDictionary(controller);
- }
+ public IReadOnlyDictionary Get(int? controller = null) => _inputManager.AutofireStickyXorAdapter.ToDictionary(controller);
- public IReadOnlyDictionary GetWithMovie(int? controller = null)
- {
- return _inputManager.ControllerOutput.ToDictionary(controller);
- }
+ public IReadOnlyDictionary GetWithMovie(int? controller = null) => _inputManager.ControllerOutput.ToDictionary(controller);
- public IReadOnlyDictionary GetImmediate(int? controller = null)
- {
- return _inputManager.ActiveController.ToDictionary(controller);
- }
+ public IReadOnlyDictionary GetImmediate(int? controller = null) => _inputManager.ActiveController.ToDictionary(controller);
public void SetFromMnemonicStr(string inputLogEntry)
{
@@ -48,17 +39,17 @@ public void SetFromMnemonicStr(string inputLogEntry)
LogCallback($"invalid mnemonic string: {inputLogEntry}");
return;
}
- foreach (var button in controller.Definition.BoolButtons) _inputManager.ButtonOverrideAdapter.SetButton(button, controller.IsPressed(button));
- foreach (var axis in controller.Definition.Axes.Keys) _inputManager.ButtonOverrideAdapter.SetAxis(axis, controller.AxisValue(axis));
+ foreach (string button in controller.Definition.BoolButtons) _inputManager.ButtonOverrideAdapter.SetButton(button, controller.IsPressed(button));
+ foreach (string axis in controller.Definition.Axes.Keys) _inputManager.ButtonOverrideAdapter.SetAxis(axis, controller.AxisValue(axis));
}
public void Set(IReadOnlyDictionary buttons, int? controller = null)
{
// If a controller is specified, we need to iterate over unique button names. If not, we iterate over
// ALL button names with P{controller} prefixes
- foreach (var button in _inputManager.ActiveController.ToBoolButtonNameList(controller))
+ foreach (string button in _inputManager.ActiveController.ToBoolButtonNameList(controller))
{
- Set(button, buttons.TryGetValue(button, out var state) ? state : null, controller);
+ Set(button, buttons.TryGetValue(button, out bool state) ? state : null, controller);
}
}
@@ -66,7 +57,7 @@ public void Set(string button, bool? state = null, int? controller = null)
{
try
{
- var buttonToSet = controller == null ? button : $"P{controller} {button}";
+ string buttonToSet = controller == null ? button : $"P{controller} {button}";
if (state == null) _inputManager.ButtonOverrideAdapter.UnSet(buttonToSet);
else _inputManager.ButtonOverrideAdapter.SetButton(buttonToSet, state.Value);
diff --git a/src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs b/src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs
index 5ce463ff57e..24b19b4b5c4 100644
--- a/src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs
@@ -28,7 +28,7 @@ MemoryDomain LazyInit()
{
if (MemoryDomainCore == null)
{
- var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
+ string error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
LogCallback(error);
throw new NotImplementedException(error);
}
@@ -46,7 +46,7 @@ public IMemoryDomains DomainList
{
if (MemoryDomainCore == null)
{
- var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
+ string error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
LogCallback(error);
throw new NotImplementedException(error);
}
@@ -60,7 +60,7 @@ public string MainMemoryName
{
if (MemoryDomainCore == null)
{
- var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
+ string error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
LogCallback(error);
throw new NotImplementedException(error);
}
@@ -90,32 +90,32 @@ private MemoryDomain NamedDomainOrCurrent(string name)
private static int U2S(uint u, int size)
{
- var sh = 8 * (4 - size);
+ int sh = 8 * (4 - size);
return ((int) u << sh) >> sh;
}
private uint ReadUnsignedLittle(long addr, int size, string domain = null)
{
uint v = 0;
- for (var i = 0; i < size; i++) v |= ReadUnsigned(addr + i, 1, domain) << (8 * i);
+ for (int i = 0; i < size; i++) v |= ReadUnsigned(addr + i, 1, domain) << (8 * i);
return v;
}
private uint ReadUnsignedBig(long addr, int size, string domain = null)
{
uint v = 0;
- for (var i = 0; i < size; i++) v |= ReadUnsigned(addr + i, 1, domain) << (8 * (size - 1 - i));
+ for (int i = 0; i < size; i++) v |= ReadUnsigned(addr + i, 1, domain) << (8 * (size - 1 - i));
return v;
}
private void WriteUnsignedLittle(long addr, uint v, int size, string domain = null)
{
- for (var i = 0; i < size; i++) WriteUnsigned(addr + i, (v >> (8 * i)) & 0xFF, 1, domain);
+ for (int i = 0; i < size; i++) WriteUnsigned(addr + i, (v >> (8 * i)) & 0xFF, 1, domain);
}
private void WriteUnsignedBig(long addr, uint v, int size, string domain = null)
{
- for (var i = 0; i < size; i++) WriteUnsigned(addr + i, (v >> (8 * (size - 1 - i))) & 0xFF, 1, domain);
+ for (int i = 0; i < size; i++) WriteUnsigned(addr + i, (v >> (8 * (size - 1 - i))) & 0xFF, 1, domain);
}
private int ReadSigned(long addr, int size, string domain = null) => U2S(ReadUnsigned(addr, size, domain), size);
@@ -220,17 +220,17 @@ public string HashRegion(long addr, int count, string domain = null)
var d = NamedDomainOrCurrent(domain);
if (!0L.RangeToExclusive(d.Size).Contains(addr))
{
- var error = $"Address {addr} is outside the bounds of domain {d.Name}";
+ string error = $"Address {addr} is outside the bounds of domain {d.Name}";
LogCallback(error);
throw new ArgumentOutOfRangeException(error);
}
if (addr + count > d.Size)
{
- var error = $"Address {addr} + count {count} is outside the bounds of domain {d.Name}";
+ string error = $"Address {addr} + count {count} is outside the bounds of domain {d.Name}";
LogCallback(error);
throw new ArgumentOutOfRangeException(error);
}
- var data = new byte[count];
+ byte[] data = new byte[count];
using (d.EnterExit())
{
d.BulkPeekByte(addr.RangeToExclusive(addr + count), data);
@@ -246,15 +246,15 @@ public IReadOnlyList ReadByteRange(long addr, int length, string domain =
{
var d = NamedDomainOrCurrent(domain);
if (addr < 0) LogCallback($"Warning: Attempted reads on addresses {addr}..-1 outside range of domain {d.Name} in {nameof(ReadByteRange)}()");
- var lastReqAddr = addr + length - 1;
- var indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L;
- var iSrc = Math.Min(Math.Max(0L, addr), d.Size);
- var iDst = iSrc - addr;
- var bytes = new byte[indexAfterLast - iSrc];
+ long lastReqAddr = addr + length - 1;
+ long indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L;
+ long iSrc = Math.Min(Math.Max(0L, addr), d.Size);
+ long iDst = iSrc - addr;
+ byte[] bytes = new byte[indexAfterLast - iSrc];
if (iSrc < indexAfterLast) using (d.EnterExit()) d.BulkPeekByte(iSrc.RangeToExclusive(indexAfterLast), bytes);
if (lastReqAddr >= d.Size) LogCallback($"Warning: Attempted reads on addresses {d.Size}..{lastReqAddr} outside range of domain {d.Name} in {nameof(ReadByteRange)}()");
if (bytes.Length == length) return bytes;
- var newBytes = new byte[length];
+ byte[] newBytes = new byte[length];
if (bytes.Length is not 0) Array.Copy(sourceArray: bytes, sourceIndex: 0, destinationArray: newBytes, destinationIndex: iDst, length: bytes.Length);
return newBytes;
}
@@ -268,10 +268,10 @@ public void WriteByteRange(long addr, IReadOnlyList memoryblock, string do
return;
}
if (addr < 0) LogCallback($"Warning: Attempted writes on addresses {addr}..-1 outside range of domain {d.Name} in {nameof(WriteByteRange)}()");
- var lastReqAddr = addr + memoryblock.Count - 1;
- var indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L;
- var iDst = Math.Min(Math.Max(0L, addr), d.Size);
- var iSrc = checked((int) (iDst - addr));
+ long lastReqAddr = addr + memoryblock.Count - 1;
+ long indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L;
+ long iDst = Math.Min(Math.Max(0L, addr), d.Size);
+ int iSrc = checked((int) (iDst - addr));
using (d.EnterExit())
{
while (iDst < indexAfterLast) d.PokeByte(iDst++, memoryblock[iSrc++]);
diff --git a/src/BizHawk.Client.Common/Api/Classes/MemorySaveStateApi.cs b/src/BizHawk.Client.Common/Api/Classes/MemorySaveStateApi.cs
index d8a89a29a2d..d117d9a741a 100644
--- a/src/BizHawk.Client.Common/Api/Classes/MemorySaveStateApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/MemorySaveStateApi.cs
@@ -11,20 +11,20 @@ public sealed class MemorySaveStateApi : IMemorySaveStateApi
private readonly Action LogCallback;
- private readonly Dictionary _memorySavestates = new Dictionary();
+ private readonly Dictionary _memorySavestates = new();
public MemorySaveStateApi(Action logCallback) => LogCallback = logCallback;
public string SaveCoreStateToMemory()
{
- var guid = Guid.NewGuid();
+ Guid guid = Guid.NewGuid();
_memorySavestates.Add(guid, StatableCore.CloneSavestate());
return guid.ToString();
}
public void LoadCoreStateFromMemory(string identifier)
{
- var guid = new Guid(identifier);
+ Guid guid = new(identifier);
try
{
StatableCore.LoadStateBinary(_memorySavestates[guid]);
diff --git a/src/BizHawk.Client.Common/Api/Classes/SQLiteApi.cs b/src/BizHawk.Client.Common/Api/Classes/SQLiteApi.cs
index 2b612af4647..08913ab2900 100644
--- a/src/BizHawk.Client.Common/Api/Classes/SQLiteApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/SQLiteApi.cs
@@ -31,7 +31,7 @@ public string OpenDatabase(string name)
_dbConnection?.Dispose();
_dbConnection = new(new SqliteConnectionStringBuilder { DataSource = name }.ToString());
_dbConnection.Open();
- using var initCmds = new SqliteCommand(null, _dbConnection);
+ using SqliteCommand initCmds = new(null, _dbConnection);
// Allows for reads and writes to happen at the same time
initCmds.CommandText = "PRAGMA journal_mode = 'wal'";
initCmds.ExecuteNonQuery();
@@ -55,7 +55,7 @@ public string WriteCommand(string query = null)
try
{
_dbConnection.Open();
- using var cmd = new SqliteCommand(query, _dbConnection);
+ using SqliteCommand cmd = new(query, _dbConnection);
cmd.ExecuteNonQuery();
result = "Command ran successfully";
}
@@ -75,14 +75,14 @@ public object ReadCommand(string query = null)
try
{
_dbConnection.Open();
- using var command = new SqliteCommand($"PRAGMA read_uncommitted =1;{query}", _dbConnection);
+ using SqliteCommand command = new($"PRAGMA read_uncommitted =1;{query}", _dbConnection);
using var reader = command.ExecuteReader();
if (reader.HasRows)
{
- var columns = new string[reader.FieldCount];
+ string[] columns = new string[reader.FieldCount];
for (int i = 0, l = reader.FieldCount; i < l; i++) columns[i] = reader.GetName(i);
long rowCount = 0;
- var table = new Dictionary();
+ Dictionary table = new();
while (reader.Read())
{
for (int i = 0, l = reader.FieldCount; i < l; i++) table[$"{columns[i]} {rowCount}"] = reader.GetValue(i);
diff --git a/src/BizHawk.Client.Common/Api/Classes/UserDataApi.cs b/src/BizHawk.Client.Common/Api/Classes/UserDataApi.cs
index 91e1d0e45fa..87441f1485a 100644
--- a/src/BizHawk.Client.Common/Api/Classes/UserDataApi.cs
+++ b/src/BizHawk.Client.Common/Api/Classes/UserDataApi.cs
@@ -29,7 +29,7 @@ public void Set(string name, object value)
_movieSession.UserBag[name] = value;
}
- public object Get(string key) => _movieSession.UserBag.TryGetValue(key, out var value) ? value : null;
+ public object Get(string key) => _movieSession.UserBag.TryGetValue(key, out object value) ? value : null;
public void Clear() => _movieSession.UserBag.Clear();
diff --git a/src/BizHawk.Client.Common/Api/ClientWebSocketWrapper.cs b/src/BizHawk.Client.Common/Api/ClientWebSocketWrapper.cs
index 9f754573936..6dd09109752 100644
--- a/src/BizHawk.Client.Common/Api/ClientWebSocketWrapper.cs
+++ b/src/BizHawk.Client.Common/Api/ClientWebSocketWrapper.cs
@@ -13,7 +13,7 @@ public struct ClientWebSocketWrapper
private ClientWebSocket? _w;
/// calls getter (unless closed/disposed, then is always returned)
- public WebSocketState State => _w?.State ?? WebSocketState.Closed;
+ public readonly WebSocketState State => _w?.State ?? WebSocketState.Closed;
public ClientWebSocketWrapper(Uri uri, CancellationToken? cancellationToken = null)
{
@@ -33,26 +33,26 @@ public Task Close(WebSocketCloseStatus closeStatus, string statusDescription, Ca
}
/// calls
- public Task Receive(ArraySegment buffer, CancellationToken? cancellationToken = null)
+ public readonly Task Receive(ArraySegment buffer, CancellationToken? cancellationToken = null)
=> _w?.ReceiveAsync(buffer, cancellationToken ?? CancellationToken.None)
?? throw new ObjectDisposedException(nameof(_w));
/// calls
- public string Receive(int bufferCap, CancellationToken? cancellationToken = null)
+ public readonly string Receive(int bufferCap, CancellationToken? cancellationToken = null)
{
if (_w == null) throw new ObjectDisposedException(nameof(_w));
- var buffer = new byte[bufferCap];
+ byte[] buffer = new byte[bufferCap];
var result = Receive(new ArraySegment(buffer), cancellationToken ?? CancellationToken.None).Result;
return Encoding.UTF8.GetString(buffer, 0, result.Count);
}
/// calls
- public Task Send(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken? cancellationToken = null)
+ public readonly Task Send(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken? cancellationToken = null)
=> _w?.SendAsync(buffer, messageType, endOfMessage, cancellationToken ?? CancellationToken.None)
?? throw new ObjectDisposedException(nameof(_w));
/// calls
- public Task Send(string message, bool endOfMessage, CancellationToken? cancellationToken = null)
+ public readonly Task Send(string message, bool endOfMessage, CancellationToken? cancellationToken = null)
{
if (_w == null) throw new ObjectDisposedException(nameof(_w));
return Send(
diff --git a/src/BizHawk.Client.Common/Api/HttpCommunication.cs b/src/BizHawk.Client.Common/Api/HttpCommunication.cs
index 1270b8d058c..b3d6d0f96e9 100644
--- a/src/BizHawk.Client.Common/Api/HttpCommunication.cs
+++ b/src/BizHawk.Client.Common/Api/HttpCommunication.cs
@@ -7,7 +7,7 @@ namespace BizHawk.Client.Common
{
public sealed class HttpCommunication
{
- private readonly HttpClient _client = new HttpClient();
+ private readonly HttpClient _client = new();
private readonly Func _takeScreenshotCallback;
@@ -66,10 +66,10 @@ public async Task Post(string url, FormUrlEncodedContent content)
public string SendScreenshot(string url = null, string parameter = "screenshot")
{
- var url1 = url ?? PostUrl;
- var content = new FormUrlEncodedContent(new Dictionary { [parameter] = Convert.ToBase64String(_takeScreenshotCallback()) });
+ string url1 = url ?? PostUrl;
+ FormUrlEncodedContent content = new(new Dictionary { [parameter] = Convert.ToBase64String(_takeScreenshotCallback()) });
Task postResponse = null;
- var trials = 5;
+ int trials = 5;
while (postResponse == null && trials > 0)
{
postResponse = Post(url1, content);
diff --git a/src/BizHawk.Client.Common/Api/MemoryMappedFiles.cs b/src/BizHawk.Client.Common/Api/MemoryMappedFiles.cs
index 669f0ce024f..065bc48ff61 100644
--- a/src/BizHawk.Client.Common/Api/MemoryMappedFiles.cs
+++ b/src/BizHawk.Client.Common/Api/MemoryMappedFiles.cs
@@ -9,7 +9,7 @@ namespace BizHawk.Client.Common
{
public sealed class MemoryMappedFiles
{
- private readonly Dictionary _mmfFiles = new Dictionary();
+ private readonly Dictionary _mmfFiles = new();
private readonly Func _takeScreenshotCallback;
@@ -23,7 +23,7 @@ public MemoryMappedFiles(Func takeScreenshotCallback, string filename)
public string ReadFromFile(string filename, int expectedSize)
{
- var bytes = ReadBytesFromFile(filename, expectedSize);
+ byte[] bytes = ReadBytesFromFile(filename, expectedSize);
return Encoding.UTF8.GetString(bytes);
}
@@ -31,7 +31,7 @@ public byte[] ReadBytesFromFile(string filename, int expectedSize)
{
var mmfFile = _mmfFiles.GetValueOrPut(filename, MemoryMappedFile.OpenExisting);
using var viewAccessor = mmfFile.CreateViewAccessor(0, expectedSize, MemoryMappedFileAccess.Read);
- var bytes = new byte[expectedSize];
+ byte[] bytes = new byte[expectedSize];
viewAccessor.ReadArray(0, bytes, 0, expectedSize);
return bytes;
}
diff --git a/src/BizHawk.Client.Common/Api/SocketServer.cs b/src/BizHawk.Client.Common/Api/SocketServer.cs
index ba8e7b7e64c..793aa2db03d 100644
--- a/src/BizHawk.Client.Common/Api/SocketServer.cs
+++ b/src/BizHawk.Client.Common/Api/SocketServer.cs
@@ -103,7 +103,7 @@ public string ReceiveString(Encoding encoding = null)
{
//build length of string into a string
byte[] oneByte = new byte[1];
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
for (; ; )
{
int recvd = _soc.Receive(oneByte, 1, 0);
@@ -150,9 +150,9 @@ public int SendBytes(byte[] sendBytes)
public string SendScreenshot(int waitingTime = 0)
{
- var bmpBytes = PrefixWithLength(_takeScreenshotCallback());
- var sentBytes = 0;
- var tries = 0;
+ byte[] bmpBytes = PrefixWithLength(_takeScreenshotCallback());
+ int sentBytes = 0;
+ int tries = 0;
while (sentBytes <= 0 && tries < Retries)
{
try
@@ -176,13 +176,13 @@ public string SendScreenshot(int waitingTime = 0)
{
return Successful ? "Screenshot was sent" : "Screenshot could not be sent";
}
- var resp = ReceiveString();
+ string resp = ReceiveString();
return resp == "" ? "Failed to get a response" : resp;
}
public int SendString(string sendString, Encoding encoding = null)
{
- var sentBytes = SendBytes(PrefixWithLength((encoding ?? Encoding.UTF8).GetBytes(sendString)));
+ int sentBytes = SendBytes(PrefixWithLength((encoding ?? Encoding.UTF8).GetBytes(sendString)));
Successful = sentBytes > 0;
return sentBytes;
}
diff --git a/src/BizHawk.Client.Common/Api/WebSocketServer.cs b/src/BizHawk.Client.Common/Api/WebSocketServer.cs
index da6a34a5100..505cff473d0 100644
--- a/src/BizHawk.Client.Common/Api/WebSocketServer.cs
+++ b/src/BizHawk.Client.Common/Api/WebSocketServer.cs
@@ -7,6 +7,6 @@ namespace BizHawk.Client.Common
{
public sealed class WebSocketServer
{
- public ClientWebSocketWrapper Open(Uri uri, CancellationToken? cancellationToken = null) => new ClientWebSocketWrapper(uri, cancellationToken);
+ public ClientWebSocketWrapper Open(Uri uri, CancellationToken? cancellationToken = null) => new(uri, cancellationToken);
}
}
diff --git a/src/BizHawk.Client.Common/ArgParser.cs b/src/BizHawk.Client.Common/ArgParser.cs
index 0d8350edd3e..3ebfa7a564c 100644
--- a/src/BizHawk.Client.Common/ArgParser.cs
+++ b/src/BizHawk.Client.Common/ArgParser.cs
@@ -48,19 +48,19 @@ public static void ParseArguments(out ParsedCLIFlags parsed, string[] args)
List<(string Key, string Value)>? userdataUnparsedPairs = null;
string? cmdRom = null;
- for (var i = 0; i < args.Length; i++)
+ for (int i = 0; i < args.Length; i++)
{
- var arg = args[i];
+ string arg = args[i];
if (arg == ">")
{
// For some reason sometimes visual studio will pass this to us on the commandline. it makes no sense.
- var stdout = args[++i];
+ string stdout = args[++i];
Console.SetOut(new StreamWriter(stdout));
continue;
}
- var argDowncased = arg.ToLowerInvariant();
+ string argDowncased = arg.ToLowerInvariant();
if (argDowncased.StartsWithOrdinal("--load-slot="))
{
cmdLoadSlot = argDowncased.Substring(argDowncased.IndexOf('=') + 1);
@@ -104,7 +104,7 @@ public static void ParseArguments(out ParsedCLIFlags parsed, string[] args)
}
else if (argDowncased.StartsWithOrdinal("--dump-length="))
{
- var len = int.TryParse(argDowncased.Substring(argDowncased.IndexOf('=') + 1), out var i1) ? i1 : default;
+ int len = int.TryParse(argDowncased.Substring(argDowncased.IndexOf('=') + 1), out int i1) ? i1 : default;
autoDumpLength = len;
}
else if (argDowncased.StartsWithOrdinal("--dump-close"))
@@ -131,7 +131,7 @@ public static void ParseArguments(out ParsedCLIFlags parsed, string[] args)
}
else if (argDowncased.StartsWithOrdinal("--socket_port="))
{
- var port = int.TryParse(argDowncased.Substring(argDowncased.IndexOf('=') + 1), out var i1) ? i1 : default;
+ int port = int.TryParse(argDowncased.Substring(argDowncased.IndexOf('=') + 1), out int i1) ? i1 : default;
if (port > 0) socketPort = port;
}
else if (argDowncased.StartsWithOrdinal("--socket_ip="))
@@ -168,9 +168,9 @@ public static void ParseArguments(out ParsedCLIFlags parsed, string[] args)
else if (argDowncased.StartsWithOrdinal("--userdata="))
{
userdataUnparsedPairs = new();
- foreach (var s in arg.Substring(11).Split(';'))
+ foreach (string? s in arg.Substring(11).Split(';'))
{
- var iColon = s.IndexOf(':');
+ int iColon = s.IndexOf(':');
if (iColon is -1) throw new ArgParserException("malformed userdata (';' without ':')");
userdataUnparsedPairs.Add((s.Substring(startIndex: 0, length: iColon), s.Substring(iColon + 1)));
}
diff --git a/src/BizHawk.Client.Common/BreakpointList.cs b/src/BizHawk.Client.Common/BreakpointList.cs
index b43df421ae7..d88b5763a7e 100644
--- a/src/BizHawk.Client.Common/BreakpointList.cs
+++ b/src/BizHawk.Client.Common/BreakpointList.cs
@@ -9,10 +9,7 @@ public class BreakpointList : List
{
public MemoryCallbackDelegate Callback { get; set; }
- public void Add(IDebuggable core, string scope, uint address, uint mask, MemoryCallbackType type)
- {
- Add(new Breakpoint(core, scope, Callback, address, mask, type));
- }
+ public void Add(IDebuggable core, string scope, uint address, uint mask, MemoryCallbackType type) => Add(new Breakpoint(core, scope, Callback, address, mask, type));
public new void Clear()
{
@@ -50,7 +47,7 @@ public void Add(IDebuggable core, string scope, uint address, uint mask, MemoryC
public new int RemoveAll(Predicate match)
{
- var removeCount = 0;
+ int removeCount = 0;
foreach (var breakpoint in this)
{
if (match(breakpoint))
@@ -157,15 +154,9 @@ public bool Active
}
}
- private void AddCallback()
- {
- _core.MemoryCallbacks.Add(new MemoryCallback(Scope, Type, Name, DoCallback, Address, AddressMask));
- }
+ private void AddCallback() => _core.MemoryCallbacks.Add(new MemoryCallback(Scope, Type, Name, DoCallback, Address, AddressMask));
- private void RemoveCallback()
- {
- _core.MemoryCallbacks.Remove(DoCallback);
- }
+ private void RemoveCallback() => _core.MemoryCallbacks.Remove(DoCallback);
private void DoCallback(uint address, uint value, uint flags)
=> Callback(address, value, flags);
diff --git a/src/BizHawk.Client.Common/Controller.cs b/src/BizHawk.Client.Common/Controller.cs
index df66988c532..168f088ae07 100644
--- a/src/BizHawk.Client.Common/Controller.cs
+++ b/src/BizHawk.Client.Common/Controller.cs
@@ -19,7 +19,7 @@ public Controller(ControllerDefinition definition)
_axes[k] = v.Neutral;
_axisRanges[k] = v;
}
- foreach (var channel in Definition.HapticsChannels) _haptics[channel] = 0;
+ foreach (string channel in Definition.HapticsChannels) _haptics[channel] = 0;
}
public ControllerDefinition Definition { get; }
@@ -33,13 +33,13 @@ public Controller(ControllerDefinition definition)
public void SetHapticChannelStrength(string name, int strength) => _haptics[name] = strength;
- private readonly WorkingDictionary> _bindings = new WorkingDictionary>();
- private readonly WorkingDictionary _buttons = new WorkingDictionary();
- private readonly WorkingDictionary _axes = new WorkingDictionary();
+ private readonly WorkingDictionary> _bindings = new();
+ private readonly WorkingDictionary _buttons = new();
+ private readonly WorkingDictionary _axes = new();
private readonly Dictionary _axisRanges = new WorkingDictionary();
- private readonly Dictionary _axisBindings = new Dictionary();
+ private readonly Dictionary _axisBindings = new();
private readonly Dictionary _haptics = new WorkingDictionary();
- private readonly Dictionary _feedbackBindings = new Dictionary();
+ private readonly Dictionary _feedbackBindings = new();
public bool this[string button] => IsPressed(button);
@@ -64,7 +64,7 @@ public void LatchFromPhysical(IController finalHostController)
foreach (var (k, v) in _bindings)
{
_buttons[k] = false;
- foreach (var button in v)
+ foreach (string button in v)
{
if (finalHostController.IsPressed(button))
{
@@ -76,10 +76,10 @@ public void LatchFromPhysical(IController finalHostController)
foreach (var (k, v) in _axisBindings)
{
// values from finalHostController are ints in -10000..10000 (or 0..10000), so scale to -1..1, using floats to keep fractional part
- var value = finalHostController.AxisValue(v.Value) / 10000.0f;
+ float value = finalHostController.AxisValue(v.Value) / 10000.0f;
// apply deadzone (and scale diminished range back up to -1..1)
- var deadzone = v.Deadzone;
+ float deadzone = v.Deadzone;
if (value < -deadzone) value += deadzone;
else if (value < deadzone) value = 0.0f;
else value -= deadzone;
@@ -104,9 +104,9 @@ public void PrepareHapticsForHost(SimpleController finalHostController)
{
foreach (var (k, v) in _feedbackBindings)
{
- if (_haptics.TryGetValue(k, out var strength))
+ if (_haptics.TryGetValue(k, out int strength))
{
- foreach (var hostChannel in v.Channels!.Split('+'))
+ foreach (string hostChannel in v.Channels!.Split('+'))
{
finalHostController.SetHapticChannelStrength(v.GamepadPrefix + hostChannel, (int) ((double) strength * v.Prescale));
}
@@ -126,7 +126,7 @@ public void OR_FromLogical(IController controller)
// foreach (string button in type.BoolButtons)
if (controller.Definition != null)
{
- foreach (var button in controller.Definition.BoolButtons)
+ foreach (string button in controller.Definition.BoolButtons)
{
if (controller.IsPressed(button))
{
@@ -138,17 +138,17 @@ public void OR_FromLogical(IController controller)
public void Overrides(OverrideAdapter controller)
{
- foreach (var button in controller.Overrides)
+ foreach (string button in controller.Overrides)
{
_buttons[button] = controller.IsPressed(button);
}
- foreach (var button in controller.AxisOverrides)
+ foreach (string button in controller.AxisOverrides)
{
_axes[button] = controller.AxisValue(button);
}
- foreach (var button in controller.InversedButtons)
+ foreach (string button in controller.InversedButtons)
{
_buttons[button] ^= true;
}
@@ -161,17 +161,14 @@ public void BindMulti(string button, string controlString)
return;
}
- var controlBindings = controlString.Split(',');
- foreach (var control in controlBindings)
+ string[] controlBindings = controlString.Split(',');
+ foreach (string control in controlBindings)
{
_bindings[button].Add(control.Trim());
}
}
- public void BindAxis(string button, AnalogBind bind)
- {
- _axisBindings[button] = bind;
- }
+ public void BindAxis(string button, AnalogBind bind) => _axisBindings[button] = bind;
public void BindFeedbackChannel(string channel, FeedbackBind binding) => _feedbackBindings[channel] = binding;
diff --git a/src/BizHawk.Client.Common/CoreFileProvider.cs b/src/BizHawk.Client.Common/CoreFileProvider.cs
index b1d9e01b754..d67e5879233 100644
--- a/src/BizHawk.Client.Common/CoreFileProvider.cs
+++ b/src/BizHawk.Client.Common/CoreFileProvider.cs
@@ -40,7 +40,7 @@ public string GetUserPath(string sysID, bool temp)
{
if (temp)
{
- var tempUserPath = Path.Combine(Path.GetTempPath(), $"biz-temp{sysID}user");
+ string tempUserPath = Path.Combine(Path.GetTempPath(), $"biz-temp{sysID}user");
if (Directory.Exists(tempUserPath))
{
Directory.Delete(tempUserPath, true);
@@ -54,7 +54,7 @@ public string GetUserPath(string sysID, bool temp)
private (byte[] FW, string Path)? GetFirmwareWithPath(FirmwareID id)
{
- var path = _firmwareManager.Request(_pathEntries, _firmwareUserSpecifications, id);
+ string? path = _firmwareManager.Request(_pathEntries, _firmwareUserSpecifications, id);
try
{
if (path is not null && File.Exists(path)) return (File.ReadAllBytes(path), path);
diff --git a/src/BizHawk.Client.Common/DialogControllerExtensions.cs b/src/BizHawk.Client.Common/DialogControllerExtensions.cs
index d6f17dccd3b..473f06cc4f5 100644
--- a/src/BizHawk.Client.Common/DialogControllerExtensions.cs
+++ b/src/BizHawk.Client.Common/DialogControllerExtensions.cs
@@ -188,7 +188,7 @@ public static bool ShowMessageBox2(
string? initFileName = null,
bool maySelectMultiple = false)
{
- var filterIndex = 1; // you'd think the default would be 0, but it's not
+ int filterIndex = 1; // you'd think the default would be 0, but it's not
return dialogParent.DialogController.ShowFileMultiOpenDialog(
dialogParent: dialogParent,
discardCWDChange: discardCWDChange,
diff --git a/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs b/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs
index 70948564b0a..4c959c48767 100644
--- a/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs
@@ -35,10 +35,7 @@ protected class DisplayManagerRenderTargetProvider : IRenderTargetProvider
{
private readonly Func _callback;
- RenderTarget IRenderTargetProvider.Get(Size size)
- {
- return _callback(size);
- }
+ RenderTarget IRenderTargetProvider.Get(Size size) => _callback(size);
public DisplayManagerRenderTargetProvider(Func callback)
{
@@ -73,7 +70,7 @@ protected DisplayManagerBase(
_videoTextureFrugalizer = new(_gl);
_shaderChainFrugalizers = new RenderTargetFrugalizer[16]; // hacky hardcoded limit.. need some other way to manage these
- for (var i = 0; i < 16; i++)
+ for (int i = 0; i < 16; i++)
{
_shaderChainFrugalizers[i] = new(_gl);
}
@@ -90,20 +87,20 @@ protected DisplayManagerBase(
if (dispMethod is EDispMethod.OpenGL or EDispMethod.D3D9)
{
- var fiHq2x = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/hq2x.cgp"));
+ FileInfo fiHq2x = new(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/hq2x.cgp"));
if (fiHq2x.Exists)
{
using var stream = fiHq2x.OpenRead();
_shaderChainHq2X = new(_gl, new(stream), Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk"));
}
- var fiScanlines = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/BizScanlines.cgp"));
+ FileInfo fiScanlines = new(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/BizScanlines.cgp"));
if (fiScanlines.Exists)
{
using var stream = fiScanlines.OpenRead();
_shaderChainScanlines = new(_gl, new(stream), Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk"));
}
- var bicubicPath = dispMethod == EDispMethod.D3D9 ? "Shaders/BizHawk/bicubic-normal.cgp" : "Shaders/BizHawk/bicubic-fast.cgp";
- var fiBicubic = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, bicubicPath));
+ string bicubicPath = dispMethod == EDispMethod.D3D9 ? "Shaders/BizHawk/bicubic-normal.cgp" : "Shaders/BizHawk/bicubic-fast.cgp";
+ FileInfo fiBicubic = new(Path.Combine(PathUtils.ExeDirectoryPath, bicubicPath));
if (fiBicubic.Exists)
{
using var stream = fiBicubic.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
@@ -216,7 +213,7 @@ public void RefreshUserShader()
_shaderChainUser?.Dispose();
if (File.Exists(GlobalConfig.DispUserFilterPath))
{
- var fi = new FileInfo(GlobalConfig.DispUserFilterPath);
+ FileInfo fi = new(GlobalConfig.DispUserFilterPath);
using var stream = fi.OpenRead();
_shaderChainUser = new(_gl, new(stream), Path.GetDirectoryName(GlobalConfig.DispUserFilterPath));
}
@@ -256,14 +253,14 @@ public void RefreshUserShader()
private (int Horizontal, int Vertical) CalculateCompleteContentPaddingSum(bool user, bool source)
{
- var p = CalculateCompleteContentPadding(user: user, source: source);
- return (p.Left + p.Right, p.Top + p.Bottom);
+ var (Left, Top, Right, Bottom) = CalculateCompleteContentPadding(user: user, source: source);
+ return (Left + Right, Top + Bottom);
}
private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, bool includeOSD, bool includeUserFilters)
{
// select user special FX shader chain
- var selectedChainProperties = new Dictionary();
+ Dictionary selectedChainProperties = new();
RetroShaderChain selectedChain = null;
switch (GlobalConfig.TargetDisplayFilter)
{
@@ -286,11 +283,11 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo
var fCoreScreenControl = CreateCoreScreenControl();
- var fPresent = new FinalPresentation(chainOutSize);
- var fInput = new SourceImage(chainInSize);
- var fOSD = new OSD(includeOSD, OSD, _theOneFont);
+ FinalPresentation fPresent = new(chainOutSize);
+ SourceImage fInput = new(chainInSize);
+ OSD fOSD = new(includeOSD, OSD, _theOneFont);
- var chain = new FilterProgram();
+ FilterProgram chain = new();
//add the first filter, encompassing output from the emulator core
chain.AddFilter(fInput, "input");
@@ -317,7 +314,7 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo
if (size.Width < 1) size.Width = 1;
if (size.Height < 1) size.Height = 1;
- var fPadding = new FinalPresentation(size);
+ FinalPresentation fPadding = new(size);
chain.AddFilter(fPadding, "padding");
fPadding.Config_PadOnly = true;
fPadding.Padding = padding;
@@ -330,7 +327,7 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo
{
if (GlobalConfig.DispPrescale != 1)
{
- var fPrescale = new PrescaleFilter() { Scale = GlobalConfig.DispPrescale };
+ PrescaleFilter fPrescale = new() { Scale = GlobalConfig.DispPrescale };
chain.AddFilter(fPrescale, "user_prescale");
}
}
@@ -344,7 +341,7 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo
// AutoPrescale makes no sense for a None final filter
if (GlobalConfig.DispAutoPrescale && GlobalConfig.DispFinalFilter != (int)FinalPresentation.eFilterOption.None)
{
- var apf = new AutoPrescaleFilter();
+ AutoPrescaleFilter apf = new();
chain.AddFilter(apf, "auto_prescale");
}
@@ -392,10 +389,10 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo
private static void AppendRetroShaderChain(FilterProgram program, string name, RetroShaderChain retroChain, Dictionary properties)
{
- for (var i = 0; i < retroChain.Passes.Length; i++)
+ for (int i = 0; i < retroChain.Passes.Length; i++)
{
- var rsp = new RetroShaderPass(retroChain, i);
- var fname = $"{name}[{i}]";
+ RetroShaderPass rsp = new(retroChain, i);
+ string fname = $"{name}[{i}]";
program.AddFilter(rsp, fname);
rsp.Parameters = properties;
}
@@ -410,7 +407,7 @@ private void AppendApiHawkLayer(FilterProgram chain, DisplaySurfaceID surfaceID)
}
var luaNativeTexture = _apiHawkSurfaceFrugalizers[surfaceID].Get(luaNativeSurface);
- var fLuaLayer = new LuaLayer();
+ LuaLayer fLuaLayer = new();
fLuaLayer.SetTexture(luaNativeTexture);
chain.AddFilter(fLuaLayer, surfaceID.GetName());
}
@@ -429,7 +426,7 @@ public Point UntransformPoint(Point p)
if (_currentFilterProgram == null) return p;
// otherwise, have the filter program untransform it
- var v = new Vector2(p.X, p.Y);
+ Vector2 v = new(p.X, p.Y);
v = _currentFilterProgram.UntransformPoint("default", v);
return new((int)v.X, (int)v.Y);
@@ -447,7 +444,7 @@ public Point TransformPoint(Point p)
}
// otherwise, have the filter program untransform it
- var v = new Vector2(p.X, p.Y);
+ Vector2 v = new(p.X, p.Y);
v = _currentFilterProgram.TransformPoint("default", v);
return new((int)v.X, (int)v.Y);
}
@@ -462,8 +459,8 @@ public Point TransformPoint(Point p)
///
public void UpdateSource(IVideoProvider videoProvider)
{
- var displayNothing = GlobalConfig.DispSpeedupFeatures == 0;
- var job = new JobInfo
+ bool displayNothing = GlobalConfig.DispSpeedupFeatures == 0;
+ JobInfo job = new()
{
VideoProvider = videoProvider,
Simulate = displayNothing,
@@ -490,7 +487,7 @@ private BaseFilter CreateCoreScreenControl()
///
public BitmapBuffer RenderOffscreen(IVideoProvider videoProvider, bool includeOSD)
{
- var job = new JobInfo
+ JobInfo job = new()
{
VideoProvider = videoProvider,
Simulate = false,
@@ -508,7 +505,7 @@ public BitmapBuffer RenderOffscreen(IVideoProvider videoProvider, bool includeOS
///
public BitmapBuffer RenderOffscreenLua(IVideoProvider videoProvider)
{
- var job = new JobInfo
+ JobInfo job = new()
{
VideoProvider = videoProvider,
Simulate = false,
@@ -547,7 +544,7 @@ public int[] GetVideoBuffer()
private static void FixRatio(float x, float y, int inw, int inh, out int outW, out int outH)
{
- var ratio = x / y;
+ float ratio = x / y;
if (ratio <= 1)
{
// taller. weird. expand height.
@@ -569,17 +566,17 @@ private static void FixRatio(float x, float y, int inw, int inh, out int outW, o
///
public Size CalculateClientSize(IVideoProvider videoProvider, int zoom)
{
- var arActive = GlobalConfig.DispFixAspectRatio;
- var arSystem = GlobalConfig.DispManagerAR == EDispManagerAR.System;
- var arCustom = GlobalConfig.DispManagerAR == EDispManagerAR.CustomSize;
- var arCustomRatio = GlobalConfig.DispManagerAR == EDispManagerAR.CustomRatio;
- var arCorrect = arSystem || arCustom || arCustomRatio;
- var arInteger = GlobalConfig.DispFixScaleInteger;
-
- var bufferWidth = videoProvider.BufferWidth;
- var bufferHeight = videoProvider.BufferHeight;
- var virtualWidth = videoProvider.VirtualWidth;
- var virtualHeight = videoProvider.VirtualHeight;
+ bool arActive = GlobalConfig.DispFixAspectRatio;
+ bool arSystem = GlobalConfig.DispManagerAR == EDispManagerAR.System;
+ bool arCustom = GlobalConfig.DispManagerAR == EDispManagerAR.CustomSize;
+ bool arCustomRatio = GlobalConfig.DispManagerAR == EDispManagerAR.CustomRatio;
+ bool arCorrect = arSystem || arCustom || arCustomRatio;
+ bool arInteger = GlobalConfig.DispFixScaleInteger;
+
+ int bufferWidth = videoProvider.BufferWidth;
+ int bufferHeight = videoProvider.BufferHeight;
+ int virtualWidth = videoProvider.VirtualWidth;
+ int virtualHeight = videoProvider.VirtualHeight;
if (arCustom)
{
@@ -620,7 +617,7 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom)
if (bufferHeight < 1) bufferHeight = 1;
// old stuff
- var fvp = new FakeVideoProvider(bufferWidth, bufferHeight, virtualWidth, virtualHeight);
+ FakeVideoProvider fvp = new(bufferWidth, bufferHeight, virtualWidth, virtualHeight);
Size chainOutsize;
if (arActive)
@@ -630,8 +627,8 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom)
if (arInteger)
{
// ALERT COPYPASTE LAUNDROMAT
- var AR = new Vector2(virtualWidth / (float) bufferWidth, virtualHeight / (float) bufferHeight);
- var targetPar = AR.X / AR.Y;
+ Vector2 AR = new(virtualWidth / (float) bufferWidth, virtualHeight / (float) bufferHeight);
+ float targetPar = AR.X / AR.Y;
// this would malfunction for AR <= 0.5 or AR >= 2.0
// EDIT - in fact, we have AR like that coming from PSX, sometimes, so maybe we should solve this better
@@ -644,19 +641,19 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom)
// TODO - also, this might be messing up zooms and stuff, we might need to run this on the output size of the filter chain
Span trials = stackalloc Vector2[3];
- for (var i = 1; i < zoom; i++)
+ for (int i = 1; i < zoom; i++)
{
// would not be good to run this per frame, but it seems to only run when the resolution changes, etc.
trials[0] = PS + Vector2.UnitX;
trials[1] = PS + Vector2.UnitY;
trials[2] = PS + Vector2.One;
- var bestIndex = -1;
- var bestValue = 1000.0f;
- for (var t = 0; t < trials.Length; t++)
+ int bestIndex = -1;
+ float bestValue = 1000.0f;
+ for (int t = 0; t < trials.Length; t++)
{
//I.
- var testAr = trials[t].X / trials[t].Y;
+ float testAr = trials[t].X / trials[t].Y;
// II.
// var calc = Vector2.Multiply(trials[t], VS);
@@ -664,7 +661,7 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom)
// not clear which approach is superior
- var deviationLinear = Math.Abs(testAr - targetPar);
+ float deviationLinear = Math.Abs(testAr - targetPar);
if (deviationLinear < bestValue)
{
bestIndex = t;
@@ -705,7 +702,7 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom)
chainOutsize.Width += ClientExtraPadding.Left + ClientExtraPadding.Right;
chainOutsize.Height += ClientExtraPadding.Top + ClientExtraPadding.Bottom;
- var job = new JobInfo
+ JobInfo job = new()
{
VideoProvider = fvp,
Simulate = true,
@@ -763,16 +760,16 @@ private FilterProgram UpdateSourceInternal(JobInfo job)
}
var videoProvider = job.VideoProvider;
- var simulate = job.Simulate;
+ bool simulate = job.Simulate;
var chainOutsize = job.ChainOutsize;
- var bufferWidth = videoProvider.BufferWidth;
- var bufferHeight = videoProvider.BufferHeight;
- var presenterTextureWidth = bufferWidth;
- var presenterTextureHeight = bufferHeight;
+ int bufferWidth = videoProvider.BufferWidth;
+ int bufferHeight = videoProvider.BufferHeight;
+ int presenterTextureWidth = bufferWidth;
+ int presenterTextureHeight = bufferHeight;
- var vw = videoProvider.VirtualWidth;
- var vh = videoProvider.VirtualHeight;
+ int vw = videoProvider.VirtualWidth;
+ int vh = videoProvider.VirtualHeight;
// TODO: it is bad that this is happening outside the filter chain
// the filter chain has the ability to add padding...
@@ -811,9 +808,9 @@ private FilterProgram UpdateSourceInternal(JobInfo job)
}
}
- var padding = CalculateCompleteContentPaddingSum(true,false);
- vw += padding.Horizontal;
- vh += padding.Vertical;
+ var (Horizontal, Vertical) = CalculateCompleteContentPaddingSum(true,false);
+ vw += Horizontal;
+ vh += Vertical;
//in case the user requested so much padding that the dimensions are now negative, just turn it to something small.
if (vw < 1) vw = 1;
@@ -847,18 +844,18 @@ private FilterProgram UpdateSourceInternal(JobInfo job)
_currEmuHeight = bufferHeight;
//build the default filter chain and set it up with services filters will need
- var chainInsize = new Size(bufferWidth, bufferHeight);
+ Size chainInsize = new(bufferWidth, bufferHeight);
var filterProgram = BuildDefaultChain(chainInsize, chainOutsize, job.IncludeOSD, job.IncludeUserFilters);
filterProgram.GuiRenderer = _renderer;
filterProgram.GL = _gl;
//setup the source image filter
- var fInput = (SourceImage)filterProgram["input"];
+ SourceImage fInput = (SourceImage)filterProgram["input"];
fInput.Texture = videoTexture;
//setup the final presentation filter
- var fPresent = (FinalPresentation)filterProgram["presentation"];
+ FinalPresentation fPresent = (FinalPresentation)filterProgram["presentation"];
if (fPresent != null)
{
fPresent.VirtualTextureSize = new(vw, vh);
@@ -906,7 +903,7 @@ protected virtual void UpdateSourceDrawingWork(JobInfo job)
//GraphicsControl.Begin(); // CRITICAL POINT for yabause+GL
//TODO - auto-create and age these (and dispose when old)
- var rtCounter = 0;
+ int rtCounter = 0;
// ReSharper disable once AccessToModifiedClosure
_currentFilterProgram.RenderTargetProvider = new DisplayManagerRenderTargetProvider(size => _shaderChainFrugalizers[rtCounter++].Get(size));
@@ -954,7 +951,7 @@ private void LoadCustomFont(Stream fontStream)
var data = Marshal.AllocCoTaskMem((int)fontStream.Length);
try
{
- var fontData = new byte[fontStream.Length];
+ byte[] fontData = new byte[fontStream.Length];
fontStream.Read(fontData, 0, (int)fontStream.Length);
Marshal.Copy(fontData, 0, data, (int)fontStream.Length);
CustomFonts.AddMemoryFont(data, fontData.Length);
diff --git a/src/BizHawk.Client.Common/DisplayManager/DisplaySurface.cs b/src/BizHawk.Client.Common/DisplayManager/DisplaySurface.cs
index e170efdbf0b..a4f97836101 100644
--- a/src/BizHawk.Client.Common/DisplayManager/DisplaySurface.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/DisplaySurface.cs
@@ -21,15 +21,9 @@ public void Clear()
_bmp.UnlockBits(bmpData);
}
- public Bitmap PeekBitmap()
- {
- return _bmp;
- }
+ public Bitmap PeekBitmap() => _bmp;
- public Graphics GetGraphics()
- {
- return Graphics.FromImage(_bmp);
- }
+ public Graphics GetGraphics() => Graphics.FromImage(_bmp);
public DisplaySurface(int width, int height)
{
diff --git a/src/BizHawk.Client.Common/DisplayManager/FilterManager.cs b/src/BizHawk.Client.Common/DisplayManager/FilterManager.cs
index 903e1d936a6..16a9c226f1a 100644
--- a/src/BizHawk.Client.Common/DisplayManager/FilterManager.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/FilterManager.cs
@@ -71,10 +71,7 @@ public enum ProgramStepType
public RenderTarget CurrRenderTarget;
- public RenderTarget GetTempTarget(int width, int height)
- {
- return RenderTargetProvider.Get(new(width, height));
- }
+ public RenderTarget GetTempTarget(int width, int height) => RenderTargetProvider.Get(new(width, height));
public void AddFilter(BaseFilter filter, string name = "")
{
@@ -87,7 +84,7 @@ public void AddFilter(BaseFilter filter, string name = "")
///
public Vector2 UntransformPoint(string channel, Vector2 point)
{
- for (var i = Filters.Count - 1; i >= 0; i--)
+ for (int i = Filters.Count - 1; i >= 0; i--)
{
var filter = Filters[i];
point = filter.UntransformPoint(channel, point);
@@ -160,16 +157,16 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget)
// propagate output size backwards through filter chain to allow a 'flex' filter to determine its output based on the desired output needs
presize = outsize;
- for (var i = Filters.Count - 1; i >= 0; i--)
+ for (int i = Filters.Count - 1; i >= 0; i--)
{
var filter = Filters[i];
presize = filter.PresizeOutput(channel, presize);
}
- var obtainedFirstOutput = false;
- var currState = new SurfaceState(null);
+ bool obtainedFirstOutput = false;
+ SurfaceState currState = new(null);
- for (var i = 0; i < Filters.Count; i++)
+ for (int i = 0; i < Filters.Count; i++)
{
var f = Filters[i];
@@ -196,7 +193,7 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget)
// (if so, insert a render filter)
case SurfaceDisposition.RenderTarget when currState.SurfaceDisposition == SurfaceDisposition.Texture:
{
- var renderer = new Render();
+ Render renderer = new();
Filters.Insert(i, renderer);
Compile(channel, inSize, outsize, finalTarget);
return;
@@ -205,7 +202,7 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget)
// (if so, the current render target gets resolved, and made no longer current
case SurfaceDisposition.Texture when currState.SurfaceDisposition == SurfaceDisposition.RenderTarget:
{
- var resolver = new Resolve();
+ Resolve resolver = new();
Filters.Insert(i, resolver);
Compile(channel, inSize, outsize, finalTarget);
return;
@@ -233,7 +230,7 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget)
iosi.SurfaceDisposition = currState.SurfaceDisposition;
}
- var newTarget = false;
+ bool newTarget = false;
if (iosi.SurfaceFormat.Size != currState.SurfaceFormat.Size)
{
newTarget = true;
@@ -267,7 +264,7 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget)
// if the current output disposition is a texture, we need to render it
if (currState.SurfaceDisposition == SurfaceDisposition.Texture)
{
- var renderer = new Render();
+ Render renderer = new();
Filters.Insert(Filters.Count, renderer);
Compile(channel, inSize, outsize, finalTarget);
return;
@@ -276,12 +273,12 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget)
// patch the program so that the final RenderTarget set operation is the framebuffer instead
if (finalTarget)
{
- for (var i = Program.Count - 1; i >= 0; i--)
+ for (int i = Program.Count - 1; i >= 0; i--)
{
var ps = Program[i];
if (ps.Type == ProgramStepType.NewTarget)
{
- var size = (Size)ps.Args;
+ Size size = (Size)ps.Args;
Debug.Assert(size == outsize);
Program[i] = new(ProgramStepType.FinalTarget, size, ps.Comment);
break;
diff --git a/src/BizHawk.Client.Common/DisplayManager/Filters/BaseFilter.cs b/src/BizHawk.Client.Common/DisplayManager/Filters/BaseFilter.cs
index a373513ad3e..afabab3e368 100644
--- a/src/BizHawk.Client.Common/DisplayManager/Filters/BaseFilter.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/Filters/BaseFilter.cs
@@ -74,10 +74,7 @@ public virtual Vector2 TransformPoint(string channel, Vector2 point)
return point;
}
- public void SetInput(Texture2d tex)
- {
- InputTexture = tex;
- }
+ public void SetInput(Texture2d tex) => InputTexture = tex;
public virtual void Run()
{
@@ -87,10 +84,7 @@ public Texture2d GetOutput()
=> _outputTexture;
// filter actions
- protected void YieldOutput(Texture2d tex)
- {
- _outputTexture = tex;
- }
+ protected void YieldOutput(Texture2d tex) => _outputTexture = tex;
protected FilterProgram FilterProgram;
protected Texture2d InputTexture;
@@ -100,21 +94,12 @@ protected void YieldOutput(Texture2d tex)
/// Indicate a 'RenderTarget' disposition if you want to draw directly to the input
/// Indicate a 'Texture' disposition if you want to use it to draw to a newly allocated render target
///
- protected IOSurfaceInfo DeclareInput(SurfaceDisposition disposition = SurfaceDisposition.Unspecified, string channel = "default")
- {
- return DeclareIO(SurfaceDirection.Input, channel, disposition);
- }
+ protected IOSurfaceInfo DeclareInput(SurfaceDisposition disposition = SurfaceDisposition.Unspecified, string channel = "default") => DeclareIO(SurfaceDirection.Input, channel, disposition);
- protected IOSurfaceInfo DeclareOutput(SurfaceDisposition disposition = SurfaceDisposition.Unspecified, string channel = "default")
- {
- return DeclareIO(SurfaceDirection.Output, channel, disposition);
- }
+ protected IOSurfaceInfo DeclareOutput(SurfaceDisposition disposition = SurfaceDisposition.Unspecified, string channel = "default") => DeclareIO(SurfaceDirection.Output, channel, disposition);
// TODO - why a different param order than DeclareOutput?
- protected RenderTarget GetTempTarget(int width, int height)
- {
- return FilterProgram.GetTempTarget(width, height);
- }
+ protected RenderTarget GetTempTarget(int width, int height) => FilterProgram.GetTempTarget(width, height);
protected IOSurfaceInfo DeclareOutput(SurfaceState state, string channel = "default")
{
@@ -123,19 +108,13 @@ protected IOSurfaceInfo DeclareOutput(SurfaceState state, string channel = "defa
return iosi;
}
- public IOSurfaceInfo FindInput(string channel = "default")
- {
- return FindIOSurfaceInfo(channel, SurfaceDirection.Input);
- }
+ public IOSurfaceInfo FindInput(string channel = "default") => FindIOSurfaceInfo(channel, SurfaceDirection.Input);
- public IOSurfaceInfo FindOutput(string channel = "default")
- {
- return FindIOSurfaceInfo(channel, SurfaceDirection.Output);
- }
+ public IOSurfaceInfo FindOutput(string channel = "default") => FindIOSurfaceInfo(channel, SurfaceDirection.Output);
private IOSurfaceInfo DeclareIO(SurfaceDirection direction, string channel, SurfaceDisposition disposition)
{
- var iosi = new IOSurfaceInfo
+ IOSurfaceInfo iosi = new()
{
SurfaceDirection = direction,
Channel = channel,
@@ -149,10 +128,7 @@ private IOSurfaceInfo DeclareIO(SurfaceDirection direction, string channel, Surf
private readonly List _ioSurfaceInfos = new();
- private IOSurfaceInfo FindIOSurfaceInfo(string channel, SurfaceDirection direction)
- {
- return _ioSurfaceInfos.Find(iosi => iosi.Channel == channel && iosi.SurfaceDirection == direction);
- }
+ private IOSurfaceInfo FindIOSurfaceInfo(string channel, SurfaceDirection direction) => _ioSurfaceInfos.Find(iosi => iosi.Channel == channel && iosi.SurfaceDirection == direction);
public class IOSurfaceInfo
{
diff --git a/src/BizHawk.Client.Common/DisplayManager/Filters/Gui.cs b/src/BizHawk.Client.Common/DisplayManager/Filters/Gui.cs
index 060ed3a95d4..2e123a43bb0 100644
--- a/src/BizHawk.Client.Common/DisplayManager/Filters/Gui.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/Filters/Gui.cs
@@ -36,14 +36,14 @@ public LetterboxingLogic()
// do maths on the viewport and the native resolution and the user settings to get a display rectangle
public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWidth, int targetHeight, int sourceWidth, int sourceHeight, Size textureSize, Size virtualSize)
{
- var textureWidth = textureSize.Width;
- var textureHeight = textureSize.Height;
- var virtualWidth = virtualSize.Width;
- var virtualHeight = virtualSize.Height;
+ int textureWidth = textureSize.Width;
+ int textureHeight = textureSize.Height;
+ int virtualWidth = virtualSize.Width;
+ int virtualHeight = virtualSize.Height;
// zero 02-jun-2014 - we passed these in, but ignored them. kind of weird..
- var oldSourceWidth = sourceWidth;
- var oldSourceHeight = sourceHeight;
+ int oldSourceWidth = sourceWidth;
+ int oldSourceHeight = sourceHeight;
sourceWidth = virtualWidth;
sourceHeight = virtualHeight;
@@ -53,8 +53,8 @@ public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWi
maintainInteger = false;
}
- var widthScale = (float)targetWidth / sourceWidth;
- var heightScale = (float)targetHeight / sourceHeight;
+ float widthScale = (float)targetWidth / sourceWidth;
+ float heightScale = (float)targetHeight / sourceHeight;
if (maintainAspect
// zero 20-jul-2014 - hacks upon hacks, this function needs rewriting
@@ -71,8 +71,8 @@ public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWi
// apply the zooming algorithm (pasted and reworked, for now)
// ALERT COPYPASTE LAUNDROMAT
- var AR = new Vector2(virtualWidth / (float) textureWidth, virtualHeight / (float) textureHeight);
- var targetPar = AR.X / AR.Y;
+ Vector2 AR = new(virtualWidth / (float) textureWidth, virtualHeight / (float) textureHeight);
+ float targetPar = AR.X / AR.Y;
var PS = Vector2.One; // this would malfunction for AR <= 0.5 or AR >= 2.0
Span trials = stackalloc Vector2[3];
@@ -84,21 +84,21 @@ public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWi
trials[1] = PS + Vector2.UnitY;
trials[2] = PS + Vector2.One;
- var bestIndex = -1;
- var bestValue = 1000.0f;
- for (var t = 0; t < trials.Length; t++)
+ int bestIndex = -1;
+ float bestValue = 1000.0f;
+ for (int t = 0; t < trials.Length; t++)
{
var vTrial = trials[t];
trialsLimited[t] = false;
//check whether this is going to exceed our allotted area
- var testVw = (int)(vTrial.X * textureWidth);
- var testVh = (int)(vTrial.Y * textureHeight);
+ int testVw = (int)(vTrial.X * textureWidth);
+ int testVh = (int)(vTrial.Y * textureHeight);
if (testVw > targetWidth) trialsLimited[t] = true;
if (testVh > targetHeight) trialsLimited[t] = true;
// I.
- var testAr = vTrial.X / vTrial.Y;
+ float testAr = vTrial.X / vTrial.Y;
// II.
// var calc = Vector2.Multiply(trials[t], VS);
@@ -106,7 +106,7 @@ public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWi
// not clear which approach is superior
- var deviationLinear = Math.Abs(testAr - targetPar);
+ float deviationLinear = Math.Abs(testAr - targetPar);
if (deviationLinear < bestValue)
{
bestIndex = t;
@@ -202,11 +202,9 @@ public ScreenControlNDS(NDS nds)
_nds = nds;
}
- public override void Initialize()
- {
+ public override void Initialize() =>
//we're going to be blitting the source as pieces to a new render target, so we need our input to be a texture
DeclareInput(SurfaceDisposition.Texture);
- }
private void CrunchNumbers()
{
@@ -238,7 +236,7 @@ private void CrunchNumbers()
// this doesn't make any sense, it's likely to be too much for a monitor to gracefully handle too
if (settings.ScreenLayout != NDS.ScreenLayoutKind.Horizontal)
{
- var rot = settings.ScreenRotation switch
+ int rot = settings.ScreenRotation switch
{
NDS.ScreenRotationKind.Rotate90 => 90,
NDS.ScreenRotationKind.Rotate180 => 180,
@@ -256,14 +254,14 @@ private void CrunchNumbers()
matBot = bot.Top;
// apply transforms from standard input screen positions to output screen positions
- var top_TL = Vector2.Transform(new(0, 0), matTop);
- var top_TR = Vector2.Transform(new(256, 0), matTop);
- var top_BL = Vector2.Transform(new(0, 192), matTop);
- var top_BR = Vector2.Transform(new(256, 192), matTop);
- var bot_TL = Vector2.Transform(new(0, 0), matBot);
- var bot_TR = Vector2.Transform(new(256, 0), matBot);
- var bot_BL = Vector2.Transform(new(0, 192), matBot);
- var bot_BR = Vector2.Transform(new(256, 192), matBot);
+ Vector2 top_TL = Vector2.Transform(new(0, 0), matTop);
+ Vector2 top_TR = Vector2.Transform(new(256, 0), matTop);
+ Vector2 top_BL = Vector2.Transform(new(0, 192), matTop);
+ Vector2 top_BR = Vector2.Transform(new(256, 192), matTop);
+ Vector2 bot_TL = Vector2.Transform(new(0, 0), matBot);
+ Vector2 bot_TR = Vector2.Transform(new(256, 0), matBot);
+ Vector2 bot_BL = Vector2.Transform(new(0, 192), matBot);
+ Vector2 bot_BR = Vector2.Transform(new(256, 192), matBot);
// in case of math errors in the transforms, we'll round this stuff.. although...
// we're gonna use matrix transforms for drawing later, so it isn't extremely helpful
@@ -315,7 +313,7 @@ private void CrunchNumbers()
fixed (Matrix4x4* matTopP = &matTop, matBotP = &matBot)
{
float* matTopF = (float*)matTopP, matBotF = (float*)matBotP;
- for (var i = 0; i < 4 * 4; i++)
+ for (int i = 0; i < 4 * 4; i++)
{
if (Math.Abs(matTopF[i]) < 0.0000001f)
{
@@ -351,14 +349,14 @@ public override Size PresizeOutput(string channel, Size size)
public override void SetInputFormat(string channel, SurfaceState state)
{
CrunchNumbers();
- var ss = new SurfaceState(new(outputSize), SurfaceDisposition.RenderTarget);
+ SurfaceState ss = new(new(outputSize), SurfaceDisposition.RenderTarget);
DeclareOutput(ss, channel);
}
public override Vector2 UntransformPoint(string channel, Vector2 point)
{
var settings = _nds.GetSettings();
- var invert = settings.ScreenInvert
+ bool invert = settings.ScreenInvert
&& settings.ScreenLayout != NDS.ScreenLayoutKind.Top
&& settings.ScreenLayout != NDS.ScreenLayoutKind.Bottom;
@@ -380,10 +378,7 @@ public override Vector2 UntransformPoint(string channel, Vector2 point)
return point;
}
- public override Vector2 TransformPoint(string channel, Vector2 point)
- {
- return Vector2.Transform(point, matTop);
- }
+ public override Vector2 TransformPoint(string channel, Vector2 point) => Vector2.Transform(point, matTop);
public override void Run()
{
@@ -406,8 +401,8 @@ public override void Run()
InputTexture.SetFilterNearest();
//draw screens
- var renderTop = false;
- var renderBottom = false;
+ bool renderTop = false;
+ bool renderBottom = false;
var settings = _nds.GetSettings();
switch (settings.ScreenLayout)
{
@@ -425,7 +420,7 @@ public override void Run()
throw new InvalidOperationException();
}
- var invert = settings.ScreenInvert && renderTop && renderBottom;
+ bool invert = settings.ScreenInvert && renderTop && renderBottom;
if (renderTop)
{
@@ -466,9 +461,9 @@ public override Vector2 UntransformPoint(string channel, Vector2 point)
if (_citra.TouchScreenEnabled)
{
var rect = _citra.TouchScreenRectangle;
- var rotated = _citra.TouchScreenRotated;
- var bufferWidth = (float)_citra.AsVideoProvider().BufferWidth;
- var bufferHeight = (float)_citra.AsVideoProvider().BufferHeight;
+ bool rotated = _citra.TouchScreenRotated;
+ float bufferWidth = _citra.AsVideoProvider().BufferWidth;
+ float bufferHeight = _citra.AsVideoProvider().BufferHeight;
// reset the point's origin to the top left of the screen
point.X -= rect.X;
@@ -498,7 +493,7 @@ public override Vector2 TransformPoint(string channel, Vector2 point)
if (_citra.TouchScreenEnabled)
{
var rect = _citra.TouchScreenRectangle;
- var rotated = _citra.TouchScreenRotated;
+ bool rotated = _citra.TouchScreenRotated;
if (rotated)
{
@@ -588,7 +583,7 @@ public override Size PresizeInput(string channel, Size size)
public override void SetInputFormat(string channel, SurfaceState state)
{
- var need = state.SurfaceFormat.Size != OutputSize || FilterOption != eFilterOption.None;
+ bool need = state.SurfaceFormat.Size != OutputSize || FilterOption != eFilterOption.None;
if (!need)
{
Nop = true;
@@ -611,8 +606,8 @@ public override void SetInputFormat(string channel, SurfaceState state)
}
else
{
- var ow = OutputSize.Width;
- var oh = OutputSize.Height;
+ int ow = OutputSize.Width;
+ int oh = OutputSize.Height;
ow -= Padding.Left + Padding.Right;
oh -= Padding.Top + Padding.Bottom;
LL = new(Config_FixAspectRatio, Config_FixScaleInteger, ow, oh, InputSize.Width, InputSize.Height, TextureSize, VirtualTextureSize);
@@ -690,17 +685,14 @@ public class PrescaleFilter : BaseFilter
{
public int Scale;
- public override void Initialize()
- {
- DeclareInput(SurfaceDisposition.Texture);
- }
+ public override void Initialize() => DeclareInput(SurfaceDisposition.Texture);
public override void SetInputFormat(string channel, SurfaceState state)
{
var outputSize = state.SurfaceFormat.Size;
outputSize.Width *= Scale;
outputSize.Height *= Scale;
- var ss = new SurfaceState(new(outputSize), SurfaceDisposition.RenderTarget);
+ SurfaceState ss = new(new(outputSize), SurfaceDisposition.RenderTarget);
DeclareOutput(ss, channel);
}
@@ -720,10 +712,7 @@ public class AutoPrescaleFilter : BaseFilter
private Size OutputSize;
private int XIS, YIS;
- public override void Initialize()
- {
- DeclareInput(SurfaceDisposition.Texture);
- }
+ public override void Initialize() => DeclareInput(SurfaceDisposition.Texture);
public override void SetInputFormat(string channel, SurfaceState state)
{
@@ -755,10 +744,7 @@ public override Size PresizeOutput(string channel, Size size)
return base.PresizeOutput(channel, size);
}
- public override Size PresizeInput(string channel, Size inSize)
- {
- return inSize;
- }
+ public override Size PresizeInput(string channel, Size inSize) => inSize;
public override void Run()
{
@@ -773,22 +759,13 @@ public override void Run()
/// More accurately, ApiHawkLayer, since the gui Lua library is delegated.
public class LuaLayer : BaseFilter
{
- public override void Initialize()
- {
- DeclareInput(SurfaceDisposition.RenderTarget);
- }
+ public override void Initialize() => DeclareInput(SurfaceDisposition.RenderTarget);
- public override void SetInputFormat(string channel, SurfaceState state)
- {
- DeclareOutput(state);
- }
+ public override void SetInputFormat(string channel, SurfaceState state) => DeclareOutput(state);
private Texture2d _texture;
- public void SetTexture(Texture2d tex)
- {
- _texture = tex;
- }
+ public void SetTexture(Texture2d tex) => _texture = tex;
public override void Run()
{
@@ -816,15 +793,9 @@ public OSD(bool drawOsd, OSDManager manager, StringRenderer font)
_font = font;
}
- public override void Initialize()
- {
- DeclareInput(SurfaceDisposition.RenderTarget);
- }
+ public override void Initialize() => DeclareInput(SurfaceDisposition.RenderTarget);
- public override void SetInputFormat(string channel, SurfaceState state)
- {
- DeclareOutput(state);
- }
+ public override void SetInputFormat(string channel, SurfaceState state) => DeclareOutput(state);
public override void Run()
{
@@ -836,7 +807,7 @@ public override void Run()
var size = FindInput().SurfaceFormat.Size;
FilterProgram.GuiRenderer.Begin(size.Width, size.Height);
- var blitter = new OSDBlitter(_font, FilterProgram.GuiRenderer, new(0, 0, size.Width, size.Height));
+ OSDBlitter blitter = new(_font, FilterProgram.GuiRenderer, new(0, 0, size.Width, size.Height));
FilterProgram.GuiRenderer.EnableBlending();
_manager.DrawScreenInfo(blitter);
_manager.DrawMessages(blitter);
diff --git a/src/BizHawk.Client.Common/DisplayManager/Filters/Retro.cs b/src/BizHawk.Client.Common/DisplayManager/Filters/Retro.cs
index 627b29035be..0e49bb7c0b8 100644
--- a/src/BizHawk.Client.Common/DisplayManager/Filters/Retro.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/Filters/Retro.cs
@@ -32,9 +32,9 @@ private static string ResolveIncludes(string content, string baseDirectory)
return content;
}
- var fname = match.Groups[4].Value;
+ string fname = match.Groups[4].Value;
fname = Path.Combine(baseDirectory,fname);
- var includedContent = ResolveIncludes(File.ReadAllText(fname),Path.GetDirectoryName(fname));
+ string includedContent = ResolveIncludes(File.ReadAllText(fname),Path.GetDirectoryName(fname));
content = content.Substring(0, match.Index) + includedContent + content.Substring(match.Index + match.Length);
}
}
@@ -52,12 +52,12 @@ public RetroShaderChain(IGL owner, RetroShaderPreset preset, string baseDirector
}
// load up the shaders
- var shaders = new RetroShader[preset.Passes.Count];
- for (var i = 0; i < preset.Passes.Count; i++)
+ RetroShader[] shaders = new RetroShader[preset.Passes.Count];
+ for (int i = 0; i < preset.Passes.Count; i++)
{
// acquire content. we look for it in any reasonable filename so that one preset can bind to multiple shaders
string content;
- var path = Path.Combine(baseDirectory, preset.Passes[i].ShaderPath);
+ string path = Path.Combine(baseDirectory, preset.Passes[i].ShaderPath);
if (!File.Exists(path))
{
if (!Path.HasExtension(path))
@@ -136,14 +136,14 @@ public class RetroShaderPreset
///
public RetroShaderPreset(Stream stream)
{
- var content = new StreamReader(stream).ReadToEnd();
- var dict = new Dictionary();
+ string content = new StreamReader(stream).ReadToEnd();
+ Dictionary dict = new();
// parse the key-value-pair format of the file
content = content.Replace("\r", "");
- foreach (var splitLine in content.Split('\n'))
+ foreach (string splitLine in content.Split('\n'))
{
- var line = splitLine.Trim();
+ string line = splitLine.Trim();
if (line.Length is 0)
{
continue;
@@ -154,10 +154,10 @@ public RetroShaderPreset(Stream stream)
continue; // comments
}
- var eq = line.IndexOf('=');
- var key = line.Substring(0, eq).Trim();
- var value = line.Substring(eq + 1).Trim();
- var quote = value.IndexOf('\"');
+ int eq = line.IndexOf('=');
+ string key = line.Substring(0, eq).Trim();
+ string value = line.Substring(eq + 1).Trim();
+ int quote = value.IndexOf('\"');
if (quote != -1)
{
value = value.Substring(quote + 1, value.IndexOf('\"', quote + 1) - (quote + 1));
@@ -165,7 +165,7 @@ public RetroShaderPreset(Stream stream)
else
{
// remove comments from end of value. exclusive from above condition, since comments after quoted strings would be snipped by the quoted string extraction
- var hash = value.IndexOf('#');
+ int hash = value.IndexOf('#');
if (hash != -1)
{
value = value.Substring(0, hash);
@@ -177,10 +177,10 @@ public RetroShaderPreset(Stream stream)
}
// process the keys
- var nShaders = FetchInt(dict, "shaders", 0);
- for (var i = 0; i < nShaders; i++)
+ int nShaders = FetchInt(dict, "shaders", 0);
+ for (int i = 0; i < nShaders; i++)
{
- var sp = new ShaderPass { Index = i };
+ ShaderPass sp = new() { Index = i };
Passes.Add(sp);
sp.InputFilterLinear = FetchBool(dict, $"filter_linear{i}", false); // Should this value not be defined, the filtering option is implementation defined.
@@ -192,7 +192,7 @@ public RetroShaderPreset(Stream stream)
// It is possible to set scale_type_xN and scale_type_yN to specialize the scaling type in either direction. scale_typeN however overrides both of these.
sp.ScaleTypeX = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, $"scale_type_x{i}", "Source"), true);
sp.ScaleTypeY = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, $"scale_type_y{i}", "Source"), true);
- var st = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, $"scale_type{i}", "NotSet"), true);
+ ScaleType st = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, $"scale_type{i}", "NotSet"), true);
if (st != ScaleType.NotSet)
{
sp.ScaleTypeX = sp.ScaleTypeY = st;
@@ -229,25 +229,13 @@ public class ShaderPass
public Vector2 Scale;
}
- private static string FetchString(IDictionary dict, string key, string @default)
- {
- return dict.TryGetValue(key, out var str) ? str : @default;
- }
+ private static string FetchString(IDictionary dict, string key, string @default) => dict.TryGetValue(key, out string str) ? str : @default;
- private static int FetchInt(IDictionary dict, string key, int @default)
- {
- return dict.TryGetValue(key, out var str) ? int.Parse(str) : @default;
- }
+ private static int FetchInt(IDictionary dict, string key, int @default) => dict.TryGetValue(key, out string str) ? int.Parse(str) : @default;
- private static float FetchFloat(IDictionary dict, string key, float @default)
- {
- return dict.TryGetValue(key, out var str) ? float.Parse(str, NumberFormatInfo.InvariantInfo) : @default;
- }
+ private static float FetchFloat(IDictionary dict, string key, float @default) => dict.TryGetValue(key, out string str) ? float.Parse(str, NumberFormatInfo.InvariantInfo) : @default;
- private static bool FetchBool(IDictionary dict, string key, bool @default)
- {
- return dict.TryGetValue(key, out var str) ? ParseBool(str) : @default;
- }
+ private static bool FetchBool(IDictionary dict, string key, bool @default) => dict.TryGetValue(key, out string str) ? ParseBool(str) : @default;
private static bool ParseBool(string value)
{
@@ -285,10 +273,7 @@ public RetroShaderPass(RetroShaderChain rsc, int index)
_sp = _rsc.Passes[index];
}
- public override void Initialize()
- {
- DeclareInput(SurfaceDisposition.Texture);
- }
+ public override void Initialize() => DeclareInput(SurfaceDisposition.Texture);
public override void SetInputFormat(string channel, SurfaceState state)
{
diff --git a/src/BizHawk.Client.Common/DisplayManager/Filters/Utils.cs b/src/BizHawk.Client.Common/DisplayManager/Filters/Utils.cs
index 9dfa70aacb0..e25b037e9bd 100644
--- a/src/BizHawk.Client.Common/DisplayManager/Filters/Utils.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/Filters/Utils.cs
@@ -16,20 +16,11 @@ public SourceImage(Size size)
public Texture2d Texture { get; set; }
- public override void Run()
- {
- YieldOutput(Texture);
- }
+ public override void Run() => YieldOutput(Texture);
- public override void Initialize()
- {
- DeclareOutput(new SurfaceState(new(_size), SurfaceDisposition.Texture));
- }
+ public override void Initialize() => DeclareOutput(new SurfaceState(new(_size), SurfaceDisposition.Texture));
- public override void SetInputFormat(string channel, SurfaceState format)
- {
- DeclareOutput(SurfaceDisposition.Texture);
- }
+ public override void SetInputFormat(string channel, SurfaceState format) => DeclareOutput(SurfaceDisposition.Texture);
}
///
@@ -37,15 +28,9 @@ public override void SetInputFormat(string channel, SurfaceState format)
///
public class Render : BaseFilter
{
- public override void Initialize()
- {
- DeclareInput(SurfaceDisposition.Texture);
- }
+ public override void Initialize() => DeclareInput(SurfaceDisposition.Texture);
- public override void SetInputFormat(string channel, SurfaceState state)
- {
- DeclareOutput(new SurfaceState(state.SurfaceFormat, SurfaceDisposition.RenderTarget));
- }
+ public override void SetInputFormat(string channel, SurfaceState state) => DeclareOutput(new SurfaceState(state.SurfaceFormat, SurfaceDisposition.RenderTarget));
public override void Run()
{
@@ -59,19 +44,10 @@ public override void Run()
public class Resolve : BaseFilter
{
- public override void Initialize()
- {
- DeclareInput(SurfaceDisposition.RenderTarget);
- }
+ public override void Initialize() => DeclareInput(SurfaceDisposition.RenderTarget);
- public override void SetInputFormat(string channel, SurfaceState state)
- {
- DeclareOutput(new SurfaceState(state.SurfaceFormat, SurfaceDisposition.Texture));
- }
+ public override void SetInputFormat(string channel, SurfaceState state) => DeclareOutput(new SurfaceState(state.SurfaceFormat, SurfaceDisposition.Texture));
- public override void Run()
- {
- YieldOutput(FilterProgram.CurrRenderTarget.Texture2d);
- }
+ public override void Run() => YieldOutput(FilterProgram.CurrRenderTarget.Texture2d);
}
}
\ No newline at end of file
diff --git a/src/BizHawk.Client.Common/DisplayManager/OSDManager.cs b/src/BizHawk.Client.Common/DisplayManager/OSDManager.cs
index 11d930cd4e6..ac519d83ae3 100644
--- a/src/BizHawk.Client.Common/DisplayManager/OSDManager.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/OSDManager.cs
@@ -55,7 +55,7 @@ private string MakeFrameCounter()
{
if (_movieSession.Movie.IsFinished())
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
sb
.Append(_emulator.Frame)
.Append('/')
@@ -66,7 +66,7 @@ private string MakeFrameCounter()
if (_movieSession.Movie.IsPlayingOrFinished())
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
sb
.Append(_emulator.Frame)
.Append('/')
@@ -78,9 +78,9 @@ private string MakeFrameCounter()
return _emulator.Frame.ToString();
}
- private readonly List _messages = new List(5);
- private readonly List _guiTextList = new List();
- private readonly List _ramWatchList = new List();
+ private readonly List _messages = new(5);
+ private readonly List _guiTextList = new();
+ private readonly List _ramWatchList = new();
public void AddMessage(string message, int? duration = null)
=> _messages.Add(new() {
@@ -88,10 +88,7 @@ public void AddMessage(string message, int? duration = null)
ExpireAt = DateTime.Now + TimeSpan.FromSeconds(duration ?? _config.OSDMessageDuration),
});
- public void ClearRamWatches()
- {
- _ramWatchList.Clear();
- }
+ public void ClearRamWatches() => _ramWatchList.Clear();
public void AddRamWatch(string message, MessagePosition pos, Color backGround, Color foreColor)
{
@@ -115,15 +112,12 @@ public void AddGuiText(string message, MessagePosition pos, Color backGround, Co
});
}
- public void ClearGuiText()
- {
- _guiTextList.Clear();
- }
+ public void ClearGuiText() => _guiTextList.Clear();
private void DrawMessage(IBlitter g, UIMessage message, int yOffset)
{
var point = GetCoordinates(g, _config.Messages, message.Message);
- var y = point.Y + yOffset; // TODO: clean me up
+ float y = point.Y + yOffset; // TODO: clean me up
g.DrawString(message.Message, FixedMessagesColor, point.X, y);
}
@@ -174,15 +168,9 @@ public void DrawMessages(IBlitter g)
}
}
- public string InputStrMovie()
- {
- return MakeStringFor(_movieSession.MovieController, cache: true);
- }
+ public string InputStrMovie() => MakeStringFor(_movieSession.MovieController, cache: true);
- public string InputStrImmediate()
- {
- return MakeStringFor(_inputManager.AutofireStickyXorAdapter, cache: true);
- }
+ public string InputStrImmediate() => MakeStringFor(_inputManager.AutofireStickyXorAdapter, cache: true);
public string InputPrevious()
{
@@ -235,10 +223,7 @@ public string MakeRerecordCount()
: "";
}
- private void DrawOsdMessage(IBlitter g, string message, Color color, float x, float y)
- {
- g.DrawString(message, color, x, y);
- }
+ private void DrawOsdMessage(IBlitter g, string message, Color color, float x, float y) => g.DrawString(message, color, x, y);
///
/// Display all screen info objects like fps, frame counter, lag counter, and input display
@@ -259,12 +244,12 @@ public void DrawScreenInfo(IBlitter g)
if (_config.DisplayInput)
{
- var moviePlaying = _movieSession.Movie.IsPlaying();
+ bool moviePlaying = _movieSession.Movie.IsPlaying();
// After the last frame of the movie, we want both the last movie input and the current inputs.
- var atMovieEnd = _movieSession.Movie.IsFinished() && _movieSession.Movie.IsAtEnd();
+ bool atMovieEnd = _movieSession.Movie.IsFinished() && _movieSession.Movie.IsAtEnd();
if (moviePlaying || atMovieEnd)
{
- var input = InputStrMovie();
+ string input = InputStrMovie();
var point = GetCoordinates(g, _config.InputDisplay, input);
Color c = Color.FromArgb(_config.MovieInput);
g.DrawString(input, c, point.X, point.Y);
@@ -272,27 +257,27 @@ public void DrawScreenInfo(IBlitter g)
if (!moviePlaying) // TODO: message config -- allow setting of "mixed", and "auto"
{
- var previousColor = Color.FromArgb(_config.LastInputColor);
+ Color previousColor = Color.FromArgb(_config.LastInputColor);
Color immediateColor = Color.FromArgb(_config.MessagesColor);
var autoColor = Color.Pink;
var changedColor = Color.PeachPuff;
//we need some kind of string for calculating position when right-anchoring, of something like that
- var bgStr = InputStrOrAll();
+ string bgStr = InputStrOrAll();
var point = GetCoordinates(g, _config.InputDisplay, bgStr);
// now, we're going to render these repeatedly, with higher-priority things overriding
// first display previous frame's input.
// note: that's only available in case we're working on a movie
- var previousStr = InputPrevious();
+ string previousStr = InputPrevious();
g.DrawString(previousStr, previousColor, point.X, point.Y);
// next, draw the immediate input.
// that is, whatever is being held down interactively right this moment even if the game is paused
// this includes things held down due to autohold or autofire
// I know, this is all really confusing
- var immediate = InputStrImmediate();
+ string immediate = InputStrImmediate();
g.DrawString(immediate, immediateColor, point.X, point.Y);
// next draw anything that's pressed because it's sticky.
@@ -301,11 +286,11 @@ public void DrawScreenInfo(IBlitter g)
// in order to achieve this we want to avoid drawing anything pink that isn't actually held down right now
// so we make an AND adapter and combine it using immediate & sticky
// (adapter creation moved to InputManager)
- var autoString = MakeStringFor(_inputManager.WeirdStickyControllerForInputDisplay, cache: true);
+ string autoString = MakeStringFor(_inputManager.WeirdStickyControllerForInputDisplay, cache: true);
g.DrawString(autoString, autoColor, point.X, point.Y);
//recolor everything that's changed from the previous input
- var immediateOverlay = MakeIntersectImmediatePrevious();
+ string immediateOverlay = MakeIntersectImmediatePrevious();
g.DrawString(immediateOverlay, changedColor, point.X, point.Y);
}
}
@@ -318,7 +303,7 @@ public void DrawScreenInfo(IBlitter g)
if (_config.DisplayLagCounter && _emulator.CanPollInput())
{
- var counter = _emulator.AsInputPollable().LagCount.ToString();
+ string counter = _emulator.AsInputPollable().LagCount.ToString();
var point = GetCoordinates(g, _config.LagCounter, counter);
DrawOsdMessage(g, counter, FixedAlertMessageColor, point.X, point.Y);
}
@@ -332,7 +317,7 @@ public void DrawScreenInfo(IBlitter g)
if (_inputManager.ClientControls["Autohold"] || _inputManager.ClientControls["Autofire"])
{
- var sb = new StringBuilder("Held: ");
+ StringBuilder sb = new("Held: ");
foreach (string sticky in _inputManager.StickyXorAdapter.CurrentStickies)
{
@@ -347,7 +332,7 @@ public void DrawScreenInfo(IBlitter g)
.Append(' ');
}
- var message = sb.ToString();
+ string message = sb.ToString();
var point = GetCoordinates(g, _config.Autohold, message);
g.DrawString(message, Color.White, point.X, point.Y);
}
diff --git a/src/BizHawk.Client.Common/DisplayManager/RenderTargetFrugalizer.cs b/src/BizHawk.Client.Common/DisplayManager/RenderTargetFrugalizer.cs
index f824969c568..69e3df93871 100644
--- a/src/BizHawk.Client.Common/DisplayManager/RenderTargetFrugalizer.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/RenderTargetFrugalizer.cs
@@ -28,23 +28,17 @@ public void Dispose()
ResetList();
}
- private void ResetList()
- {
- _currentRenderTargets = new List { null, null };
- }
+ private void ResetList() => _currentRenderTargets = new List { null, null };
private readonly IGL _gl;
private List _currentRenderTargets;
- public RenderTarget Get(Size dimensions)
- {
- return Get(dimensions.Width, dimensions.Height);
- }
+ public RenderTarget Get(Size dimensions) => Get(dimensions.Width, dimensions.Height);
public RenderTarget Get(int width, int height)
{
//get the current entry
- RenderTarget currentRenderTarget = _currentRenderTargets[0];
+ var currentRenderTarget = _currentRenderTargets[0];
//check if its rotten and needs recreating
if (currentRenderTarget == null
diff --git a/src/BizHawk.Client.Common/DisplayManager/TextureFrugalizer.cs b/src/BizHawk.Client.Common/DisplayManager/TextureFrugalizer.cs
index a084d8f5068..0d908108f8a 100644
--- a/src/BizHawk.Client.Common/DisplayManager/TextureFrugalizer.cs
+++ b/src/BizHawk.Client.Common/DisplayManager/TextureFrugalizer.cs
@@ -26,23 +26,20 @@ public void Dispose()
ResetList();
}
- private void ResetList()
- {
- _currentTextures = new List { null, null };
- }
+ private void ResetList() => _currentTextures = new List { null, null };
private readonly IGL _gl;
private List _currentTextures;
public Texture2d Get(IDisplaySurface ds)
{
- using var bb = new BitmapBuffer(ds.PeekBitmap(), new BitmapLoadOptions());
+ using BitmapBuffer bb = new(ds.PeekBitmap(), new BitmapLoadOptions());
return Get(bb);
}
public Texture2d Get(BitmapBuffer bb)
{
//get the current entry
- Texture2d currentTexture = _currentTextures[0];
+ var currentTexture = _currentTextures[0];
// TODO - its a bit cruddy here that we don't respect the current texture HasAlpha condition (in fact, there's no such concept)
// we might need to deal with that in the future to fix some bugs.
diff --git a/src/BizHawk.Client.Common/FilesystemFilter.cs b/src/BizHawk.Client.Common/FilesystemFilter.cs
index e05a06c4c67..b82e17a85e2 100644
--- a/src/BizHawk.Client.Common/FilesystemFilter.cs
+++ b/src/BizHawk.Client.Common/FilesystemFilter.cs
@@ -55,24 +55,24 @@ public FilesystemFilter(
public static readonly IReadOnlyCollection DiscExtensions = new[] { "cue", "ccd", "cdi", "iso", "mds", "m3u", "nrg" };
- public static readonly FilesystemFilter Archives = new FilesystemFilter("Archives", ArchiveExtensions);
+ public static readonly FilesystemFilter Archives = new("Archives", ArchiveExtensions);
- public static readonly FilesystemFilter BizHawkMovies = new FilesystemFilter("Movie Files", new[] { MovieService.StandardMovieExtension });
+ public static readonly FilesystemFilter BizHawkMovies = new("Movie Files", new[] { MovieService.StandardMovieExtension });
- public static readonly FilesystemFilter EmuHawkSaveStates = new FilesystemFilter("Save States", new[] { "State" });
+ public static readonly FilesystemFilter EmuHawkSaveStates = new("Save States", new[] { "State" });
- public static readonly FilesystemFilter LuaScripts = new FilesystemFilter("Lua Scripts", new[] { "lua" });
+ public static readonly FilesystemFilter LuaScripts = new("Lua Scripts", new[] { "lua" });
- public static readonly FilesystemFilter PNGs = new FilesystemFilter("PNG Files", new[] { "png" });
+ public static readonly FilesystemFilter PNGs = new("PNG Files", new[] { "png" });
- public static readonly FilesystemFilter TAStudioProjects = new FilesystemFilter("TAS Project Files", new[] { MovieService.TasMovieExtension });
+ public static readonly FilesystemFilter TAStudioProjects = new("TAS Project Files", new[] { MovieService.TasMovieExtension });
- public static readonly FilesystemFilter TextFiles = new FilesystemFilter("Text Files", new[] { "txt" });
+ public static readonly FilesystemFilter TextFiles = new("Text Files", new[] { "txt" });
/// return value is a valid Filter for Save- /OpenFileDialog
public static string SerializeEntry(string desc, IReadOnlyCollection exts)
{
- var joinedLower = string.Join(";", exts.Select(static ext => $"*.{ext}"));
+ string joinedLower = string.Join(";", exts.Select(static ext => $"*.{ext}"));
return OSTailoredCode.IsUnixHost
? $"{desc} ({joinedLower})|{string.Join(";", exts.Select(static ext => $"*.{ext};*.{ext.ToUpperInvariant()}"))}"
: $"{desc} ({joinedLower})|{joinedLower}";
diff --git a/src/BizHawk.Client.Common/FilesystemFilterSet.cs b/src/BizHawk.Client.Common/FilesystemFilterSet.cs
index f29314e55c6..5e81f58788c 100644
--- a/src/BizHawk.Client.Common/FilesystemFilterSet.cs
+++ b/src/BizHawk.Client.Common/FilesystemFilterSet.cs
@@ -27,7 +27,7 @@ public override string ToString()
{
if (_ser is null)
{
- var entries = Filters.Select(static filter => filter.ToString()).ToList();
+ List entries = Filters.Select(static filter => filter.ToString()).ToList();
if (CombinedEntryDesc is not null) entries.Insert(0, FilesystemFilter.SerializeEntry(CombinedEntryDesc, CombinedExts));
if (AppendAllFilesEntry) entries.Add(FilesystemFilter.AllFilesEntry);
_ser = string.Join("|", entries);
@@ -37,6 +37,6 @@ public override string ToString()
public static readonly FilesystemFilterSet Palettes = new(new FilesystemFilter("Palette Files", new[] { "pal" }));
- public static readonly FilesystemFilterSet Screenshots = new FilesystemFilterSet(FilesystemFilter.PNGs, new FilesystemFilter(".bmp Files", new[] { "bmp" }));
+ public static readonly FilesystemFilterSet Screenshots = new(FilesystemFilter.PNGs, new FilesystemFilter(".bmp Files", new[] { "bmp" }));
}
}
diff --git a/src/BizHawk.Client.Common/OpenAdvanced.cs b/src/BizHawk.Client.Common/OpenAdvanced.cs
index 394a100fd17..2d05f95a0f0 100644
--- a/src/BizHawk.Client.Common/OpenAdvanced.cs
+++ b/src/BizHawk.Client.Common/OpenAdvanced.cs
@@ -60,20 +60,14 @@ private static IOpenAdvanced Deserialize(string text)
OpenAdvancedTypes.LibretroNoGame => new OpenAdvanced_LibretroNoGame(),
OpenAdvancedTypes.MAME => new OpenAdvanced_MAME(),
_ => null
- };
-
- if (ioa == null)
- {
- throw new InvalidOperationException($"{nameof(IOpenAdvanced)} deserialization error");
- }
-
+ } ?? throw new InvalidOperationException($"{nameof(IOpenAdvanced)} deserialization error");
ioa.Deserialize(token);
return ioa;
}
public static string Serialize(IOpenAdvanced ioa)
{
- var sw = new StringWriter();
+ StringWriter sw = new();
sw.Write("{0}*", ioa.TypeName);
ioa.Serialize(sw);
return sw.ToString();
@@ -93,15 +87,9 @@ public struct Token
public string DisplayName => $"{Path.GetFileNameWithoutExtension(token.CorePath)}: {token.Path}";
public string SimplePath => token.Path;
- public void Deserialize(string str)
- {
- token = JsonConvert.DeserializeObject(str);
- }
-
- public void Serialize(TextWriter tw)
- {
- tw.Write(JsonConvert.SerializeObject(token));
- }
+ public void Deserialize(string str) => token = JsonConvert.DeserializeObject(str);
+
+ public void Serialize(TextWriter tw) => tw.Write(JsonConvert.SerializeObject(token));
public string CorePath
{
@@ -131,15 +119,9 @@ public OpenAdvanced_LibretroNoGame(string corePath)
public string DisplayName => Path.GetFileName(CorePath); // assume we like the filename of the core
public string SimplePath => ""; // effectively a signal to not use a game
- public void Deserialize(string str)
- {
- CorePath = str;
- }
+ public void Deserialize(string str) => CorePath = str;
- public void Serialize(TextWriter tw)
- {
- tw.Write(CorePath);
- }
+ public void Serialize(TextWriter tw) => tw.Write(CorePath);
public string CorePath { get; set; }
}
@@ -152,15 +134,9 @@ public class OpenAdvanced_OpenRom : IOpenAdvanced
public string DisplayName => Path;
public string SimplePath => Path;
- public void Deserialize(string str)
- {
- Path = str;
- }
+ public void Deserialize(string str) => Path = str;
- public void Serialize(TextWriter tw)
- {
- tw.Write(Path);
- }
+ public void Serialize(TextWriter tw) => tw.Write(Path);
}
public class OpenAdvanced_MAME : IOpenAdvanced
@@ -171,14 +147,8 @@ public class OpenAdvanced_MAME : IOpenAdvanced
public string DisplayName => $"{TypeName}: {Path}";
public string SimplePath => Path;
- public void Deserialize(string str)
- {
- Path = str;
- }
+ public void Deserialize(string str) => Path = str;
- public void Serialize(TextWriter tw)
- {
- tw.Write(Path);
- }
+ public void Serialize(TextWriter tw) => tw.Write(Path);
}
}
\ No newline at end of file
diff --git a/src/BizHawk.Client.Common/QuickBmpFile.cs b/src/BizHawk.Client.Common/QuickBmpFile.cs
index 4e7d18136d7..83f0356e5dc 100644
--- a/src/BizHawk.Client.Common/QuickBmpFile.cs
+++ b/src/BizHawk.Client.Common/QuickBmpFile.cs
@@ -233,8 +233,8 @@ public class LoadedBMP : IVideoProvider
public static unsafe bool Load(IVideoProvider v, Stream s)
{
- var bf = BITMAPFILEHEADER.FromStream(s);
- var bi = BITMAPINFOHEADER.FromStream(s);
+ BITMAPFILEHEADER bf = BITMAPFILEHEADER.FromStream(s);
+ BITMAPINFOHEADER bi = BITMAPINFOHEADER.FromStream(s);
if (bf.bfType != 0x4d42
|| bf.bfOffBits != bf.bfSize + bi.biSize
|| bi.biPlanes != 1
@@ -251,7 +251,7 @@ public static unsafe bool Load(IVideoProvider v, Stream s)
s.Read(src, 0, src.Length);
if (v is LoadedBMP)
{
- var l = v as LoadedBMP;
+ LoadedBMP l = v as LoadedBMP;
l.BufferWidth = inW;
l.BufferHeight = inH;
l.VideoBuffer = new int[inW * inH];
@@ -284,8 +284,8 @@ public static unsafe bool Load(IVideoProvider v, Stream s)
public static unsafe void Save(IVideoProvider v, Stream s, int w, int h)
{
- var bf = new BITMAPFILEHEADER();
- var bi = new BITMAPINFOHEADER();
+ BITMAPFILEHEADER bf = new();
+ BITMAPINFOHEADER bi = new();
bf.bfType = 0x4d42;
bf.bfOffBits = bf.bfSize + bi.biSize;
diff --git a/src/BizHawk.Client.Common/RecentFiles.cs b/src/BizHawk.Client.Common/RecentFiles.cs
index 041cd971774..1ab262a3d30 100644
--- a/src/BizHawk.Client.Common/RecentFiles.cs
+++ b/src/BizHawk.Client.Common/RecentFiles.cs
@@ -10,7 +10,7 @@ namespace BizHawk.Client.Common
public class RecentFiles : IEnumerable
{
// ReSharper disable once FieldCanBeMadeReadOnly.Local
- private List recentlist;
+ private readonly List recentlist;
public RecentFiles()
: this(8)
@@ -77,9 +77,6 @@ public bool Remove(string newFile)
return false;
}
- public void ToggleAutoLoad()
- {
- AutoLoad ^= true;
- }
+ public void ToggleAutoLoad() => AutoLoad ^= true;
}
}
diff --git a/src/BizHawk.Client.Common/RomGame.cs b/src/BizHawk.Client.Common/RomGame.cs
index 1b255178096..33f794de926 100644
--- a/src/BizHawk.Client.Common/RomGame.cs
+++ b/src/BizHawk.Client.Common/RomGame.cs
@@ -105,15 +105,15 @@ public RomGame(HawkFile file, string patch)
{
RomData = FileData;
}
- else if (file.Extension == ".dsk" || file.Extension == ".tap" || file.Extension == ".tzx" ||
- file.Extension == ".pzx" || file.Extension == ".csw" || file.Extension == ".wav" || file.Extension == ".cdt")
+ else if (file.Extension is ".dsk" or ".tap" or ".tzx" or
+ ".pzx" or ".csw" or ".wav" or ".cdt")
{
// these are not roms. unfortunately if treated as such there are certain edge-cases
// where a header offset is detected. This should mitigate this issue until a cleaner solution is found
// (-Asnivor)
RomData = FileData;
}
- else if (SHA1_check == Flappy_Bird_INTV || SHA1_check == Minehunter_INTV)
+ else if (SHA1_check is Flappy_Bird_INTV or Minehunter_INTV)
{
// several INTV games have sizes that are multiples of 512 bytes
Console.WriteLine("False positive detected in Header Check, using entire file.");
@@ -147,19 +147,19 @@ public RomGame(HawkFile file, string patch)
CheckForPatchOptions();
if (patch is null) return;
- using var patchFile = new HawkFile(patch);
+ using HawkFile patchFile = new(patch);
patchFile.BindFirstOf(".ips");
if (!patchFile.IsBound) patchFile.BindFirstOf(".bps");
if (!patchFile.IsBound) return;
- var patchBytes = patchFile.GetStream().ReadAllBytes();
+ byte[] patchBytes = patchFile.GetStream().ReadAllBytes();
if (BPSPatcher.IsIPSFile(patchBytes))
{
RomData = BPSPatcher.Patch(RomData, new BPSPatcher.IPSPayload(patchBytes));
}
else if (BPSPatcher.IsBPSFile(patchBytes, out var patchStruct))
{
- var ignoreBaseChecksum = true; //TODO check base checksum and ask user before continuing
- RomData = BPSPatcher.Patch(StripSNESDumpHeader(RomData), patchStruct, out var checksumsMatch);
+ bool ignoreBaseChecksum = true; //TODO check base checksum and ask user before continuing
+ RomData = BPSPatcher.Patch(StripSNESDumpHeader(RomData), patchStruct, out bool checksumsMatch);
if (!checksumsMatch && !ignoreBaseChecksum) throw new Exception("BPS patch didn't produce the expected output");
}
else
@@ -183,7 +183,7 @@ private static byte[] DeInterleaveSMD(byte[] source)
}
int pages = size / 0x4000;
- var output = new byte[size];
+ byte[] output = new byte[size];
for (int page = 0; page < pages; page++)
{
@@ -203,10 +203,10 @@ private void CheckForPatchOptions()
{
if (GameInfo["PatchBytes"])
{
- var args = GameInfo.OptionValue("PatchBytes");
- foreach (var val in args.Split(','))
+ string args = GameInfo.OptionValue("PatchBytes");
+ foreach (string val in args.Split(','))
{
- var split = val.Split(':');
+ string[] split = val.Split(':');
int offset = int.Parse(split[0], NumberStyles.HexNumber);
byte value = byte.Parse(split[1], NumberStyles.HexNumber);
RomData[offset] = value;
diff --git a/src/BizHawk.Client.Common/RomLoader.cs b/src/BizHawk.Client.Common/RomLoader.cs
index d4411bc1bfc..9ecac749a5a 100644
--- a/src/BizHawk.Client.Common/RomLoader.cs
+++ b/src/BizHawk.Client.Common/RomLoader.cs
@@ -71,20 +71,14 @@ public enum LoadErrorType
// helper methods for the settings events
private TSetting GetCoreSettings()
- where TCore : IEmulator
- {
- return (TSetting)GetCoreSettings(typeof(TCore), typeof(TSetting));
- }
+ where TCore : IEmulator => (TSetting)GetCoreSettings(typeof(TCore), typeof(TSetting));
private TSync GetCoreSyncSettings()
- where TCore : IEmulator
- {
- return (TSync)GetCoreSyncSettings(typeof(TCore), typeof(TSync));
- }
+ where TCore : IEmulator => (TSync)GetCoreSyncSettings(typeof(TCore), typeof(TSync));
private object GetCoreSettings(Type t, Type settingsType)
{
- var e = new SettingsLoadArgs(t, settingsType);
+ SettingsLoadArgs e = new(t, settingsType);
if (OnLoadSettings == null)
throw new InvalidOperationException("Frontend failed to provide a settings getter");
OnLoadSettings(this, e);
@@ -95,7 +89,7 @@ private object GetCoreSettings(Type t, Type settingsType)
private object GetCoreSyncSettings(Type t, Type syncSettingsType)
{
- var e = new SettingsLoadArgs(t, syncSettingsType);
+ SettingsLoadArgs e = new(t, syncSettingsType);
if (OnLoadSyncSettings == null)
throw new InvalidOperationException("Frontend failed to provide a sync settings getter");
OnLoadSyncSettings(this, e);
@@ -183,15 +177,9 @@ public SettingsLoadArgs(Type t, Type s)
}
// May want to phase out this method in favor of the overload with more parameters
- private void DoLoadErrorCallback(string message, string systemId, LoadErrorType type = LoadErrorType.Unknown)
- {
- OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, type));
- }
+ private void DoLoadErrorCallback(string message, string systemId, LoadErrorType type = LoadErrorType.Unknown) => OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, type));
- private void DoLoadErrorCallback(string message, string systemId, string path, bool det, LoadErrorType type = LoadErrorType.Unknown)
- {
- OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, path, det, type));
- }
+ private void DoLoadErrorCallback(string message, string systemId, string path, bool det, LoadErrorType type = LoadErrorType.Unknown) => OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, path, det, type));
public IOpenAdvanced OpenAdvanced { get; set; }
@@ -205,7 +193,7 @@ private bool HandleArchiveBinding(HawkFile file)
// ...including unrecognised extensions that the user has set a platform for
if (!file.IsBound)
{
- var exts = _config.PreferredPlatformsForExtensions.Where(static kvp => !string.IsNullOrEmpty(kvp.Value))
+ List exts = _config.PreferredPlatformsForExtensions.Where(static kvp => !string.IsNullOrEmpty(kvp.Value))
.Select(static kvp => kvp.Key)
.ToList();
if (exts.Count is not 0) file.BindSoleItemOf(exts);
@@ -234,8 +222,8 @@ private GameInfo MakeGameFromDisc(Disc disc, string ext, string name)
{
// TODO - use more sophisticated IDer
var discType = new DiscIdentifier(disc).DetectDiscType();
- var discHasher = new DiscHasher(disc);
- var discHash = discType == DiscType.SonyPSX
+ DiscHasher discHasher = new(disc);
+ string discHash = discType == DiscType.SonyPSX
? discHasher.Calculate_PSX_BizIDHash()
: discHasher.OldHash();
@@ -249,59 +237,27 @@ Exception NoCoreForSystem(string sysID)
game.System = sysID;
return new NoAvailableCoreException(sysID);
}
- switch (discType)
- {
- case DiscType.SegaSaturn:
- game.System = VSystemID.Raw.SAT;
- break;
- case DiscType.MegaCD:
- game.System = VSystemID.Raw.GEN;
- break;
- case DiscType.PCFX:
- game.System = VSystemID.Raw.PCFX;
- break;
-
- case DiscType.TurboGECD:
- case DiscType.TurboCD:
- game.System = VSystemID.Raw.PCE;
- break;
-
- case DiscType.JaguarCD:
- game.System = VSystemID.Raw.Jaguar;
- break;
-
- case DiscType.Amiga:
- throw NoCoreForSystem(VSystemID.Raw.Amiga);
- case DiscType.CDi:
- throw NoCoreForSystem(VSystemID.Raw.PhillipsCDi);
- case DiscType.Dreamcast:
- throw NoCoreForSystem(VSystemID.Raw.Dreamcast);
- case DiscType.GameCube:
- throw NoCoreForSystem(VSystemID.Raw.GameCube);
- case DiscType.NeoGeoCD:
- throw NoCoreForSystem(VSystemID.Raw.NeoGeoCD);
- case DiscType.Panasonic3DO:
- throw NoCoreForSystem(VSystemID.Raw.Panasonic3DO);
- case DiscType.Playdia:
- throw NoCoreForSystem(VSystemID.Raw.Playdia);
- case DiscType.SonyPS2:
- throw NoCoreForSystem(VSystemID.Raw.PS2);
- case DiscType.SonyPSP:
- throw NoCoreForSystem(VSystemID.Raw.PSP);
- case DiscType.Wii:
- throw NoCoreForSystem(VSystemID.Raw.Wii);
-
- case DiscType.AudioDisc:
- case DiscType.UnknownCDFS:
- case DiscType.UnknownFormat:
- game.System = _config.TryGetChosenSystemForFileExt(ext, out var sysID) ? sysID : VSystemID.Raw.NULL;
- break;
-
- default: //"for an unknown disc, default to psx instead of pce-cd, since that is far more likely to be what they are attempting to open" [5e07ab3ec3b8b8de9eae71b489b55d23a3909f55, year 2015]
- case DiscType.SonyPSX:
- game.System = VSystemID.Raw.PSX;
- break;
- }
+ game.System = discType switch
+ {
+ DiscType.SegaSaturn => VSystemID.Raw.SAT,
+ DiscType.MegaCD => VSystemID.Raw.GEN,
+ DiscType.PCFX => VSystemID.Raw.PCFX,
+ DiscType.TurboGECD or DiscType.TurboCD => VSystemID.Raw.PCE,
+ DiscType.JaguarCD => VSystemID.Raw.Jaguar,
+ DiscType.Amiga => throw NoCoreForSystem(VSystemID.Raw.Amiga),
+ DiscType.CDi => throw NoCoreForSystem(VSystemID.Raw.PhillipsCDi),
+ DiscType.Dreamcast => throw NoCoreForSystem(VSystemID.Raw.Dreamcast),
+ DiscType.GameCube => throw NoCoreForSystem(VSystemID.Raw.GameCube),
+ DiscType.NeoGeoCD => throw NoCoreForSystem(VSystemID.Raw.NeoGeoCD),
+ DiscType.Panasonic3DO => throw NoCoreForSystem(VSystemID.Raw.Panasonic3DO),
+ DiscType.Playdia => throw NoCoreForSystem(VSystemID.Raw.Playdia),
+ DiscType.SonyPS2 => throw NoCoreForSystem(VSystemID.Raw.PS2),
+ DiscType.SonyPSP => throw NoCoreForSystem(VSystemID.Raw.PSP),
+ DiscType.Wii => throw NoCoreForSystem(VSystemID.Raw.Wii),
+ DiscType.AudioDisc or DiscType.UnknownCDFS or DiscType.UnknownFormat => _config.TryGetChosenSystemForFileExt(ext, out string sysID) ? sysID : VSystemID.Raw.NULL,
+ //"for an unknown disc, default to psx instead of pce-cd, since that is far more likely to be what they are attempting to open" [5e07ab3ec3b8b8de9eae71b489b55d23a3909f55, year 2015]
+ _ => VSystemID.Raw.PSX,
+ };
return game;
}
@@ -317,7 +273,7 @@ private bool LoadDisc(string path, CoreComm nextComm, HawkFile file, string ext,
game = MakeGameFromDisc(disc, ext, Path.GetFileNameWithoutExtension(file.Name));
- var cip = new CoreInventoryParameters(this)
+ CoreInventoryParameters cip = new(this)
{
Comm = nextComm,
Game = game,
@@ -338,13 +294,13 @@ private bool LoadDisc(string path, CoreComm nextComm, HawkFile file, string ext,
private void LoadM3U(string path, CoreComm nextComm, HawkFile file, string forcedCoreName, out IEmulator nextEmulator, out GameInfo game)
{
M3U_File m3u;
- using (var sr = new StreamReader(path))
+ using (StreamReader sr = new(path))
m3u = M3U_File.Read(sr);
if (m3u.Entries.Count == 0)
throw new InvalidOperationException("Can't load an empty M3U");
m3u.Rebase(Path.GetDirectoryName(path));
- var discs = m3u.Entries
+ List discs = m3u.Entries
.Select(e => e.Path)
.Where(p => Disc.IsValidExtension(Path.GetExtension(p)))
.Select(path => (p: path, d: DiscExtensions.CreateAnyType(path, str => DoLoadErrorCallback(str, "???", LoadErrorType.DiscError))))
@@ -360,7 +316,7 @@ private void LoadM3U(string path, CoreComm nextComm, HawkFile file, string force
throw new InvalidOperationException("Couldn't load any contents of the M3U as discs");
game = MakeGameFromDisc(discs[0].DiscData, Path.GetExtension(m3u.Entries[0].Path), discs[0].DiscName);
- var cip = new CoreInventoryParameters(this)
+ CoreInventoryParameters cip = new(this)
{
Comm = nextComm,
Game = game,
@@ -379,8 +335,8 @@ private IEmulator MakeCoreFromCoreInventory(CoreInventoryParameters cip, string
}
else
{
- _ = _config.PreferredCores.TryGetValue(cip.Game.System, out var preferredCore);
- var dbForcedCoreName = cip.Game.ForcedCore;
+ _ = _config.PreferredCores.TryGetValue(cip.Game.System, out string preferredCore);
+ string dbForcedCoreName = cip.Game.ForcedCore;
cores = CoreInventory.Instance.GetCores(cip.Game.System)
.OrderBy(c =>
{
@@ -399,7 +355,7 @@ private IEmulator MakeCoreFromCoreInventory(CoreInventoryParameters cip, string
.ToList();
if (cores.Count == 0) throw new InvalidOperationException("No core was found to try on the game");
}
- var exceptions = new List();
+ List exceptions = new();
foreach (var core in cores)
{
try
@@ -443,13 +399,13 @@ private void LoadOther(
if (string.IsNullOrEmpty(rom.GameInfo.System))
{
// Has the user picked a preference for this extension?
- if (_config.TryGetChosenSystemForFileExt(rom.Extension.ToLowerInvariant(), out var systemID))
+ if (_config.TryGetChosenSystemForFileExt(rom.Extension.ToLowerInvariant(), out string systemID))
{
rom.GameInfo.System = systemID;
}
else if (ChoosePlatform != null)
{
- var result = ChoosePlatform(rom);
+ string result = ChoosePlatform(rom);
if (!string.IsNullOrEmpty(result))
{
rom.GameInfo.System = result;
@@ -490,7 +446,7 @@ private void LoadOther(
break;
case VSystemID.Raw.PSX when ext is ".bin":
const string FILE_EXT_CUE = ".cue";
- var cuePath = TempFileManager.GetTempFilename(friendlyName: "syn", dotAndExtension: FILE_EXT_CUE, delete: false);
+ string cuePath = TempFileManager.GetTempFilename(friendlyName: "syn", dotAndExtension: FILE_EXT_CUE, delete: false);
DiscMountJob.CreateSyntheticCue(cueFilePath: cuePath, binFilePath: file.Name);
var gameBak = game;
var nextEmulatorBak = nextEmulator;
@@ -517,7 +473,7 @@ private void LoadOther(
nextEmulator = nextEmulatorBak;
break;
}
- var cip = new CoreInventoryParameters(this)
+ CoreInventoryParameters cip = new(this)
{
Comm = nextComm,
Game = game,
@@ -543,7 +499,7 @@ static byte[] CbDeflater(Stream instream, int size)
{
return new GZipStream(instream, CompressionMode.Decompress).ReadAllBytes();
}
- var psf = new PSF();
+ PSF psf = new();
psf.Load(path, CbDeflater);
nextEmulator = new Octoshock(
nextComm,
@@ -564,11 +520,11 @@ private bool LoadXML(string path, CoreComm nextComm, HawkFile file, string force
game = null;
try
{
- var xmlGame = XmlGame.Create(file); // if load fails, are we supposed to retry as a bsnes XML????????
+ XmlGame xmlGame = XmlGame.Create(file); // if load fails, are we supposed to retry as a bsnes XML????????
game = xmlGame.GI;
- var system = game.System;
- var cip = new CoreInventoryParameters(this)
+ string system = game.System;
+ CoreInventoryParameters cip = new(this)
{
Comm = nextComm,
Game = game,
@@ -643,7 +599,7 @@ private void LoadMAME(
{
try
{
- using var f = new HawkFile(path, allowArchives: true);
+ using HawkFile f = new(path, allowArchives: true);
if (!HandleArchiveBinding(f)) throw;
LoadOther(nextComm, f, ext: ext, forcedCoreName: null, out nextEmulator, out rom, out game, out cancel);
}
@@ -667,7 +623,7 @@ public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, s
bool allowArchives = true;
if (OpenAdvanced is OpenAdvanced_MAME || MAMEMachineDB.IsMAMEMachine(path)) allowArchives = false;
- using var file = new HawkFile(path, false, allowArchives);
+ using HawkFile file = new(path, false, allowArchives);
if (!file.Exists && OpenAdvanced is not OpenAdvanced_LibretroNoGame) return false; // if the provided file doesn't even exist, give up! (unless libretro no game is used)
CanonicalFullPath = file.CanonicalFullPath;
@@ -678,14 +634,14 @@ public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, s
try
{
- var cancel = false;
+ bool cancel = false;
if (OpenAdvanced is OpenAdvanced_Libretro or OpenAdvanced_LibretroNoGame)
{
// must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
// game name == name of core
Game = game = new GameInfo { Name = Path.GetFileNameWithoutExtension(launchLibretroCore), System = VSystemID.Raw.Libretro };
- var retro = new LibretroHost(nextComm, game, launchLibretroCore);
+ LibretroHost retro = new(nextComm, game, launchLibretroCore);
nextEmulator = retro;
if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path))
@@ -743,7 +699,7 @@ public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, s
}
// not libretro: do extension checking
- var ext = file.Extension;
+ string ext = file.Extension;
switch (ext)
{
case ".m3u":
@@ -800,7 +756,7 @@ public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, s
}
catch (Exception ex)
{
- var system = game?.System;
+ string system = game?.System;
DispatchErrorMessage(ex, system: system, path: path);
return false;
@@ -821,7 +777,7 @@ private void DispatchErrorMessage(Exception ex, string system, string path)
{
DoLoadErrorCallback("Multiple cores failed to load the rom:", system);
}
- foreach (Exception e in agg.InnerExceptions)
+ foreach (var e in agg.InnerExceptions)
{
DispatchErrorMessage(e, system: system, path: path);
}
diff --git a/src/BizHawk.Client.Common/SaveSlotManager.cs b/src/BizHawk.Client.Common/SaveSlotManager.cs
index 96bfa3221ea..6a5609248de 100644
--- a/src/BizHawk.Client.Common/SaveSlotManager.cs
+++ b/src/BizHawk.Client.Common/SaveSlotManager.cs
@@ -31,7 +31,7 @@ public void Update(IEmulator emulator, IMovie movie, string saveStatePrefix)
}
else
{
- var file = new FileInfo($"{saveStatePrefix}.QuickSave{i % 10}.State");
+ FileInfo file = new($"{saveStatePrefix}.QuickSave{i % 10}.State");
if (file.Directory != null && file.Directory.Exists == false)
{
file.Directory.Create();
@@ -77,9 +77,9 @@ public bool IsRedo(IMovie movie, int slot)
public void SwapBackupSavestate(IMovie movie, string path, int currentSlot)
{
// Takes the .state and .bak files and swaps them
- var state = new FileInfo(path);
- var backup = new FileInfo($"{path}.bak");
- var temp = new FileInfo($"{path}.bak.tmp");
+ FileInfo state = new(path);
+ FileInfo backup = new($"{path}.bak");
+ FileInfo temp = new($"{path}.bak.tmp");
if (!state.Exists || !backup.Exists)
{
diff --git a/src/BizHawk.Client.Common/SharpCompressArchiveFile.cs b/src/BizHawk.Client.Common/SharpCompressArchiveFile.cs
index 13f0c4112b2..b7c696df8cf 100644
--- a/src/BizHawk.Client.Common/SharpCompressArchiveFile.cs
+++ b/src/BizHawk.Client.Common/SharpCompressArchiveFile.cs
@@ -37,7 +37,7 @@ public void Dispose()
public void ExtractFile(int index, Stream stream)
{
var reader = _archive!.ExtractAllEntries();
- for (var i = 0; i <= index; i++) reader.MoveToNextEntry();
+ for (int i = 0; i <= index; i++) reader.MoveToNextEntry();
using var entryStream = reader.OpenEntryStream();
entryStream.CopyTo(stream);
}
@@ -45,8 +45,8 @@ public void ExtractFile(int index, Stream stream)
public List? Scan()
{
List outFiles = new();
- var entries = EnumerateArchiveFiles().ToList();
- for (var i = 0; i < entries.Count; i++)
+ List<(IArchiveEntry Entry, int ArchiveIndex)> entries = EnumerateArchiveFiles().ToList();
+ for (int i = 0; i < entries.Count; i++)
{
var (entry, archiveIndex) = entries[i];
if (entry.Key is null) return null; // see https://github.com/adamhathcock/sharpcompress/issues/137
diff --git a/src/BizHawk.Client.Common/SharpCompressDearchivalMethod.cs b/src/BizHawk.Client.Common/SharpCompressDearchivalMethod.cs
index dd4143bf513..acbb23d7e47 100644
--- a/src/BizHawk.Client.Common/SharpCompressDearchivalMethod.cs
+++ b/src/BizHawk.Client.Common/SharpCompressDearchivalMethod.cs
@@ -40,10 +40,10 @@ public bool CheckSignature(string fileName, out int offset, out bool isExecutabl
// looking for magic bytes
fs.Seek(0x101, SeekOrigin.Begin);
- var buffer = new byte[8];
+ byte[] buffer = new byte[8];
fs.Read(buffer, 0, 8);
- var s = buffer.BytesToHexString();
- if (s == "7573746172003030" || s == "7573746172202000") return true; // "ustar\000" (libarchive's bsdtar) or "ustar \0" (GNU Tar)
+ string s = buffer.BytesToHexString();
+ if (s is "7573746172003030" or "7573746172202000") return true; // "ustar\000" (libarchive's bsdtar) or "ustar \0" (GNU Tar)
Console.WriteLine($"SharpCompress identified file as original .tar format, probably a false positive, ignoring. Filename: {fileName}");
return false;
@@ -67,13 +67,13 @@ public bool CheckSignature(Stream fileStream, string? filenameHint)
if (fileStream.Length < 512) return false;
// looking for magic bytes
- var seekPos = fileStream.Position;
+ long seekPos = fileStream.Position;
fileStream.Seek(0x101, SeekOrigin.Begin);
- var buffer = new byte[8];
+ byte[] buffer = new byte[8];
fileStream.Read(buffer, 0, 8);
fileStream.Seek(seekPos, SeekOrigin.Begin);
- var s = buffer.BytesToHexString();
- if (s == "7573746172003030" || s == "7573746172202000") return true; // "ustar\000" (libarchive's bsdtar) or "ustar \0" (GNU Tar)
+ string s = buffer.BytesToHexString();
+ if (s is "7573746172003030" or "7573746172202000") return true; // "ustar\000" (libarchive's bsdtar) or "ustar \0" (GNU Tar)
Console.WriteLine($"SharpCompress identified file in stream as original .tar format, probably a false positive, ignoring. Filename hint: {filenameHint}");
return false;
diff --git a/src/BizHawk.Client.Common/Sound/HostAudioManagerExtensions.cs b/src/BizHawk.Client.Common/Sound/HostAudioManagerExtensions.cs
index 53453c6ac0f..9b10999bc58 100644
--- a/src/BizHawk.Client.Common/Sound/HostAudioManagerExtensions.cs
+++ b/src/BizHawk.Client.Common/Sound/HostAudioManagerExtensions.cs
@@ -2,14 +2,8 @@ namespace BizHawk.Client.Common
{
public static class HostAudioManagerExtensions
{
- public static int MillisecondsToSamples(this IHostAudioManager audioMan, int milliseconds)
- {
- return milliseconds * audioMan.SampleRate / 1000;
- }
+ public static int MillisecondsToSamples(this IHostAudioManager audioMan, int milliseconds) => milliseconds * audioMan.SampleRate / 1000;
- public static double SamplesToMilliseconds(this IHostAudioManager audioMan, int samples)
- {
- return samples * 1000.0 / audioMan.SampleRate;
- }
+ public static double SamplesToMilliseconds(this IHostAudioManager audioMan, int samples) => samples * 1000.0 / audioMan.SampleRate;
}
}
diff --git a/src/BizHawk.Client.Common/Sound/Output/DummySoundOutput.cs b/src/BizHawk.Client.Common/Sound/Output/DummySoundOutput.cs
index 31d5839e551..8e4531afb37 100644
--- a/src/BizHawk.Client.Common/Sound/Output/DummySoundOutput.cs
+++ b/src/BizHawk.Client.Common/Sound/Output/DummySoundOutput.cs
@@ -34,10 +34,7 @@ public void StartSound()
_lastWriteTime = 0;
}
- public void StopSound()
- {
- BufferSizeSamples = 0;
- }
+ public void StopSound() => BufferSizeSamples = 0;
public int CalculateSamplesNeeded()
{
diff --git a/src/BizHawk.Client.Common/Sound/Utilities/BufferedAsync.cs b/src/BizHawk.Client.Common/Sound/Utilities/BufferedAsync.cs
index 14795ab8978..038b86cf2fc 100644
--- a/src/BizHawk.Client.Common/Sound/Utilities/BufferedAsync.cs
+++ b/src/BizHawk.Client.Common/Sound/Utilities/BufferedAsync.cs
@@ -34,7 +34,7 @@ public sealed class BufferedAsync : ISoundProvider, IBufferedSoundProvider
{
public ISoundProvider BaseSoundProvider { get; set; }
- private readonly Queue buffer = new Queue(MaxExcessSamples);
+ private readonly Queue buffer = new(MaxExcessSamples);
private int SamplesInOneFrame = 1470;
private readonly int TargetExtraSamples = 882;
@@ -43,12 +43,9 @@ public sealed class BufferedAsync : ISoundProvider, IBufferedSoundProvider
///
/// recalculates some internal parameters based on the IEmulator's framerate
///
- public void RecalculateMagic(double framerate)
- {
+ public void RecalculateMagic(double framerate) =>
// ceiling instead of floor here is very important (magic)
- SamplesInOneFrame = 2 * (int)Math.Ceiling((44100.0 / framerate));
- //TargetExtraSamples = ;// complete guess
- }
+ SamplesInOneFrame = 2 * (int)Math.Ceiling((44100.0 / framerate));//TargetExtraSamples = ;// complete guess
public void DiscardSamples()
{
@@ -67,7 +64,7 @@ public void GetSamplesAsync(short[] samples)
if (samplesToGenerate + buffer.Count < samples.Length)
samplesToGenerate = samples.Length - buffer.Count;
- var mySamples = new short[samplesToGenerate];
+ short[] mySamples = new short[samplesToGenerate];
if (BaseSoundProvider.SyncMode != SyncSoundMode.Async)
{
@@ -100,9 +97,6 @@ public void SetSyncMode(SyncSoundMode mode)
}
/// always
- public void GetSamplesSync(out short[] samples, out int nsamp)
- {
- throw new InvalidOperationException("Sync mode is not supported.");
- }
+ public void GetSamplesSync(out short[] samples, out int nsamp) => throw new InvalidOperationException("Sync mode is not supported.");
}
}
\ No newline at end of file
diff --git a/src/BizHawk.Client.Common/Sound/Utilities/SoundOutputProvider.cs b/src/BizHawk.Client.Common/Sound/Utilities/SoundOutputProvider.cs
index 7c5b06bd25d..b89d767acf5 100644
--- a/src/BizHawk.Client.Common/Sound/Utilities/SoundOutputProvider.cs
+++ b/src/BizHawk.Client.Common/Sound/Utilities/SoundOutputProvider.cs
@@ -32,20 +32,20 @@ public class SoundOutputProvider : IBufferedSoundProvider
private readonly Func _getCoreVsyncRateCallback;
- private readonly Queue _buffer = new Queue();
+ private readonly Queue _buffer = new();
private readonly bool _standaloneMode;
private readonly int _targetExtraSamples;
private int _maxSamplesDeficit;
- private readonly Queue _extraCountHistory = new Queue();
- private readonly Queue _outputCountHistory = new Queue();
- private readonly Queue _hardCorrectionHistory = new Queue();
+ private readonly Queue _extraCountHistory = new();
+ private readonly Queue _outputCountHistory = new();
+ private readonly Queue _hardCorrectionHistory = new();
private int _baseConsecutiveEmptyFrames;
- private readonly Queue _baseEmptyFrameCorrectionHistory = new Queue();
+ private readonly Queue _baseEmptyFrameCorrectionHistory = new();
private double _lastAdvertisedSamplesPerFrame;
- private readonly Queue _baseSamplesPerFrame = new Queue();
+ private readonly Queue _baseSamplesPerFrame = new();
private short[] _outputBuffer = Array.Empty();
@@ -210,7 +210,7 @@ private void GetSamplesFromBase(ref double scaleFactor)
{
throw new InvalidOperationException("Base sound provider must be in sync mode.");
}
- BaseSoundProvider.GetSamplesSync(out var samples, out var count);
+ BaseSoundProvider.GetSamplesSync(out short[] samples, out int count);
bool correctedEmptyFrame = false;
if (count == 0)
diff --git a/src/BizHawk.Client.Common/Sound/Utilities/SyncToAsyncProvider.cs b/src/BizHawk.Client.Common/Sound/Utilities/SyncToAsyncProvider.cs
index bd311de14c3..c55fa10d364 100644
--- a/src/BizHawk.Client.Common/Sound/Utilities/SyncToAsyncProvider.cs
+++ b/src/BizHawk.Client.Common/Sound/Utilities/SyncToAsyncProvider.cs
@@ -16,10 +16,7 @@ public SyncToAsyncProvider(Func getCoreVsyncRateCallback, ISoundProvider
};
}
- public void DiscardSamples()
- {
- _outputProvider.DiscardSamples();
- }
+ public void DiscardSamples() => _outputProvider.DiscardSamples();
public bool CanProvideAsync => true;
@@ -35,14 +32,8 @@ public void SetSyncMode(SyncSoundMode mode)
}
/// always
- public void GetSamplesSync(out short[] samples, out int nsamp)
- {
- throw new InvalidOperationException("Sync mode is not supported.");
- }
+ public void GetSamplesSync(out short[] samples, out int nsamp) => throw new InvalidOperationException("Sync mode is not supported.");
- public void GetSamplesAsync(short[] samples)
- {
- _outputProvider.GetSamples(samples);
- }
+ public void GetSamplesAsync(short[] samples) => _outputProvider.GetSamples(samples);
}
}
diff --git a/src/BizHawk.Client.Common/XmlGame.cs b/src/BizHawk.Client.Common/XmlGame.cs
index 9684da4443e..ea54193c4d3 100644
--- a/src/BizHawk.Client.Common/XmlGame.cs
+++ b/src/BizHawk.Client.Common/XmlGame.cs
@@ -24,7 +24,7 @@ public static XmlGame Create(HawkFile f)
{
try
{
- var x = new XmlDocument();
+ XmlDocument x = new();
x.Load(f.GetStream());
var y = x.SelectSingleNode("./BizHawk-XMLGame");
if (y == null)
@@ -32,7 +32,7 @@ public static XmlGame Create(HawkFile f)
return null;
}
- var ret = new XmlGame
+ XmlGame ret = new()
{
GI =
{
@@ -42,17 +42,17 @@ public static XmlGame Create(HawkFile f)
},
Xml = x
};
- var fullPath = "";
+ string fullPath = "";
var n = y.SelectSingleNode("./LoadAssets");
if (n != null)
{
- var hashStream = new MemoryStream();
+ MemoryStream hashStream = new();
int? originalIndex = null;
foreach (XmlNode a in n.ChildNodes)
{
- var filename = a.Attributes!["FileName"].Value;
+ string filename = a.Attributes!["FileName"].Value;
byte[] data;
if (filename[0] == '|')
{
@@ -77,7 +77,7 @@ public static XmlGame Create(HawkFile f)
fullPath = Path.Combine(fullPath, filename.SubstringBefore('|'));
try
{
- using var hf = new HawkFile(fullPath, allowArchives: !MAMEMachineDB.IsMAMEMachine(fullPath));
+ using HawkFile hf = new(fullPath, allowArchives: !MAMEMachineDB.IsMAMEMachine(fullPath));
if (hf.IsArchive)
{
var archiveItem = hf.ArchiveItems.First(ai => ai.Name == filename.Split('|').Skip(1).First());
@@ -89,7 +89,7 @@ public static XmlGame Create(HawkFile f)
}
else
{
- var path = fullPath.SubstringBefore('|');
+ string path = fullPath.SubstringBefore('|');
data = RomGame.Is3DSRom(Path.GetExtension(path).ToUpperInvariant())
? Array.Empty()
: File.ReadAllBytes(path);
@@ -103,7 +103,7 @@ public static XmlGame Create(HawkFile f)
ret.Assets.Add(new(filename, data));
ret.AssetFullPaths.Add(fullPath);
- var sha1 = SHA1Checksum.Compute(data);
+ byte[] sha1 = SHA1Checksum.Compute(data);
hashStream.Write(sha1, 0, sha1.Length);
}
diff --git a/src/BizHawk.Client.Common/cheats/GameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/GameSharkDecoder.cs
index 54ac1058885..c6018abdba9 100644
--- a/src/BizHawk.Client.Common/cheats/GameSharkDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/GameSharkDecoder.cs
@@ -34,7 +34,7 @@ public IDecodeResult Decode(string code)
public MemoryDomain CheatDomain()
{
- var domain = CheatDomainName();
+ string domain = CheatDomainName();
return domain is null ? _domains.SystemBus : _domains[domain]!;
}
diff --git a/src/BizHawk.Client.Common/cheats/GbGameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/GbGameSharkDecoder.cs
index 14750d9b17d..1edb77dc2f1 100644
--- a/src/BizHawk.Client.Common/cheats/GbGameSharkDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/GbGameSharkDecoder.cs
@@ -22,20 +22,20 @@ public static IDecodeResult Decode(string code)
return new InvalidCheatCode("GameShark codes must be 8 characters with no dashes.");
}
- var test = code.Substring(0, 2);
- if (test != "00" && test != "01")
+ string test = code.Substring(0, 2);
+ if (test is not "00" and not "01")
{
return new InvalidCheatCode("All GameShark Codes for GameBoy need to start with 00 or 01");
}
- var result = new DecodeResult { Size = WatchSize.Byte };
+ DecodeResult result = new() { Size = WatchSize.Byte };
code = code.Remove(0, 2);
- var valueStr = code.Remove(2, 4);
+ string valueStr = code.Remove(2, 4);
code = code.Remove(0, 2);
- var addrStr = code.Remove(0, 2);
+ string addrStr = code.Remove(0, 2);
addrStr += code.Remove(2, 2);
result.Value = int.Parse(valueStr, NumberStyles.HexNumber);
diff --git a/src/BizHawk.Client.Common/cheats/GbGgGameGenieDecoder.cs b/src/BizHawk.Client.Common/cheats/GbGgGameGenieDecoder.cs
index 849fea2ce37..78501306fe9 100644
--- a/src/BizHawk.Client.Common/cheats/GbGgGameGenieDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/GbGgGameGenieDecoder.cs
@@ -8,7 +8,7 @@ namespace BizHawk.Client.Common.cheats
///
public static class GbGgGameGenieDecoder
{
- private static readonly Dictionary _gbGgGameGenieTable = new Dictionary
+ private static readonly Dictionary _gbGgGameGenieTable = new()
{
['0'] = 0,
['1'] = 1,
@@ -45,7 +45,7 @@ public static IDecodeResult Decode(string _code)
// Bit # |3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|
// maps to| Value |A|B|C|D|E|F|G|H|I|J|K|L|XOR 0xF|a|b|c|c|NotUsed|e|f|g|h|
// proper | Value |XOR 0xF|A|B|C|D|E|F|G|H|I|J|K|L|g|h|a|b|Nothing|c|d|e|f|
- var result = new DecodeResult { Size = WatchSize.Byte };
+ DecodeResult result = new() { Size = WatchSize.Byte };
int x;
@@ -95,7 +95,7 @@ public static IDecodeResult Decode(string _code)
if (_code.Length > 8)
{
_ = _gbGgGameGenieTable.TryGetValue(_code[6], out x);
- var comp = x << 2;
+ int comp = x << 2;
// 8th character ignored
_ = _gbGgGameGenieTable.TryGetValue(_code[8], out x);
diff --git a/src/BizHawk.Client.Common/cheats/GbaGameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/GbaGameSharkDecoder.cs
index 6b94b732f9b..c4b0d2205aa 100644
--- a/src/BizHawk.Client.Common/cheats/GbaGameSharkDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/GbaGameSharkDecoder.cs
@@ -12,8 +12,8 @@ public static class GbaGameSharkDecoder
private static string Decrypt(string code)
{
- var op1 = uint.Parse(code.Remove(8, 9), NumberStyles.HexNumber);
- var op2 = uint.Parse(code.Remove(0, 9), NumberStyles.HexNumber);
+ uint op1 = uint.Parse(code.Remove(8, 9), NumberStyles.HexNumber);
+ uint op2 = uint.Parse(code.Remove(0, 9), NumberStyles.HexNumber);
uint sum = 0xC6EF3720;
@@ -28,12 +28,13 @@ private static string Decrypt(string code)
return $"{op1:X8} {op2:X8}";
}
+ #pragma warning disable IDE0051
// TODO: When to use this?
private static string DecryptPro(string code)
{
- var sum = 0xC6EF3720;
- var op1 = uint.Parse(code.Remove(8, 9), NumberStyles.HexNumber);
- var op2 = uint.Parse(code.Remove(0, 9), NumberStyles.HexNumber);
+ uint sum = 0xC6EF3720;
+ uint op1 = uint.Parse(code.Remove(8, 9), NumberStyles.HexNumber);
+ uint op2 = uint.Parse(code.Remove(0, 9), NumberStyles.HexNumber);
for (int j = 0; j < 32; ++j)
{
@@ -44,6 +45,7 @@ private static string DecryptPro(string code)
return $"{op1:X8} {op2:X8}";
}
+ #pragma warning restore IDE0051
public static IDecodeResult Decode(string code)
{
@@ -62,7 +64,7 @@ public static IDecodeResult Decode(string code)
return new InvalidCheatCode("All GBA GameShark Codes need to be 17 characters in length with a space after the first eight.");
}
- var result = new DecodeResult
+ DecodeResult result = new()
{
Size = code.First() switch
{
@@ -89,9 +91,6 @@ public static IDecodeResult Decode(string code)
return result;
}
- private static string GetLast(string str, int length)
- {
- return length >= str.Length ? str : str.Substring(str.Length - length);
- }
+ private static string GetLast(string str, int length) => length >= str.Length ? str : str.Substring(str.Length - length);
}
}
diff --git a/src/BizHawk.Client.Common/cheats/GenesisActionReplayDecoder.cs b/src/BizHawk.Client.Common/cheats/GenesisActionReplayDecoder.cs
index ee61b0a9351..2f1e34a8c3b 100644
--- a/src/BizHawk.Client.Common/cheats/GenesisActionReplayDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/GenesisActionReplayDecoder.cs
@@ -18,7 +18,7 @@ public static IDecodeResult Decode(string code)
return new InvalidCheatCode("Action Replay/Pro Action Replay Codes need to contain a colon after the sixth character.");
}
- var parseString = code.Remove(0, 2);
+ string parseString = code.Remove(0, 2);
return code.Length switch
{
9 =>
diff --git a/src/BizHawk.Client.Common/cheats/GenesisGameGenieDecoder.cs b/src/BizHawk.Client.Common/cheats/GenesisGameGenieDecoder.cs
index 290db9c097c..2e32177ee62 100644
--- a/src/BizHawk.Client.Common/cheats/GenesisGameGenieDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/GenesisGameGenieDecoder.cs
@@ -5,7 +5,7 @@ namespace BizHawk.Client.Common.cheats
{
public static class GenesisGameGenieDecoder
{
- private static readonly Dictionary GameGenieTable = new Dictionary
+ private static readonly Dictionary GameGenieTable = new()
{
['A'] = 0,
['B'] = 1,
@@ -62,10 +62,10 @@ public static IDecodeResult Decode(string code)
long hexCode = 0;
// convert code to a long binary string
- foreach (var t in code)
+ foreach (char t in code)
{
hexCode <<= 5;
- _ = GameGenieTable.TryGetValue(t, out var y);
+ _ = GameGenieTable.TryGetValue(t, out long y);
hexCode |= y;
}
diff --git a/src/BizHawk.Client.Common/cheats/IDecodeResult.cs b/src/BizHawk.Client.Common/cheats/IDecodeResult.cs
index bbc51f2f28c..c76cfaffed4 100644
--- a/src/BizHawk.Client.Common/cheats/IDecodeResult.cs
+++ b/src/BizHawk.Client.Common/cheats/IDecodeResult.cs
@@ -39,7 +39,7 @@ public static bool IsValid(this IDecodeResult result, out DecodeResult valid)
public static Cheat ToCheat(this DecodeResult result, MemoryDomain domain, string description)
{
- var watch = Watch.GenerateWatch(
+ Watch watch = Watch.GenerateWatch(
domain,
result.Address,
result.Size,
diff --git a/src/BizHawk.Client.Common/cheats/N64GameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/N64GameSharkDecoder.cs
index 2d42fcc523a..5707629e83b 100644
--- a/src/BizHawk.Client.Common/cheats/N64GameSharkDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/N64GameSharkDecoder.cs
@@ -46,7 +46,7 @@ public static IDecodeResult Decode(string code)
return new InvalidCheatCode("This code is not needed by Bizhawk.");
}
- var s = code.Remove(0, 2);
+ string s = code.Remove(0, 2);
return new DecodeResult
{
diff --git a/src/BizHawk.Client.Common/cheats/NesGameGenieDecoder.cs b/src/BizHawk.Client.Common/cheats/NesGameGenieDecoder.cs
index 1f5a25bb4b7..64d6ca84bc7 100644
--- a/src/BizHawk.Client.Common/cheats/NesGameGenieDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/NesGameGenieDecoder.cs
@@ -5,7 +5,7 @@ namespace BizHawk.Client.Common.cheats
{
public static class NesGameGenieDecoder
{
- private static readonly Dictionary GameGenieTable = new Dictionary
+ private static readonly Dictionary GameGenieTable = new()
{
['A'] = 0, // 0000
['P'] = 1, // 0001
@@ -32,12 +32,12 @@ public static IDecodeResult Decode(string code)
throw new ArgumentNullException(nameof(code));
}
- if (code.Length != 6 && code.Length != 8)
+ if (code.Length is not 6 and not 8)
{
return new InvalidCheatCode("Game Genie codes need to be six or eight characters in length.");
}
- var result = new DecodeResult { Size = WatchSize.Byte };
+ DecodeResult result = new() { Size = WatchSize.Byte };
// char 3 bit 3 denotes the code length.
if (code.Length == 6)
{
@@ -47,7 +47,7 @@ public static IDecodeResult Decode(string code)
result.Value = 0;
result.Address = 0x8000;
- _ = GameGenieTable.TryGetValue(code[0], out var x);
+ _ = GameGenieTable.TryGetValue(code[0], out int x);
result.Value |= x & 0x07;
result.Value |= (x & 0x08) << 4;
@@ -79,7 +79,7 @@ public static IDecodeResult Decode(string code)
result.Address = 0x8000;
result.Compare = 0;
- _ = GameGenieTable.TryGetValue(code[0], out var x);
+ _ = GameGenieTable.TryGetValue(code[0], out int x);
result.Value |= x & 0x07;
result.Value |= (x & 0x08) << 4;
diff --git a/src/BizHawk.Client.Common/cheats/PsxGameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/PsxGameSharkDecoder.cs
index 3298a37227a..206ffe79dd6 100644
--- a/src/BizHawk.Client.Common/cheats/PsxGameSharkDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/PsxGameSharkDecoder.cs
@@ -24,9 +24,9 @@ public static IDecodeResult Decode(string code)
return new InvalidCheatCode("All PSX GameShark Cheats need to be 13 characters in length.");
}
- var result = new DecodeResult();
+ DecodeResult result = new();
- var type = code.Substring(0, 2);
+ string type = code.Substring(0, 2);
result.Size = type switch
{
"10" => WatchSize.Word,
@@ -49,7 +49,7 @@ public static IDecodeResult Decode(string code)
_ => WatchSize.Byte
};
- var s = code.Remove(0, 2);
+ string s = code.Remove(0, 2);
result.Address = int.Parse(s.Remove(6, 5), NumberStyles.HexNumber);
result.Value = int.Parse(s.Remove(0, 7), NumberStyles.HexNumber);
diff --git a/src/BizHawk.Client.Common/cheats/SaturnGameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/SaturnGameSharkDecoder.cs
index 06fd4355471..3d8dbeb353d 100644
--- a/src/BizHawk.Client.Common/cheats/SaturnGameSharkDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/SaturnGameSharkDecoder.cs
@@ -28,16 +28,16 @@ public static IDecodeResult Decode(string code)
return new InvalidCheatCode("All Saturn GameShark Cheats need to be 13 characters in length.");
}
- var result = new DecodeResult { Size = WatchSize.Word };
+ DecodeResult result = new() { Size = WatchSize.Word };
// Only the first character really matters? 16 or 36?
- var test = code.Remove(2, 11).Remove(1, 1);
+ string test = code.Remove(2, 11).Remove(1, 1);
if (test == "3")
{
result.Size = WatchSize.Byte;
}
-
- var s = code.Remove(0, 2);
+
+ string s = code.Remove(0, 2);
result.Address = int.Parse(s.Remove(6, 5), NumberStyles.HexNumber);
result.Value = int.Parse(s.Remove(0, 7));
return result;
diff --git a/src/BizHawk.Client.Common/cheats/SmsActionReplayDecoder.cs b/src/BizHawk.Client.Common/cheats/SmsActionReplayDecoder.cs
index c3ef9867a52..12c5b6fa075 100644
--- a/src/BizHawk.Client.Common/cheats/SmsActionReplayDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/SmsActionReplayDecoder.cs
@@ -17,11 +17,11 @@ public static IDecodeResult Decode(string code)
return new InvalidCheatCode("Action Replay Codes must be 9 characters with a dash after the third character");
}
- var result = new DecodeResult { Size = WatchSize.Byte };
+ DecodeResult result = new() { Size = WatchSize.Byte };
- var s = code.Remove(0, 2);
- var ramAddress = s.Remove(4, 2).Replace("-", "");
- var ramValue = s.Remove(0, 5);
+ string s = code.Remove(0, 2);
+ string ramAddress = s.Remove(4, 2).Replace("-", "");
+ string ramValue = s.Remove(0, 5);
result.Address = int.Parse(ramAddress, NumberStyles.HexNumber);
result.Value = int.Parse(ramValue, NumberStyles.HexNumber);
return result;
diff --git a/src/BizHawk.Client.Common/cheats/SnesGameGenieDecoder.cs b/src/BizHawk.Client.Common/cheats/SnesGameGenieDecoder.cs
index 24e12e8e80f..a11dd208444 100644
--- a/src/BizHawk.Client.Common/cheats/SnesGameGenieDecoder.cs
+++ b/src/BizHawk.Client.Common/cheats/SnesGameGenieDecoder.cs
@@ -9,7 +9,7 @@ public static class SnesGameGenieDecoder
// Code: D F 4 7 0 9 1 5 6 B C 8 A 2 3 E
// Hex: 0 1 2 3 4 5 6 7 8 9 A B C D E F
// This only applies to the SNES
- private static readonly Dictionary SNESGameGenieTable = new Dictionary
+ private static readonly Dictionary SNESGameGenieTable = new()
{
['D'] = 0, // 0000
['F'] = 1, // 0001
@@ -48,7 +48,7 @@ public static IDecodeResult Decode(string code)
// Bit # |3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|
// maps to| Value |i|j|k|l|q|r|s|t|o|p|a|b|c|d|u|v|w|x|e|f|g|h|m|n|
// order | Value |a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|
- var result = new DecodeResult { Size = WatchSize.Byte };
+ DecodeResult result = new() { Size = WatchSize.Byte };
int x;
diff --git a/src/BizHawk.Client.Common/config/Binding.cs b/src/BizHawk.Client.Common/config/Binding.cs
index 323e475008d..946e78cb729 100644
--- a/src/BizHawk.Client.Common/config/Binding.cs
+++ b/src/BizHawk.Client.Common/config/Binding.cs
@@ -14,8 +14,8 @@ public class HotkeyInfo
static HotkeyInfo()
{
- var dict = new Dictionary();
- var i = 0;
+ Dictionary dict = new();
+ int i = 0;
#if true
void Bind(string tabGroup, string displayName, string defaultBinding = "", string toolTip = "")
=> dict.Add(displayName, new(tabGroup: tabGroup, i++, displayName: displayName, toolTip: toolTip, defaultBinding: defaultBinding));
diff --git a/src/BizHawk.Client.Common/config/ConfigExtensions.cs b/src/BizHawk.Client.Common/config/ConfigExtensions.cs
index db982d0d3aa..7f9da1a4e7f 100644
--- a/src/BizHawk.Client.Common/config/ConfigExtensions.cs
+++ b/src/BizHawk.Client.Common/config/ConfigExtensions.cs
@@ -17,7 +17,7 @@ private class TypeNameEncapsulator
}
private static JToken Serialize(object o)
{
- var tne = new TypeNameEncapsulator { o = o };
+ TypeNameEncapsulator tne = new() { o = o };
return JToken.FromObject(tne, ConfigService.Serializer)["o"];
// Maybe todo: This code is identical to the code above, except that it does not emit the legacy "$type"
@@ -54,10 +54,7 @@ public static object GetCoreSettings(this Config config, Type coreType, Type set
///
/// null if no settings were saved, or there was an error deserializing
public static TSetting GetCoreSettings(this Config config)
- where TCore : IEmulator
- {
- return (TSetting)config.GetCoreSettings(typeof(TCore), typeof(TSetting));
- }
+ where TCore : IEmulator => (TSetting)config.GetCoreSettings(typeof(TCore), typeof(TSetting));
///
/// saves the core settings for a core
@@ -94,10 +91,7 @@ public static object GetCoreSyncSettings(this Config config, Type coreType, Type
///
/// null if no settings were saved, or there was an error deserializing
public static TSync GetCoreSyncSettings(this Config config)
- where TCore : IEmulator
- {
- return (TSync)config.GetCoreSyncSettings(typeof(TCore), typeof(TSync));
- }
+ where TCore : IEmulator => (TSync)config.GetCoreSyncSettings(typeof(TCore), typeof(TSync));
///
/// saves the core syncsettings for a core
@@ -120,11 +114,11 @@ public static void PutCoreSyncSettings(this Config config, object o, Type coreTy
public static void ReplaceKeysInBindings(this Config config, IReadOnlyDictionary replMap)
{
string ReplMulti(string multiBind)
- => multiBind.TransformFields(',', bind => bind.TransformFields('+', button => replMap.TryGetValue(button, out var repl) ? repl : button));
- foreach (var k in config.HotkeyBindings.Keys.ToList()) config.HotkeyBindings[k] = ReplMulti(config.HotkeyBindings[k]);
+ => multiBind.TransformFields(',', bind => bind.TransformFields('+', button => replMap.TryGetValue(button, out string repl) ? repl : button));
+ foreach (string k in config.HotkeyBindings.Keys.ToList()) config.HotkeyBindings[k] = ReplMulti(config.HotkeyBindings[k]);
foreach (var bindCollection in new[] { config.AllTrollers, config.AllTrollersAutoFire }) // analog and feedback binds can only be bound to (host) gamepads, not keyboard
{
- foreach (var k in bindCollection.Keys.ToArray()) bindCollection[k] = bindCollection[k].ToDictionary(static kvp => kvp.Key, kvp => ReplMulti(kvp.Value));
+ foreach (string k in bindCollection.Keys.ToArray()) bindCollection[k] = bindCollection[k].ToDictionary(static kvp => kvp.Key, kvp => ReplMulti(kvp.Value));
}
}
@@ -132,7 +126,7 @@ string ReplMulti(string multiBind)
/// will be if returned value is
public static bool TryGetChosenSystemForFileExt(this Config config, string fileExt, out string systemID)
{
- var b = config.PreferredPlatformsForExtensions.TryGetValue(fileExt, out var v);
+ bool b = config.PreferredPlatformsForExtensions.TryGetValue(fileExt, out string v);
if (b && !string.IsNullOrEmpty(v))
{
systemID = v;
diff --git a/src/BizHawk.Client.Common/config/ConfigService.cs b/src/BizHawk.Client.Common/config/ConfigService.cs
index 310790ac32c..0394f9d6175 100644
--- a/src/BizHawk.Client.Common/config/ConfigService.cs
+++ b/src/BizHawk.Client.Common/config/ConfigService.cs
@@ -67,14 +67,14 @@ public static bool IsFromSameVersion(string filepath, out string msg)
}
else
{
- var cfgVersion = VersionInfo.VersionStrToInt(cfgVersionStr);
+ uint cfgVersion = VersionInfo.VersionStrToInt(cfgVersionStr);
if (cfgVersion < 0x02050000U)
{
fmt = MSGFMT_PRE_2_5;
}
else
{
- var thisVersion = VersionInfo.VersionStrToInt(VersionInfo.MainVersion);
+ uint thisVersion = VersionInfo.VersionStrToInt(VersionInfo.MainVersion);
fmt = cfgVersion < thisVersion ? MSGFMT_OLDER : MSGFMT_NEWER;
}
}
@@ -85,15 +85,15 @@ public static bool IsFromSameVersion(string filepath, out string msg)
/// internal error
public static T Load(string filepath) where T : new()
{
- T config = default(T);
+ T config = default;
try
{
- var file = new FileInfo(filepath);
+ FileInfo file = new(filepath);
if (file.Exists)
{
using var reader = file.OpenText();
- var r = new JsonTextReader(reader);
+ JsonTextReader r = new(reader);
config = (T)Serializer.Deserialize(r, typeof(T));
}
}
@@ -107,11 +107,11 @@ public static bool IsFromSameVersion(string filepath, out string msg)
public static void Save(string filepath, object config)
{
- var file = new FileInfo(filepath);
+ FileInfo file = new(filepath);
try
{
using var writer = file.CreateText();
- var w = new JsonTextWriter(writer) { Formatting = Formatting.Indented };
+ JsonTextWriter w = new(writer) { Formatting = Formatting.Indented };
Serializer.Serialize(w, config);
}
catch
@@ -128,9 +128,9 @@ private class TypeNameEncapsulator
public static object LoadWithType(string serialized)
{
- using var tr = new StringReader(serialized);
- using var jr = new JsonTextReader(tr);
- var tne = (TypeNameEncapsulator)Serializer.Deserialize(jr, typeof(TypeNameEncapsulator));
+ using StringReader tr = new(serialized);
+ using JsonTextReader jr = new(tr);
+ TypeNameEncapsulator tne = (TypeNameEncapsulator)Serializer.Deserialize(jr, typeof(TypeNameEncapsulator));
// in the case of trying to deserialize nothing, tne will be nothing
// we want to return nothing
@@ -139,9 +139,9 @@ public static object LoadWithType(string serialized)
public static string SaveWithType(object o)
{
- using var sw = new StringWriter();
- using var jw = new JsonTextWriter(sw) { Formatting = Formatting.None };
- var tne = new TypeNameEncapsulator { o = o };
+ using StringWriter sw = new();
+ using JsonTextWriter jw = new(sw) { Formatting = Formatting.None };
+ TypeNameEncapsulator tne = new() { o = o };
Serializer.Serialize(jw, tne, typeof(TypeNameEncapsulator));
sw.Flush();
return sw.ToString();
diff --git a/src/BizHawk.Client.Common/config/FeedbackBind.cs b/src/BizHawk.Client.Common/config/FeedbackBind.cs
index 207e94d763a..bf322d299cc 100644
--- a/src/BizHawk.Client.Common/config/FeedbackBind.cs
+++ b/src/BizHawk.Client.Common/config/FeedbackBind.cs
@@ -13,7 +13,7 @@ public struct FeedbackBind
public string? GamepadPrefix;
[JsonIgnore]
- public bool IsZeroed => GamepadPrefix == null;
+ public readonly bool IsZeroed => GamepadPrefix == null;
public float Prescale;
diff --git a/src/BizHawk.Client.Common/config/MessagePosition.cs b/src/BizHawk.Client.Common/config/MessagePosition.cs
index 039b3f24c78..01f0676fdd5 100644
--- a/src/BizHawk.Client.Common/config/MessagePosition.cs
+++ b/src/BizHawk.Client.Common/config/MessagePosition.cs
@@ -21,14 +21,14 @@ public static class MessagePositionExtensions
{
public static bool IsTop(this MessagePosition.AnchorType type)
{
- return type == MessagePosition.AnchorType.TopLeft
- || type == MessagePosition.AnchorType.TopRight;
+ return type is MessagePosition.AnchorType.TopLeft
+ or MessagePosition.AnchorType.TopRight;
}
public static bool IsLeft(this MessagePosition.AnchorType type)
{
- return type == MessagePosition.AnchorType.TopLeft
- || type == MessagePosition.AnchorType.BottomLeft;
+ return type is MessagePosition.AnchorType.TopLeft
+ or MessagePosition.AnchorType.BottomLeft;
}
public static string ToCoordinateStr(this MessagePosition position) => $"{position.X}, {position.Y}";
@@ -36,14 +36,14 @@ public static bool IsLeft(this MessagePosition.AnchorType type)
public static class DefaultMessagePositions
{
- public static readonly MessagePosition Fps = new MessagePosition { X = 0, Y = 0 };
- public static readonly MessagePosition FrameCounter = new MessagePosition { X = 0, Y = 14 };
- public static readonly MessagePosition LagCounter = new MessagePosition { X = 0, Y = 42 };
- public static readonly MessagePosition InputDisplay = new MessagePosition { X = 0, Y = 28 };
- public static readonly MessagePosition ReRecordCounter = new MessagePosition { X = 0, Y = 56 };
- public static readonly MessagePosition Messages = new MessagePosition { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.BottomLeft };
- public static readonly MessagePosition Autohold = new MessagePosition { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.TopRight };
- public static readonly MessagePosition RamWatches = new MessagePosition { X = 0, Y = 70 };
+ public static readonly MessagePosition Fps = new() { X = 0, Y = 0 };
+ public static readonly MessagePosition FrameCounter = new() { X = 0, Y = 14 };
+ public static readonly MessagePosition LagCounter = new() { X = 0, Y = 42 };
+ public static readonly MessagePosition InputDisplay = new() { X = 0, Y = 28 };
+ public static readonly MessagePosition ReRecordCounter = new() { X = 0, Y = 56 };
+ public static readonly MessagePosition Messages = new() { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.BottomLeft };
+ public static readonly MessagePosition Autohold = new() { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.TopRight };
+ public static readonly MessagePosition RamWatches = new() { X = 0, Y = 70 };
public const int
MessagesColor = -1,
diff --git a/src/BizHawk.Client.Common/config/PathEntryCollection.cs b/src/BizHawk.Client.Common/config/PathEntryCollection.cs
index c2dec1d2c77..4154989b5a8 100644
--- a/src/BizHawk.Client.Common/config/PathEntryCollection.cs
+++ b/src/BizHawk.Client.Common/config/PathEntryCollection.cs
@@ -148,10 +148,10 @@ public void ResolveWithDefaults()
if (!Paths.Exists(p => p.System == defaultPath.System && p.Type == defaultPath.Type)) Paths.Add(defaultPath);
}
- var entriesToRemove = new List();
+ List entriesToRemove = new();
// Remove entries that no longer exist in defaults
- foreach (PathEntry pathEntry in Paths)
+ foreach (var pathEntry in Paths)
{
var path = Defaults.Value.FirstOrDefault(p => p.System == pathEntry.System && p.Type == pathEntry.Type);
if (path == null)
@@ -160,7 +160,7 @@ public void ResolveWithDefaults()
}
}
- foreach (PathEntry entry in entriesToRemove)
+ foreach (var entry in entriesToRemove)
{
Paths.Remove(entry);
}
diff --git a/src/BizHawk.Client.Common/config/PathEntryCollectionExtensions.cs b/src/BizHawk.Client.Common/config/PathEntryCollectionExtensions.cs
index 9ae93cdf6a9..8798590d898 100644
--- a/src/BizHawk.Client.Common/config/PathEntryCollectionExtensions.cs
+++ b/src/BizHawk.Client.Common/config/PathEntryCollectionExtensions.cs
@@ -22,7 +22,7 @@ public static string BaseFor(this PathEntryCollection collection, string systemI
public static string GlobalBaseAbsolutePath(this PathEntryCollection collection)
{
- var globalBase = collection[PathEntryCollection.GLOBAL, "Base"].Path;
+ string globalBase = collection[PathEntryCollection.GLOBAL, "Base"].Path;
// if %exe% prefixed then substitute exe path and repeat
if (globalBase.StartsWith("%exe%", StringComparison.InvariantCultureIgnoreCase))
@@ -56,7 +56,7 @@ public static PathEntry EntryWithFallback(this PathEntryCollection collection, s
public static string AbsolutePathForType(this PathEntryCollection collection, string systemId, string type)
{
- var path = collection.EntryWithFallback(type, systemId).Path;
+ string path = collection.EntryWithFallback(type, systemId).Path;
return collection.AbsolutePathFor(path, systemId);
}
@@ -67,12 +67,10 @@ public static string AbsolutePathForType(this PathEntryCollection collection, st
/// Logic will fallback until an absolute path is found,
/// using Global Base as a last resort
///
- public static string AbsolutePathFor(this PathEntryCollection collection, string path, string systemId)
- {
+ public static string AbsolutePathFor(this PathEntryCollection collection, string path, string systemId) =>
// warning: supposedly Path.GetFullPath accesses directories (and needs permissions)
// if this poses a problem, we need to paste code from .net or mono sources and fix them to not pose problems, rather than homebrew stuff
- return Path.GetFullPath(collection.AbsolutePathForInner(path, systemId));
- }
+ Path.GetFullPath(collection.AbsolutePathForInner(path, systemId));
private static string AbsolutePathForInner(this PathEntryCollection collection, string path, string systemId)
{
@@ -136,54 +134,51 @@ private static string AbsolutePathForInner(this PathEntryCollection collection,
public static string MovieAbsolutePath(this PathEntryCollection collection)
{
- var path = collection[PathEntryCollection.GLOBAL, "Movies"].Path;
+ string path = collection[PathEntryCollection.GLOBAL, "Movies"].Path;
return collection.AbsolutePathFor(path, null);
}
public static string MovieBackupsAbsolutePath(this PathEntryCollection collection)
{
- var path = collection[PathEntryCollection.GLOBAL, "Movie backups"].Path;
+ string path = collection[PathEntryCollection.GLOBAL, "Movie backups"].Path;
return collection.AbsolutePathFor(path, null);
}
public static string AvAbsolutePath(this PathEntryCollection collection)
{
- var path = collection[PathEntryCollection.GLOBAL, "A/V Dumps"].Path;
+ string path = collection[PathEntryCollection.GLOBAL, "A/V Dumps"].Path;
return collection.AbsolutePathFor(path, null);
}
public static string LuaAbsolutePath(this PathEntryCollection collection)
{
- var path = collection[PathEntryCollection.GLOBAL, "Lua"].Path;
+ string path = collection[PathEntryCollection.GLOBAL, "Lua"].Path;
return collection.AbsolutePathFor(path, null);
}
- public static string FirmwareAbsolutePath(this PathEntryCollection collection)
- {
- return collection.AbsolutePathFor(collection.FirmwaresPathFragment, null);
- }
+ public static string FirmwareAbsolutePath(this PathEntryCollection collection) => collection.AbsolutePathFor(collection.FirmwaresPathFragment, null);
public static string LogAbsolutePath(this PathEntryCollection collection)
{
- var path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Debug Logs"].Path);
+ string path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Debug Logs"].Path);
return collection.AbsolutePathFor(path, null);
}
public static string WatchAbsolutePath(this PathEntryCollection collection)
{
- var path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Watch (.wch)"].Path);
+ string path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Watch (.wch)"].Path);
return collection.AbsolutePathFor(path, null);
}
public static string ToolsAbsolutePath(this PathEntryCollection collection)
{
- var path = collection[PathEntryCollection.GLOBAL, "Tools"].Path;
+ string path = collection[PathEntryCollection.GLOBAL, "Tools"].Path;
return collection.AbsolutePathFor(path, null);
}
public static string MultiDiskAbsolutePath(this PathEntryCollection collection)
{
- var path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Multi-Disk Bundles"].Path);
+ string path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Multi-Disk Bundles"].Path);
return collection.AbsolutePathFor(path, null);
}
@@ -213,7 +208,7 @@ public static string RomAbsolutePath(this PathEntryCollection collection, string
public static string SaveRamAbsolutePath(this PathEntryCollection collection, IGameInfo game, IMovie movie)
{
- var name = game.FilesystemSafeName();
+ string name = game.FilesystemSafeName();
if (movie.IsActive())
{
name += $".{Path.GetFileNameWithoutExtension(movie.Filename)}";
@@ -228,7 +223,7 @@ public static string SaveRamAbsolutePath(this PathEntryCollection collection, IG
// Shenanigans
public static string RetroSaveRamAbsolutePath(this PathEntryCollection collection, IGameInfo game)
{
- var name = game.FilesystemSafeName();
+ string name = game.FilesystemSafeName();
name = Path.GetDirectoryName(name);
if (name == "")
{
@@ -246,7 +241,7 @@ public static string RetroSaveRamAbsolutePath(this PathEntryCollection collectio
// Shenanigans
public static string RetroSystemAbsolutePath(this PathEntryCollection collection, IGameInfo game)
{
- var name = game.FilesystemSafeName();
+ string name = game.FilesystemSafeName();
name = Path.GetDirectoryName(name);
if (string.IsNullOrEmpty(name))
{
@@ -261,7 +256,7 @@ public static string RetroSystemAbsolutePath(this PathEntryCollection collection
public static string AutoSaveRamAbsolutePath(this PathEntryCollection collection, IGameInfo game, IMovie movie)
{
- var path = collection.SaveRamAbsolutePath(game, movie);
+ string path = collection.SaveRamAbsolutePath(game, movie);
return path.Insert(path.Length - 8, ".AutoSaveRAM");
}
@@ -289,15 +284,9 @@ public static string ScreenshotAbsolutePathFor(this PathEntryCollection collecti
return collection.AbsolutePathFor(entry.Path, systemId);
}
- public static string PalettesAbsolutePathFor(this PathEntryCollection collection, string systemId)
- {
- return collection.AbsolutePathFor(collection[systemId, "Palettes"].Path, systemId);
- }
+ public static string PalettesAbsolutePathFor(this PathEntryCollection collection, string systemId) => collection.AbsolutePathFor(collection[systemId, "Palettes"].Path, systemId);
- public static string UserAbsolutePathFor(this PathEntryCollection collection, string systemId)
- {
- return collection.AbsolutePathFor(collection[systemId, "User"].Path, systemId);
- }
+ public static string UserAbsolutePathFor(this PathEntryCollection collection, string systemId) => collection.AbsolutePathFor(collection[systemId, "User"].Path, systemId);
///
/// Takes an absolute path and attempts to convert it to a relative, based on the system,
@@ -316,7 +305,7 @@ public static void RefreshTempPath(this PathEntryCollection collection)
{
if (string.IsNullOrWhiteSpace(collection.TempFilesFragment))
return;
- var path = collection.AbsolutePathFor(collection.TempFilesFragment, null);
+ string path = collection.AbsolutePathFor(collection.TempFilesFragment, null);
TempFileManager.HelperSetTempPath(path);
}
@@ -324,7 +313,7 @@ private static string ResolveToolsPath(this PathEntryCollection collection, stri
{
if (Path.IsPathRooted(subPath) || subPath.StartsWith('%')) return subPath;
- var toolsPath = collection[PathEntryCollection.GLOBAL, "Tools"].Path;
+ string toolsPath = collection[PathEntryCollection.GLOBAL, "Tools"].Path;
// Hack for backwards compatibility, prior to 1.11.5, .wch files were in .\Tools, we don't want that to turn into .Tools\Tools
if (subPath == "Tools")
diff --git a/src/BizHawk.Client.Common/config/ToolDialogSettings.cs b/src/BizHawk.Client.Common/config/ToolDialogSettings.cs
index 5c2304af1ba..a92f0f2b424 100644
--- a/src/BizHawk.Client.Common/config/ToolDialogSettings.cs
+++ b/src/BizHawk.Client.Common/config/ToolDialogSettings.cs
@@ -89,10 +89,10 @@ public Point TopLeft
public bool UseWindowSize => SaveWindowPosition && Width.HasValue && Height.HasValue;
[JsonIgnore]
- public Point WindowPosition => new Point(Wndx ?? 0, Wndy ?? 0);
+ public Point WindowPosition => new(Wndx ?? 0, Wndy ?? 0);
[JsonIgnore]
- public Size WindowSize => new Size(Width ?? 0, Height ?? 0);
+ public Size WindowSize => new(Width ?? 0, Height ?? 0);
public class ColumnList : List
{
diff --git a/src/BizHawk.Client.Common/controllers/AutofireController.cs b/src/BizHawk.Client.Common/controllers/AutofireController.cs
index 854562f323d..cea11a2fa06 100644
--- a/src/BizHawk.Client.Common/controllers/AutofireController.cs
+++ b/src/BizHawk.Client.Common/controllers/AutofireController.cs
@@ -21,9 +21,9 @@ public AutofireController(IEmulator emulator, int on, int off)
private readonly IEmulator _emulator;
- private readonly WorkingDictionary> _bindings = new WorkingDictionary>();
- private readonly WorkingDictionary _buttons = new WorkingDictionary();
- private readonly WorkingDictionary _buttonStarts = new WorkingDictionary();
+ private readonly WorkingDictionary> _bindings = new();
+ private readonly WorkingDictionary _buttons = new();
+ private readonly WorkingDictionary _buttonStarts = new();
public int On { get; set; }
public int Off { get; set; }
@@ -34,20 +34,14 @@ public AutofireController(IEmulator emulator, int on, int off)
public bool IsPressed(string button)
{
- var a = (internal_frame - _buttonStarts[button]) % (On + Off);
+ int a = (internal_frame - _buttonStarts[button]) % (On + Off);
return a < On && _buttons[button];
}
- public void ClearStarts()
- {
- _buttonStarts.Clear();
- }
+ public void ClearStarts() => _buttonStarts.Clear();
/// always
- public int AxisValue(string name)
- {
- throw new NotImplementedException();
- }
+ public int AxisValue(string name) => throw new NotImplementedException();
public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => Array.Empty<(string, int)>();
@@ -63,7 +57,7 @@ public void LatchFromPhysical(IController controller)
foreach (var (k, v) in _bindings)
{
- foreach (var boundBtn in v)
+ foreach (string boundBtn in v)
{
if (_buttons[k] == false && controller.IsPressed(boundBtn))
{
@@ -76,7 +70,7 @@ public void LatchFromPhysical(IController controller)
foreach (var (k, v) in _bindings)
{
_buttons[k] = false;
- foreach (var button in v)
+ foreach (string button in v)
{
if (controller.IsPressed(button))
{
@@ -90,8 +84,8 @@ public void BindMulti(string button, string controlString)
{
if (!string.IsNullOrEmpty(controlString))
{
- var controlBindings = controlString.Split(',');
- foreach (var control in controlBindings)
+ string[] controlBindings = controlString.Split(',');
+ foreach (string control in controlBindings)
{
_bindings[button].Add(control.Trim());
}
@@ -100,7 +94,7 @@ public void BindMulti(string button, string controlString)
public void IncrementStarts()
{
- foreach (var key in _buttonStarts.Keys.ToArray())
+ foreach (string key in _buttonStarts.Keys.ToArray())
{
_buttonStarts[key]++;
}
diff --git a/src/BizHawk.Client.Common/controllers/ClickyVirtualPadController.cs b/src/BizHawk.Client.Common/controllers/ClickyVirtualPadController.cs
index 2c39ea71228..d048277e697 100644
--- a/src/BizHawk.Client.Common/controllers/ClickyVirtualPadController.cs
+++ b/src/BizHawk.Client.Common/controllers/ClickyVirtualPadController.cs
@@ -11,7 +11,7 @@ namespace BizHawk.Client.Common
///
public class ClickyVirtualPadController : IController
{
- private readonly HashSet _pressed = new HashSet();
+ private readonly HashSet _pressed = new();
public ControllerDefinition Definition { get; set; }
diff --git a/src/BizHawk.Client.Common/controllers/SimpleController.cs b/src/BizHawk.Client.Common/controllers/SimpleController.cs
index 59542794253..071ab90f7e5 100644
--- a/src/BizHawk.Client.Common/controllers/SimpleController.cs
+++ b/src/BizHawk.Client.Common/controllers/SimpleController.cs
@@ -48,10 +48,7 @@ public bool this[string button]
public IReadOnlyDictionary BoolButtons() => Buttons;
- public void AcceptNewAxis(string axisId, int value)
- {
- Axes[axisId] = value;
- }
+ public void AcceptNewAxis(string axisId, int value) => Axes[axisId] = value;
public void AcceptNewAxes(IEnumerable<(string AxisID, int Value)> newValues)
{
diff --git a/src/BizHawk.Client.Common/display/IInputDisplayGenerator.cs b/src/BizHawk.Client.Common/display/IInputDisplayGenerator.cs
index 473cd3d2481..e74cfa80bc7 100644
--- a/src/BizHawk.Client.Common/display/IInputDisplayGenerator.cs
+++ b/src/BizHawk.Client.Common/display/IInputDisplayGenerator.cs
@@ -31,13 +31,13 @@ public Bk2InputDisplayGenerator(string systemId, IController source)
public string Generate()
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
foreach (var (button, range, mnemonicChar) in _cachedInputSpecs)
{
if (range is not null)
{
- var val = _source.AxisValue(button);
+ int val = _source.AxisValue(button);
if (val == range.Value.Neutral)
{
diff --git a/src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs b/src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs
index 1bcd584f870..d5b09f40683 100644
--- a/src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs
+++ b/src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs
@@ -19,19 +19,19 @@ public sealed class FirmwareManager
public static (byte[] Patched, string ActualHash) PerformPatchInMemory(byte[] @base, in FirmwarePatchOption patchOption)
{
- var patched = patchOption.Patches.Aggregate(seed: @base, (a, fpd) => fpd.ApplyToMutating(a));
+ byte[] patched = patchOption.Patches.Aggregate(seed: @base, (a, fpd) => fpd.ApplyToMutating(a));
return (patched, SHA1Checksum.ComputeDigestHex(patched));
}
public static (string FilePath, int FileSize, FirmwareFile FF) PerformPatchOnDisk(string baseFilename, in FirmwarePatchOption patchOption, PathEntryCollection pathEntries)
{
- var @base = File.ReadAllBytes(baseFilename);
+ byte[] @base = File.ReadAllBytes(baseFilename);
var (patched, actualHash) = PerformPatchInMemory(@base, in patchOption);
Trace.Assert(actualHash == patchOption.TargetHash);
- var patchedParentDir = Path.Combine(pathEntries[PathEntryCollection.GLOBAL, "Temp Files"].Path, "AutopatchedFirmware");
+ string patchedParentDir = Path.Combine(pathEntries[PathEntryCollection.GLOBAL, "Temp Files"].Path, "AutopatchedFirmware");
Directory.CreateDirectory(patchedParentDir);
var ff = FirmwareDatabase.FirmwareFilesByHash[patchOption.TargetHash];
- var patchedFilePath = Path.Combine(patchedParentDir, ff.RecommendedName);
+ string patchedFilePath = Path.Combine(patchedParentDir, ff.RecommendedName);
File.WriteAllBytes(patchedFilePath, patched);
return (patchedFilePath, @base.Length, ff); // patches can't change length with the current implementation
}
@@ -48,12 +48,12 @@ public static (string FilePath, int FileSize, FirmwareFile FF) PerformPatchOnDis
private ResolutionInfo? AttemptPatch(FirmwareRecord requested, PathEntryCollection pathEntries, IDictionary userSpecifications)
{
// look for patchsets where 1. they produce a file that fulfils the request, and 2. a matching input file is present in the firmware dir
- var targetOptionHashes = FirmwareDatabase.FirmwareOptions.Where(fo => fo.ID == requested.ID).Select(fo => fo.Hash).ToList();
- var presentBaseFiles = _resolutionDictionary.Values.Select(ri => ri.Hash).ToList(); //TODO might want to use files which are known (in the database), but not assigned to any record
+ List targetOptionHashes = FirmwareDatabase.FirmwareOptions.Where(fo => fo.ID == requested.ID).Select(fo => fo.Hash).ToList();
+ List presentBaseFiles = _resolutionDictionary.Values.Select(ri => ri.Hash).ToList(); //TODO might want to use files which are known (in the database), but not assigned to any record
var patchOption = FirmwareDatabase.AllPatches.FirstOrNull(fpo => targetOptionHashes.Contains(fpo.TargetHash) && presentBaseFiles.Contains(fpo.BaseHash));
if (patchOption is null) return null;
// found one, proceed with patching the base file
- var baseFilename = _resolutionDictionary.Values.First(ri => ri.Hash == patchOption.Value.BaseHash).FilePath!;
+ string baseFilename = _resolutionDictionary.Values.First(ri => ri.Hash == patchOption.Value.BaseHash).FilePath!;
var (patchedFilePath, patchedFileLength, ff) = PerformPatchOnDisk(baseFilename, patchOption.Value, pathEntries);
// cache and return this new file's metadata
userSpecifications[requested.ID.ConfigKey] = patchedFilePath;
@@ -111,7 +111,7 @@ public RealFirmwareFile Read(FileInfo fi)
// we can let it fall through here, as ReadAllBytes just reads all bytes starting from the stream position :)
}
- var hash = SHA1Checksum.ComputeDigestHex(fs.ReadAllBytes());
+ string hash = SHA1Checksum.ComputeDigestHex(fs.ReadAllBytes());
return _dict![hash] = new RealFirmwareFile(fi, hash);
}
}
@@ -123,16 +123,16 @@ public bool CanFileBeImported(string f)
{
try
{
- var fi = new FileInfo(f);
+ FileInfo fi = new(f);
if (!fi.Exists) return false;
// weed out filesizes first to reduce the unnecessary overhead of a hashing operation
if (!_firmwareSizes.Contains(fi.Length)) return false;
// check the hash
- var reader = new RealFirmwareReader();
+ RealFirmwareReader reader = new();
reader.Read(fi);
- var hash = reader.Dict.Values.First().Hash;
+ string hash = reader.Dict.Values.First().Hash;
return FirmwareDatabase.FirmwareFiles.Any(a => a.Hash == hash);
}
catch
@@ -143,10 +143,10 @@ public bool CanFileBeImported(string f)
public void DoScanAndResolve(PathEntryCollection pathEntries, IDictionary userSpecifications)
{
- var reader = new RealFirmwareReader();
+ RealFirmwareReader reader = new();
// build a list of files under the global firmwares path, and build a hash for each of them (as ResolutionInfo) while we're at it
- var todo = new Queue(new[] { new DirectoryInfo(pathEntries.AbsolutePathFor(pathEntries.FirmwaresPathFragment, null)) });
+ Queue todo = new(new[] { new DirectoryInfo(pathEntries.AbsolutePathFor(pathEntries.FirmwaresPathFragment, null)) });
while (todo.Count != 0)
{
var di = todo.Dequeue();
@@ -180,7 +180,7 @@ public void DoScanAndResolve(PathEntryCollection pathEntries, IDictionary
+ foreach (string? k in Buttons.Keys.Where(k =>
k.EndsWithOrdinal($"+{ie.LogicalButton.Button}") || k.StartsWithOrdinal($"{ie.LogicalButton.Button}+") || k.Contains($"+{ie.LogicalButton.Button}+"))
.ToArray())
Buttons[k] = false;
@@ -33,7 +33,7 @@ public sealed class ControllerInputCoalescer : InputCoalescer
protected override void ProcessSubsets(string button, bool state)
{
// For controller input, we want Shift+X to register as both Shift and X (for Keyboard controllers)
- foreach (var s in button.Split('+')) Buttons[s] = state;
+ foreach (string? s in button.Split('+')) Buttons[s] = state;
}
}
}
diff --git a/src/BizHawk.Client.Common/input/InputEvent.cs b/src/BizHawk.Client.Common/input/InputEvent.cs
index dd7a7d3572d..8f8c0acf60d 100644
--- a/src/BizHawk.Client.Common/input/InputEvent.cs
+++ b/src/BizHawk.Client.Common/input/InputEvent.cs
@@ -69,9 +69,9 @@ public override readonly string ToString()
if (Modifiers is 0U) return Button;
var allMods = _getEffectiveModListCallback();
StringBuilder ret = new();
- for (var i = 0; i < allMods.Count; i++)
+ for (int i = 0; i < allMods.Count; i++)
{
- var b = 1U << i;
+ uint b = 1U << i;
if ((Modifiers & b) is not 0U)
{
ret.Append(allMods[i]);
diff --git a/src/BizHawk.Client.Common/inputAdapters/AutoPattern.cs b/src/BizHawk.Client.Common/inputAdapters/AutoPattern.cs
index b1a832c0c37..76ce40908df 100644
--- a/src/BizHawk.Client.Common/inputAdapters/AutoPattern.cs
+++ b/src/BizHawk.Client.Common/inputAdapters/AutoPattern.cs
@@ -57,15 +57,9 @@ public bool GetNextValue(bool isLag = false)
///
/// Gets the next value without incrementing index.
///
- public bool PeekNextValue()
- {
- return Pattern[_index];
- }
+ public bool PeekNextValue() => Pattern[_index];
- public void Reset()
- {
- _index = 0;
- }
+ public void Reset() => _index = 0;
}
public class AutoPatternAxis
@@ -134,14 +128,8 @@ public int GetNextValue(bool isLag = false)
///
/// Gets the next value without incrementing index.
///
- public int PeekNextValue()
- {
- return Pattern[_index];
- }
+ public int PeekNextValue() => Pattern[_index];
- public void Reset()
- {
- _index = 0;
- }
+ public void Reset() => _index = 0;
}
}
diff --git a/src/BizHawk.Client.Common/inputAdapters/InputManager.cs b/src/BizHawk.Client.Common/inputAdapters/InputManager.cs
index edf2174518b..8e1642bfcf8 100644
--- a/src/BizHawk.Client.Common/inputAdapters/InputManager.cs
+++ b/src/BizHawk.Client.Common/inputAdapters/InputManager.cs
@@ -90,10 +90,7 @@ public void ToggleStickies()
AutofireStickyXorAdapter.MassToggleStickyState(AutoFireController.PressedButtons);
}
- public void ToggleAutoStickies()
- {
- AutofireStickyXorAdapter.MassToggleStickyState(ActiveController.PressedButtons);
- }
+ public void ToggleAutoStickies() => AutofireStickyXorAdapter.MassToggleStickyState(ActiveController.PressedButtons);
private static Controller BindToDefinition(
ControllerDefinition def,
@@ -101,12 +98,12 @@ private static Controller BindToDefinition(
IDictionary> analogBinds,
IDictionary> feedbackBinds)
{
- var ret = new Controller(def);
+ Controller ret = new(def);
if (allBinds.TryGetValue(def.Name, out var binds))
{
- foreach (var btn in def.BoolButtons)
+ foreach (string btn in def.BoolButtons)
{
- if (binds.TryGetValue(btn, out var bind))
+ if (binds.TryGetValue(btn, out string bind))
{
ret.BindMulti(btn, bind);
}
@@ -115,7 +112,7 @@ private static Controller BindToDefinition(
if (analogBinds.TryGetValue(def.Name, out var aBinds))
{
- foreach (var btn in def.Axes.Keys)
+ foreach (string btn in def.Axes.Keys)
{
if (aBinds.TryGetValue(btn, out var bind))
{
@@ -126,7 +123,7 @@ private static Controller BindToDefinition(
if (feedbackBinds.TryGetValue(def.Name, out var fBinds))
{
- foreach (var channel in def.HapticsChannels)
+ foreach (string channel in def.HapticsChannels)
{
if (fBinds.TryGetValue(channel, out var bind)) ret.BindFeedbackChannel(channel, bind);
}
@@ -141,12 +138,12 @@ private static AutofireController BindToDefinitionAF(
int on,
int off)
{
- var ret = new AutofireController(emulator, on, off);
+ AutofireController ret = new(emulator, on, off);
if (allBinds.TryGetValue(emulator.ControllerDefinition.Name, out var binds))
{
- foreach (var btn in emulator.ControllerDefinition.BoolButtons)
+ foreach (string btn in emulator.ControllerDefinition.BoolButtons)
{
- if (binds.TryGetValue(btn, out var bind))
+ if (binds.TryGetValue(btn, out string bind))
{
ret.BindMulti(btn, bind);
}
diff --git a/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs b/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs
index 9373b86d92c..78918ad9095 100644
--- a/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs
+++ b/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs
@@ -15,16 +15,16 @@ public class OverrideAdapter : IController
public IInputDisplayGenerator InputDisplayGenerator { get; set; } = null;
- private readonly Dictionary _overrides = new Dictionary();
- private readonly Dictionary _axisOverrides = new Dictionary();
- private readonly List _inverses = new List();
+ private readonly Dictionary _overrides = new();
+ private readonly Dictionary _axisOverrides = new();
+ private readonly List _inverses = new();
/// not overridden
public bool IsPressed(string button)
- => _overrides.TryGetValue(button, out var b) ? b : throw new InvalidOperationException();
+ => _overrides.TryGetValue(button, out bool b) ? b : throw new InvalidOperationException();
public int AxisValue(string name)
- => _axisOverrides.TryGetValue(name, out var i) ? i : 0;
+ => _axisOverrides.TryGetValue(name, out int i) ? i : 0;
public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => throw new NotImplementedException(); // no idea --yoshi
@@ -51,10 +51,7 @@ public void UnSet(string button)
_inverses.Remove(button);
}
- public void SetInverse(string button)
- {
- _inverses.Add(button);
- }
+ public void SetInverse(string button) => _inverses.Add(button);
public void FrameTick()
{
diff --git a/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs b/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs
index 69fbeb89e19..900ac9c68ad 100644
--- a/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs
+++ b/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs
@@ -19,14 +19,14 @@ public class StickyXorAdapter : IStickyAdapter
public bool IsPressed(string button)
{
- var source = Source.IsPressed(button);
+ bool source = Source.IsPressed(button);
source ^= CurrentStickies.Contains(button);
return source;
}
public int AxisValue(string name)
{
- var val = _axisSet[name];
+ int? val = _axisSet[name];
if (val.HasValue)
{
@@ -47,11 +47,11 @@ public int AxisValue(string name)
public IController Source { get; set; }
- private List _justPressed = new List();
+ private List _justPressed = new();
// if SetAxis() is called (typically virtual pads), then that axis will entirely override the Source input
// otherwise, the source is passed thru.
- private readonly WorkingDictionary _axisSet = new WorkingDictionary();
+ private readonly WorkingDictionary _axisSet = new();
public void SetAxis(string name, int? value)
{
@@ -97,7 +97,7 @@ public void ClearStickies()
public void MassToggleStickyState(List buttons)
{
- foreach (var button in buttons.Where(button => !_justPressed.Contains(button)))
+ foreach (string button in buttons.Where(button => !_justPressed.Contains(button)))
{
if (CurrentStickies.Contains(button))
{
@@ -121,7 +121,7 @@ public class AutoFireStickyXorAdapter : IStickyAdapter, IInputAdapter
public bool IsPressed(string button)
{
- var source = Source.IsPressed(button);
+ bool source = Source.IsPressed(button);
bool patternValue = false;
if (_boolPatterns.TryGetValue(button, out var pattern))
{
@@ -154,8 +154,8 @@ public void SetOnOffPatternFromConfig(int on, int off)
_off = off < 0 ? 0 : off;
}
- private readonly WorkingDictionary _boolPatterns = new WorkingDictionary();
- private readonly WorkingDictionary _axisPatterns = new WorkingDictionary();
+ private readonly WorkingDictionary _boolPatterns = new();
+ private readonly WorkingDictionary _axisPatterns = new();
public AutoFireStickyXorAdapter()
{
@@ -191,12 +191,9 @@ public void SetSticky(string button, bool isSticky, AutoPatternBool pattern = nu
}
}
- public bool IsSticky(string button)
- {
- return _boolPatterns.ContainsKey(button) || _axisPatterns.ContainsKey(button);
- }
+ public bool IsSticky(string button) => _boolPatterns.ContainsKey(button) || _axisPatterns.ContainsKey(button);
- public HashSet CurrentStickies => new HashSet(_boolPatterns.Keys);
+ public HashSet CurrentStickies => new(_boolPatterns.Keys);
public void ClearStickies()
{
@@ -217,11 +214,11 @@ public void IncrementLoops(bool lagged)
}
}
- private List _justPressed = new List();
+ private List _justPressed = new();
public void MassToggleStickyState(List buttons)
{
- foreach (var button in buttons.Where(button => !_justPressed.Contains(button)))
+ foreach (string button in buttons.Where(button => !_justPressed.Contains(button)))
{
SetSticky(button, !_boolPatterns.ContainsKey(button));
}
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/ClientLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/ClientLuaLibrary.cs
index 6619ea5907e..30dcfbc4264 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/ClientLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/ClientLuaLibrary.cs
@@ -53,17 +53,11 @@ public int BorderWidth()
[LuaMethodExample("local inclibuf = client.bufferheight( );")]
[LuaMethod("bufferheight", "Gets the visible height of the emu display surface (the core video output). This excludes the gameExtraPadding you've set.")]
- public int BufferHeight()
- {
- return VideoProvider?.BufferHeight ?? NullVideo.Instance.BufferHeight; // TODO: consider exposing the video provider from mainform, so it can decide NullVideo is the correct substitute
- }
+ public int BufferHeight() => VideoProvider?.BufferHeight ?? NullVideo.Instance.BufferHeight; // TODO: consider exposing the video provider from mainform, so it can decide NullVideo is the correct substitute
[LuaMethodExample("local inclibuf = client.bufferwidth( );")]
[LuaMethod("bufferwidth", "Gets the visible width of the emu display surface (the core video output). This excludes the gameExtraPadding you've set.")]
- public int BufferWidth()
- {
- return VideoProvider?.BufferWidth ?? NullVideo.Instance.BufferWidth;
- }
+ public int BufferWidth() => VideoProvider?.BufferWidth ?? NullVideo.Instance.BufferWidth;
[LuaMethodExample("client.clearautohold( );")]
[LuaMethod("clearautohold", "Clears all autohold keys")]
@@ -201,7 +195,7 @@ public void OpenRamSearch()
public bool OpenRom(string path)
{
_luaLibsImpl.IsRebootingCore = true;
- var success = APIs.EmuClient.OpenRom(path);
+ bool success = APIs.EmuClient.OpenRom(path);
_luaLibsImpl.IsRebootingCore = false;
return success;
}
@@ -322,10 +316,7 @@ public int Ypos()
[LuaMethodExample("local incbhver = client.getversion( );")]
[LuaMethod("getversion", "Returns the current stable BizHawk version")]
- public static string GetVersion()
- {
- return VersionInfo.MainVersion;
- }
+ public static string GetVersion() => VersionInfo.MainVersion;
[LuaMethodExample("local nlcliget = client.getavailabletools( );")]
[LuaMethod("getavailabletools", "Returns a list of the tools currently open")]
@@ -344,7 +335,7 @@ public LuaTable GetTool(string name)
[LuaMethod("createinstance", "returns a default instance of the given type of object if it exists (not case sensitive). Note: This will only work on objects which have a parameterless constructor. If no suitable type is found, or the type does not have a parameterless constructor, then nil is returned")]
public LuaTable CreateInstance(string name)
{
- var instance = APIs.Tool.CreateInstance(name);
+ object instance = APIs.Tool.CreateInstance(name);
return instance == null ? null : _th.ObjectToTable(instance);
}
@@ -360,10 +351,7 @@ public void SaveRam()
[LuaMethodExample("client.sleep( 50 );")]
[LuaMethod("sleep", "sleeps for n milliseconds")]
- public void Sleep(int millis)
- {
- Thread.Sleep(millis);
- }
+ public void Sleep(int millis) => Thread.Sleep(millis);
[LuaMethodExample("client.exactsleep( 50 );")]
[LuaMethod("exactsleep", "sleeps exactly for n milliseconds")]
@@ -397,8 +385,8 @@ public void AddCheat(string code)
Log($"cheat codes not supported by the current system: {MainForm.Emulator.SystemId}");
return;
}
-
- var decoder = new GameSharkDecoder(MainForm.Emulator.AsMemoryDomains(), MainForm.Emulator.SystemId);
+
+ GameSharkDecoder decoder = new(MainForm.Emulator.AsMemoryDomains(), MainForm.Emulator.SystemId);
var result = decoder.Decode(code);
if (result.IsValid(out var valid))
@@ -427,7 +415,7 @@ public void RemoveCheat(string code)
return;
}
- var decoder = new GameSharkDecoder(MainForm.Emulator.AsMemoryDomains(), MainForm.Emulator.SystemId);
+ GameSharkDecoder decoder = new(MainForm.Emulator.AsMemoryDomains(), MainForm.Emulator.SystemId);
var result = decoder.Decode(code);
if (result.IsValid(out var valid))
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/CommLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/CommLuaLibrary.cs
index bc44d08d1cb..62422c2faaf 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/CommLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/CommLuaLibrary.cs
@@ -22,7 +22,7 @@ public CommLuaLibrary(ILuaLibraries luaLibsImpl, ApiContainer apiContainer, Acti
[LuaMethod("getluafunctionslist", "returns a list of implemented functions")]
public static string GetLuaFunctionsList()
{
- var list = new StringBuilder();
+ StringBuilder list = new();
foreach (var function in typeof(CommLuaLibrary).GetMethods())
{
list.AppendLine(function.ToString());
@@ -73,10 +73,7 @@ public string SocketServerResponse()
}
[LuaMethod("socketServerSuccessful", "returns the status of the last Socket server action")]
- public bool SocketServerSuccessful()
- {
- return CheckSocketServer() && APIs.Comm.Sockets.Successful;
- }
+ public bool SocketServerSuccessful() => CheckSocketServer() && APIs.Comm.Sockets.Successful;
[LuaMethod("socketServerSetTimeout", "sets the timeout in milliseconds for receiving messages")]
public void SocketServerSetTimeout(int timeout)
@@ -100,16 +97,10 @@ public void SocketServerSetPort(int port)
}
[LuaMethod("socketServerGetIp", "returns the IP address of the Lua socket server")]
- public string SocketServerGetIp()
- {
- return APIs.Comm.Sockets?.IP;
- }
+ public string SocketServerGetIp() => APIs.Comm.Sockets?.IP;
[LuaMethod("socketServerGetPort", "returns the port of the Lua socket server")]
- public int? SocketServerGetPort()
- {
- return APIs.Comm.Sockets?.Port;
- }
+ public int? SocketServerGetPort() => APIs.Comm.Sockets?.Port;
[LuaMethod("socketServerGetInfo", "returns the IP and port of the Lua socket server")]
public string SocketServerGetInfo()
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/EmulationLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/EmulationLuaLibrary.cs
index 879e741a397..8532b867002 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/EmulationLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/EmulationLuaLibrary.cs
@@ -25,10 +25,7 @@ public void DisplayVsync(bool enabled)
[LuaMethodExample("emu.frameadvance( );")]
[LuaMethod("frameadvance", "Signals to the emulator to resume emulation. Necessary for any lua script while loop or else the emulator will freeze!")]
- public void FrameAdvance()
- {
- FrameAdvanceCallback();
- }
+ public void FrameAdvance() => FrameAdvanceCallback();
[LuaMethodExample("local inemufra = emu.framecount( );")]
[LuaMethod("framecount", "Returns the current frame count")]
@@ -110,10 +107,7 @@ public void SetRenderPlanes(params bool[] luaParam)
[LuaMethodExample("emu.yield( );")]
[LuaMethod("yield", "allows a script to run while emulation is paused and interact with the gui/main window in realtime ")]
- public void Yield()
- {
- YieldCallback();
- }
+ public void Yield() => YieldCallback();
[LuaMethodExample("local stemuget = emu.getdisplaytype();")]
[LuaMethod("getdisplaytype", "returns the display type (PAL vs NTSC) that the emulator is currently running in")]
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/GuiLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/GuiLuaLibrary.cs
index ac7f6a5ba0f..e709a758cf6 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/GuiLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/GuiLuaLibrary.cs
@@ -76,8 +76,8 @@ public void DrawBezier(
{
try
{
- var pointsArr = new Point[4];
- var i = 0;
+ Point[] pointsArr = new Point[4];
+ int i = 0;
foreach (var point in _th.EnumerateValues(points)
.Select(table => _th.EnumerateValues(table).ToList()))
{
@@ -217,12 +217,12 @@ public void DrawPolygon(
[LuaColorParam] object background = null,
string surfaceName = null)
{
- var pointsList = _th.EnumerateValues(points)
+ System.Collections.Generic.List> pointsList = _th.EnumerateValues(points)
.Select(table => _th.EnumerateValues(table).ToList()).ToList();
try
{
- var pointsArr = new Point[pointsList.Count];
- var i = 0;
+ Point[] pointsArr = new Point[pointsList.Count];
+ int i = 0;
foreach (var point in pointsList)
{
pointsArr[i] = new Point((int) point[0] + (offsetX ?? 0), (int) point[1] + (offsetY ?? 0));
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/JoypadLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/JoypadLuaLibrary.cs
index 27799327c3d..bc48d834e8a 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/JoypadLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/JoypadLuaLibrary.cs
@@ -37,7 +37,7 @@ public void SetFromMnemonicStr(string inputLogEntry)
[LuaMethod("set", "sets the given buttons to their provided values for the current frame")]
public void Set(LuaTable buttons, int? controller = null)
{
- var dict = new Dictionary();
+ Dictionary dict = new();
foreach (var (k, v) in _th.EnumerateEntries(buttons))
{
dict[k.ToString()] = Convert.ToBoolean(v); // Accepts 1/0 or true/false
@@ -49,10 +49,10 @@ public void Set(LuaTable buttons, int? controller = null)
[LuaMethod("setanalog", "sets the given analog controls to their provided values for the current frame. Note that unlike set() there is only the logic of overriding with the given value.")]
public void SetAnalog(LuaTable controls, int? controller = null)
{
- var dict = new Dictionary();
+ Dictionary dict = new();
foreach (var (k, v) in _th.EnumerateEntries(controls))
{
- dict[k.ToString()] = long.TryParse(v.ToString(), out var d) ? (int) d : null;
+ dict[k.ToString()] = long.TryParse(v.ToString(), out long d) ? (int) d : null;
}
APIs.Joypad.SetAnalog(dict, controller);
}
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/MemoryLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/MemoryLuaLibrary.cs
index 945b378b127..072aacf29a8 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/MemoryLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/MemoryLuaLibrary.cs
@@ -73,8 +73,7 @@ public LuaTable ReadBytesAsDict(long addr, int length, string domain = null)
[LuaDeprecatedMethod]
[LuaMethod("writebyterange", "Writes the given values to the given addresses as unsigned bytes")]
- public void WriteByteRange(LuaTable memoryblock, string domain = null)
- {
+ public void WriteByteRange(LuaTable memoryblock, string domain = null) =>
#if true
WriteBytesAsDict(memoryblock, domain);
#else
@@ -98,7 +97,7 @@ public void WriteByteRange(LuaTable memoryblock, string domain = null)
Log($"Error: the domain {d.Name} is not writable");
}
#endif
- }
+
[LuaMethodExample("memory.write_bytes_as_array(0x100, { 0xAB, 0x12, 0xCD, 0x34 });")]
[LuaMethod("write_bytes_as_array", "Writes sequential bytes starting at addr.")]
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/MovieLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/MovieLuaLibrary.cs
index c77d116ed99..5918a61acdc 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/MovieLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/MovieLuaLibrary.cs
@@ -72,7 +72,7 @@ public string Mode()
public bool PlayFromStart(string path = "")
{
_luaLibsImpl.IsRebootingCore = true;
- var success = APIs.Movie.PlayFromStart(path);
+ bool success = APIs.Movie.PlayFromStart(path);
_luaLibsImpl.IsRebootingCore = false;
return success;
}
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/SQLiteLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/SQLiteLuaLibrary.cs
index 9ac0170f491..642dc085db7 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/SQLiteLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/SQLiteLuaLibrary.cs
@@ -34,7 +34,7 @@ public string WriteCommand(string query = "")
"Ex: select * from rewards")]
public object ReadCommand(string query = "")
{
- var result = APIs.SQLite.ReadCommand(query);
+ object result = APIs.SQLite.ReadCommand(query);
return result switch
{
Dictionary dict => _th.DictToTable(dict),
diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/SaveStateLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/SaveStateLuaLibrary.cs
index 5d9c00e7c62..e04345302e1 100644
--- a/src/BizHawk.Client.Common/lua/CommonLibs/SaveStateLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/CommonLibs/SaveStateLuaLibrary.cs
@@ -14,7 +14,7 @@ public SaveStateLuaLibrary(ILuaLibraries luaLibsImpl, ApiContainer apiContainer,
public bool Load(string path, bool suppressOSD = false)
{
_luaLibsImpl.IsUpdateSupressed = true;
- var success = APIs.SaveState.Load(path, suppressOSD);
+ bool success = APIs.SaveState.Load(path, suppressOSD);
_luaLibsImpl.IsUpdateSupressed = false;
return success;
}
@@ -24,7 +24,7 @@ public bool Load(string path, bool suppressOSD = false)
public bool LoadSlot(int slotNum, bool suppressOSD = false)
{
_luaLibsImpl.IsUpdateSupressed = true;
- var success = APIs.SaveState.LoadSlot(slotNum, suppressOSD: suppressOSD);
+ bool success = APIs.SaveState.LoadSlot(slotNum, suppressOSD: suppressOSD);
_luaLibsImpl.IsUpdateSupressed = false;
return success;
}
diff --git a/src/BizHawk.Client.Common/lua/EnvironmentSandbox.cs b/src/BizHawk.Client.Common/lua/EnvironmentSandbox.cs
index 3f201935e92..792ea6ed916 100644
--- a/src/BizHawk.Client.Common/lua/EnvironmentSandbox.cs
+++ b/src/BizHawk.Client.Common/lua/EnvironmentSandbox.cs
@@ -5,10 +5,8 @@ namespace BizHawk.Client.Common
{
public static class EnvironmentSandbox
{
- public static void Sandbox(Action callback)
- {
+ public static void Sandbox(Action callback) =>
// just a stub for right now
callback();
- }
}
}
diff --git a/src/BizHawk.Client.Common/lua/LuaDocumentation.cs b/src/BizHawk.Client.Common/lua/LuaDocumentation.cs
index fb6d7dd6cd5..ff347599746 100644
--- a/src/BizHawk.Client.Common/lua/LuaDocumentation.cs
+++ b/src/BizHawk.Client.Common/lua/LuaDocumentation.cs
@@ -10,7 +10,7 @@ public class LuaDocumentation : List
{
public string ToTASVideosWikiMarkup()
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
sb.AppendLine("__This is an autogenerated page, do not edit.__ (To update, open the function list dialog on a Debug build and click the wiki button.)")
.AppendLine()
@@ -76,23 +76,23 @@ public string ToTASVideosWikiMarkup()
** The ''name'' of a callback is an optional parameter in all the event subscription functions. The ''ID'' of a callback is what's returned by the subscription function. Multiple callbacks can share the same name, but IDs are unique.
");
- foreach (var library in this.Select(lf => (Name: lf.Library, Description: lf.LibraryDescription))
+ foreach (var (Name, Description) in this.Select(lf => (Name: lf.Library, Description: lf.LibraryDescription))
.Distinct()
.OrderBy(library => library.Name))
{
sb
- .AppendFormat("%%TAB {0}%%", library.Name)
+ .AppendFormat("%%TAB {0}%%", Name)
.AppendLine()
.AppendLine();
- if (!string.IsNullOrWhiteSpace(library.Description))
+ if (!string.IsNullOrWhiteSpace(Description))
{
sb
- .Append(library.Description)
+ .Append(Description)
.AppendLine()
.AppendLine();
}
- foreach (var func in this.Where(lf => lf.Library == library.Name).OrderBy(lf => lf.Name))
+ foreach (var func in this.Where(lf => lf.Library == Name).OrderBy(lf => lf.Name))
{
string deprecated = func.IsDeprecated ? "__[[deprecated]]__ " : "";
sb
@@ -135,23 +135,23 @@ public class Completion
public string ToSublime2CompletionList()
{
- var sc = new SublimeCompletions();
+ SublimeCompletions sc = new();
foreach (var f in this.OrderBy(lf => lf.Library).ThenBy(lf => lf.Name))
{
- var completion = new SublimeCompletions.Completion
+ SublimeCompletions.Completion completion = new()
{
Trigger = $"{f.Library}.{f.Name}"
};
- var sb = new StringBuilder();
+ StringBuilder sb = new();
if (f.ParameterList.Any())
{
sb
.Append($"{f.Library}.{f.Name}(");
- var parameters = f.Method.GetParameters()
+ List parameters = f.Method.GetParameters()
.ToList();
for (int i = 0; i < parameters.Count; i++)
@@ -187,10 +187,7 @@ public string ToSublime2CompletionList()
return JsonConvert.SerializeObject(sc);
}
- public string ToNotepadPlusPlusAutoComplete()
- {
- return ""; // TODO
- }
+ public string ToNotepadPlusPlusAutoComplete() => ""; // TODO
}
public class LibraryFunction
@@ -232,11 +229,11 @@ public string ParameterList
{
var parameters = Method.GetParameters();
- var list = new StringBuilder();
+ StringBuilder list = new();
list.Append('(');
- for (var i = 0; i < parameters.Length; i++)
+ for (int i = 0; i < parameters.Length; i++)
{
- var p = TypeCleanup(parameters[i].ToString());
+ string p = TypeCleanup(parameters[i].ToString());
if (parameters[i].GetCustomAttribute() != null) p = p.Replace("object", "luacolor");
if (parameters[i].IsOptional)
{
@@ -297,7 +294,7 @@ public string ReturnType
{
get
{
- var returnType = Method.ReturnType.ToString();
+ string returnType = Method.ReturnType.ToString();
return TypeCleanup(returnType).Trim();
}
}
diff --git a/src/BizHawk.Client.Common/lua/LuaFileList.cs b/src/BizHawk.Client.Common/lua/LuaFileList.cs
index 689a16e88e9..7643480ac28 100644
--- a/src/BizHawk.Client.Common/lua/LuaFileList.cs
+++ b/src/BizHawk.Client.Common/lua/LuaFileList.cs
@@ -35,10 +35,7 @@ public LuaFileList(IReadOnlyCollection collection, Action onChanged)
if (collection != null) AddRange(collection); // doesn't actually trigger callback as the superclass' Add is called; if this class is rewritten without `new` methods, something clever will need to be done, like a bool field _initialised
}
- public void StopAllScripts()
- {
- ForEach(lf => lf.State = LuaFile.RunState.Disabled);
- }
+ public void StopAllScripts() => ForEach(lf => lf.State = LuaFile.RunState.Disabled);
public new void Clear()
{
@@ -68,7 +65,7 @@ public void StopAllScripts()
public bool Load(string path, bool disableOnLoad)
{
- var file = new FileInfo(path);
+ FileInfo file = new(path);
if (!file.Exists)
{
return false;
@@ -85,10 +82,10 @@ public bool Load(string path, bool disableOnLoad)
}
else
{
- var scriptPath = line.Substring(2, line.Length - 2);
+ string scriptPath = line.Substring(2, line.Length - 2);
if (!Path.IsPathRooted(scriptPath))
{
- var directory = Path.GetDirectoryName(path);
+ string directory = Path.GetDirectoryName(path);
scriptPath = Path.GetFullPath(Path.Combine(directory ?? "", scriptPath));
}
@@ -107,9 +104,9 @@ public bool Load(string path, bool disableOnLoad)
public void Save(string path)
{
- using var sw = new StreamWriter(path);
- var sb = new StringBuilder();
- var saveDirectory = Path.GetDirectoryName(Path.GetFullPath(path));
+ using StreamWriter sw = new(path);
+ StringBuilder sb = new();
+ string saveDirectory = Path.GetDirectoryName(Path.GetFullPath(path));
foreach (var file in this)
{
if (file.IsSeparator)
diff --git a/src/BizHawk.Client.Common/lua/LuaFunctionList.cs b/src/BizHawk.Client.Common/lua/LuaFunctionList.cs
index 7e20aa4e6ee..6bc86694f2b 100644
--- a/src/BizHawk.Client.Common/lua/LuaFunctionList.cs
+++ b/src/BizHawk.Client.Common/lua/LuaFunctionList.cs
@@ -9,7 +9,7 @@ namespace BizHawk.Client.Common
{
public class LuaFunctionList : IEnumerable
{
- private readonly List _functions = new List();
+ private readonly List _functions = new();
private readonly Action Changed;
@@ -36,7 +36,7 @@ public bool Remove(NamedLuaFunction function, IEmulator emulator)
emulator.AsDebuggable().MemoryCallbacks.Remove(function.MemCallback);
}
- var result = _functions.Remove(function);
+ bool result = _functions.Remove(function);
if (result)
{
Changed();
@@ -47,7 +47,7 @@ public bool Remove(NamedLuaFunction function, IEmulator emulator)
public void RemoveForFile(LuaFile file, IEmulator emulator)
{
- var functionsToRemove = _functions.Where(l => l.LuaFile.Path == file.Path || ReferenceEquals(l.LuaFile.Thread, file.Thread)).ToList();
+ List functionsToRemove = _functions.Where(l => l.LuaFile.Path == file.Path || ReferenceEquals(l.LuaFile.Thread, file.Thread)).ToList();
foreach (var function in functionsToRemove)
{
diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/BitLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/BitLuaLibrary.cs
index f4620df8b11..fc5cb24cee0 100644
--- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/BitLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/BitLuaLibrary.cs
@@ -60,17 +60,11 @@ public uint Lshift(uint val, int amt)
[LuaMethodExample("local uibitrol = bit.rol( 1000, 4 );")]
[LuaMethod("rol", "Left rotate 'val' by 'amt' bits")]
- public static uint Rol(uint val, int amt)
- {
- return (val << amt) | (val >> (32 - amt));
- }
+ public static uint Rol(uint val, int amt) => (val << amt) | (val >> (32 - amt));
[LuaMethodExample("local uibitror = bit.ror( 1000, 4 );")]
[LuaMethod("ror", "Right rotate 'val' by 'amt' bits")]
- public static uint Ror(uint val, int amt)
- {
- return (val >> amt) | (val << (32 - amt));
- }
+ public static uint Ror(uint val, int amt) => (val >> amt) | (val << (32 - amt));
[LuaDeprecatedMethod]
[LuaMethodExample("local uibitrsh = bit.rshift( 1000, 4 );")]
@@ -83,31 +77,19 @@ public uint Rshift(uint val, int amt)
[LuaMethodExample("local inbitars = bit.arshift( -1000, 4 );")]
[LuaMethod("arshift", "Arithmetic shift right of 'val' by 'amt' bits")]
- public static int Arshift(uint val, int amt)
- {
- return (int)val >> amt;
- }
+ public static int Arshift(uint val, int amt) => (int)val >> amt;
[LuaMethodExample("if ( bit.check( -12345, 35 ) ) then\r\n\tconsole.log( \"Returns result of bit 'pos' being set in 'num'\" );\r\nend;")]
[LuaMethod("check", "Returns result of bit 'pos' being set in 'num'")]
- public static bool Check(long num, int pos)
- {
- return (num & (1 << pos)) != 0;
- }
+ public static bool Check(long num, int pos) => (num & (1 << pos)) != 0;
[LuaMethodExample("local uibitset = bit.set( 25, 35 );")]
[LuaMethod("set", "Sets the bit 'pos' in 'num'")]
- public static uint Set(uint num, int pos)
- {
- return num | 1U << pos;
- }
+ public static uint Set(uint num, int pos) => num | 1U << pos;
[LuaMethodExample("local lobitcle = bit.clear( 25, 35 );")]
[LuaMethod("clear", "Clears the bit 'pos' in 'num'")]
- public static long Clear(uint num, int pos)
- {
- return num & ~(1 << pos);
- }
+ public static long Clear(uint num, int pos) => num & ~(1 << pos);
[LuaMethodExample("local usbitbyt = bit.byteswap_16( 100 );")]
[LuaMethod("byteswap_16", "Byte swaps 'short', i.e. bit.byteswap_16(0xFF00) would return 0x00FF")]
diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/EventsLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/EventsLuaLibrary.cs
index 0dc0d636877..9d1b43a6a06 100644
--- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/EventsLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/EventsLuaLibrary.cs
@@ -35,10 +35,7 @@ private void LogMemoryCallbacksNotImplemented(bool isWildcard)
private void LogMemoryExecuteCallbacksNotImplemented(bool isWildcard)
=> Log($"{Emulator.Attributes().CoreName} does not implement {(isWildcard ? "wildcard " : string.Empty)}memory execute callbacks");
- private void LogScopeNotAvailable(string scope)
- {
- Log($"{scope} is not an available scope for {Emulator.Attributes().CoreName}");
- }
+ private void LogScopeNotAvailable(string scope) => Log($"{scope} is not an available scope for {Emulator.Attributes().CoreName}");
[LuaMethod("can_use_callback_params", "Returns whether EmuHawk will pass arguments to callbacks. The current version passes arguments to \"memory\" callbacks (RAM/ROM/bus R/W), so this function will return true for that input. (It returns false for any other input.) This tells you whether it's necessary to enable workarounds/hacks because a script is running in a version without parameter support.")]
[LuaMethodExample("local mem_callback = event.can_use_callback_params(\"memory\") and mem_callback or mem_callback_pre_29;")]
@@ -82,10 +79,7 @@ public string OnInputPoll(LuaFunction luaf, string name = null)
return Guid.Empty.ToString();
}
- private void LogNotImplemented()
- {
- Log($"Error: {Emulator.Attributes().CoreName} does not yet implement input polling callbacks");
- }
+ private void LogNotImplemented() => Log($"Error: {Emulator.Attributes().CoreName} does not yet implement input polling callbacks");
[LuaMethodExample("local steveonl = event.onloadstate(\r\n\tfunction()\r\n\tconsole.log( \"Fires after a state is loaded. Receives a lua function name, and registers it to the event immediately following a successful savestate event\" );\r\nend\", \"Frame name\" );")]
[LuaMethod("onloadstate", "Fires after a state is loaded. Your callback can have 1 parameter, which will be the name of the loaded state.")]
@@ -99,11 +93,9 @@ public string OnMemoryExecute(
LuaFunction luaf,
uint address,
string name = null,
- string scope = null)
- {
-// Log("Deprecated function event.onmemoryexecute() used, replace the call with event.on_bus_exec().");
- return OnBusExec(luaf, address, name: name, scope: scope);
- }
+ string scope = null) =>
+ // Log("Deprecated function event.onmemoryexecute() used, replace the call with event.on_bus_exec().");
+ OnBusExec(luaf, address, name: name, scope: scope);
[LuaMethodExample("local exec_cb_id = event.on_bus_exec(\r\n\tfunction(addr, val, flags)\r\n\t\tconsole.log( \"Fires immediately before the given address is executed by the core. {{val}} is the value to be executed (or {{0}} always, if this feature is only partially implemented).\" );\r\n\tend\r\n\t, 0x200, \"Frame name\", \"System Bus\" );")]
[LuaMethod("on_bus_exec", "Fires immediately before the given address is executed by the core. Your callback can have 3 parameters {{(addr, val, flags)}}. {{val}} is the value to be executed (or {{0}} always, if this feature is only partially implemented).")]
@@ -145,11 +137,9 @@ public string OnBusExec(
public string OnMemoryExecuteAny(
LuaFunction luaf,
string name = null,
- string scope = null)
- {
-// Log("Deprecated function event.onmemoryexecuteany(...) used, replace the call with event.on_bus_exec_any(...).");
- return OnBusExecAny(luaf, name: name, scope: scope);
- }
+ string scope = null) =>
+ // Log("Deprecated function event.onmemoryexecuteany(...) used, replace the call with event.on_bus_exec_any(...).");
+ OnBusExecAny(luaf, name: name, scope: scope);
[LuaMethodExample("local exec_cb_id = event.on_bus_exec_any(\r\n\tfunction(addr, val, flags)\r\n\t\tconsole.log( \"Fires immediately before every instruction executed (in the specified scope) by the core (CPU-intensive). {{val}} is the value to be executed (or {{0}} always, if this feature is only partially implemented).\" );\r\n\tend\r\n\t, \"Frame name\", \"System Bus\" );")]
[LuaMethod("on_bus_exec_any", "Fires immediately before every instruction executed (in the specified scope) by the core (CPU-intensive). Your callback can have 3 parameters {{(addr, val, flags)}}. {{val}} is the value to be executed (or {{0}} always, if this feature is only partially implemented).")]
@@ -196,11 +186,9 @@ public string OnMemoryRead(
LuaFunction luaf,
uint? address = null,
string name = null,
- string scope = null)
- {
-// Log("Deprecated function event.onmemoryread(...) used, replace the call with event.on_bus_read(...).");
- return OnBusRead(luaf, address, name: name, scope: scope);
- }
+ string scope = null) =>
+ // Log("Deprecated function event.onmemoryread(...) used, replace the call with event.on_bus_read(...).");
+ OnBusRead(luaf, address, name: name, scope: scope);
[LuaMethodExample("local exec_cb_id = event.on_bus_read(\r\n\tfunction(addr, val, flags)\r\n\t\tconsole.log( \"Fires immediately before the given address is read by the core. {{val}} is the value read. If no address is given, it will fire on every memory read.\" );\r\n\tend\r\n\t, 0x200, \"Frame name\" );")]
[LuaMethod("on_bus_read", "Fires immediately before the given address is read by the core. Your callback can have 3 parameters {{(addr, val, flags)}}. {{val}} is the value read. If no address is given, it will fire on every memory read.")]
@@ -242,11 +230,9 @@ public string OnMemoryWrite(
LuaFunction luaf,
uint? address = null,
string name = null,
- string scope = null)
- {
-// Log("Deprecated function event.onmemorywrite(...) used, replace the call with event.on_bus_write(...).");
- return OnBusWrite(luaf, address, name: name, scope: scope);
- }
+ string scope = null) =>
+ // Log("Deprecated function event.onmemorywrite(...) used, replace the call with event.on_bus_write(...).");
+ OnBusWrite(luaf, address, name: name, scope: scope);
[LuaMethodExample("local exec_cb_id = event.on_bus_write(\r\n\tfunction(addr, val, flags)\r\n\t\tconsole.log( \"Fires immediately before the given address is written by the core. {{val}} is the value to be written (or {{0}} always, if this feature is only partially implemented). If no address is given, it will fire on every memory write.\" );\r\n\tend\r\n\t, 0x200, \"Frame name\" );")]
[LuaMethod("on_bus_write", "Fires immediately before the given address is written by the core. Your callback can have 3 parameters {{(addr, val, flags)}}. {{val}} is the value to be written (or {{0}} always, if this feature is only partially implemented). If no address is given, it will fire on every memory write.")]
@@ -336,9 +322,6 @@ private string ProcessScope(string scope)
return scope;
}
- private bool HasScope(string scope)
- {
- return string.IsNullOrWhiteSpace(scope) || DebuggableCore.MemoryCallbacks.AvailableScopes.Contains(scope);
- }
+ private bool HasScope(string scope) => string.IsNullOrWhiteSpace(scope) || DebuggableCore.MemoryCallbacks.AvailableScopes.Contains(scope);
}
}
diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/MainMemoryLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/MainMemoryLuaLibrary.cs
index 5c012bd8bf2..7ecfc8feb81 100644
--- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/MainMemoryLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/MainMemoryLuaLibrary.cs
@@ -38,10 +38,7 @@ public string GetName()
[LuaMethodExample("local uimaiget = mainmemory.getcurrentmemorydomainsize( );")]
[LuaMethod("getcurrentmemorydomainsize", "Returns the number of bytes of the domain defined as main memory")]
- public uint GetSize()
- {
- return (uint)Domain.Size;
- }
+ public uint GetSize() => (uint)Domain.Size;
[LuaMethodExample("local uimairea = mainmemory.readbyte( 0x100 );")]
[LuaMethod("readbyte", "gets the value from the given address as an unsigned byte")]
@@ -70,8 +67,7 @@ public LuaTable ReadBytesAsDict(long addr, int length)
[LuaDeprecatedMethod]
[LuaMethod("writebyterange", "Writes the given values to the given addresses as unsigned bytes")]
- public void WriteByteRange(LuaTable memoryblock)
- {
+ public void WriteByteRange(LuaTable memoryblock) =>
#if true
WriteBytesAsDict(memoryblock);
#else
@@ -95,7 +91,7 @@ public void WriteByteRange(LuaTable memoryblock)
Log($"Error: the domain {d.Name} is not writable");
}
#endif
- }
+
[LuaMethodExample("mainmemory.write_bytes_as_array(0x100, { 0xAB, 0x12, 0xCD, 0x34 });")]
[LuaMethod("write_bytes_as_array", "Writes sequential bytes starting at addr.")]
diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/SNESLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/SNESLuaLibrary.cs
index 139d96f7c9b..1d2e92cea14 100644
--- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/SNESLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/SNESLuaLibrary.cs
@@ -23,59 +23,35 @@ private LibsnesCore.SnesSettings Settings
[LuaMethodExample("if ( snes.getlayer_bg_1( ) ) then\r\n\tconsole.log( \"Returns whether the bg 1 layer is displayed\" );\r\nend;")]
[LuaMethod("getlayer_bg_1", "Returns whether the bg 1 layer is displayed")]
- public bool GetLayerBg1()
- {
- return Settings.ShowBG1_1;
- }
+ public bool GetLayerBg1() => Settings.ShowBG1_1;
[LuaMethodExample("if ( snes.getlayer_bg_2( ) ) then\r\n\tconsole.log( \"Returns whether the bg 2 layer is displayed\" );\r\nend;")]
[LuaMethod("getlayer_bg_2", "Returns whether the bg 2 layer is displayed")]
- public bool GetLayerBg2()
- {
- return Settings.ShowBG2_1;
- }
+ public bool GetLayerBg2() => Settings.ShowBG2_1;
[LuaMethodExample("if ( snes.getlayer_bg_3( ) ) then\r\n\tconsole.log( \"Returns whether the bg 3 layer is displayed\" );\r\nend;")]
[LuaMethod("getlayer_bg_3", "Returns whether the bg 3 layer is displayed")]
- public bool GetLayerBg3()
- {
- return Settings.ShowBG3_1;
- }
+ public bool GetLayerBg3() => Settings.ShowBG3_1;
[LuaMethodExample("if ( snes.getlayer_bg_4( ) ) then\r\n\tconsole.log( \"Returns whether the bg 4 layer is displayed\" );\r\nend;")]
[LuaMethod("getlayer_bg_4", "Returns whether the bg 4 layer is displayed")]
- public bool GetLayerBg4()
- {
- return Settings.ShowBG4_1;
- }
+ public bool GetLayerBg4() => Settings.ShowBG4_1;
[LuaMethodExample("if ( snes.getlayer_obj_1( ) ) then\r\n\tconsole.log( \"Returns whether the obj 1 layer is displayed\" );\r\nend;")]
[LuaMethod("getlayer_obj_1", "Returns whether the obj 1 layer is displayed")]
- public bool GetLayerObj1()
- {
- return Settings.ShowOBJ_0;
- }
+ public bool GetLayerObj1() => Settings.ShowOBJ_0;
[LuaMethodExample("if ( snes.getlayer_obj_2( ) ) then\r\n\tconsole.log( \"Returns whether the obj 2 layer is displayed\" );\r\nend;")]
[LuaMethod("getlayer_obj_2", "Returns whether the obj 2 layer is displayed")]
- public bool GetLayerObj2()
- {
- return Settings.ShowOBJ_1;
- }
+ public bool GetLayerObj2() => Settings.ShowOBJ_1;
[LuaMethodExample("if ( snes.getlayer_obj_3( ) ) then\r\n\tconsole.log( \"Returns whether the obj 3 layer is displayed\" );\r\nend;")]
[LuaMethod("getlayer_obj_3", "Returns whether the obj 3 layer is displayed")]
- public bool GetLayerObj3()
- {
- return Settings.ShowOBJ_2;
- }
+ public bool GetLayerObj3() => Settings.ShowOBJ_2;
[LuaMethodExample("if ( snes.getlayer_obj_4( ) ) then\r\n\tconsole.log( \"Returns whether the obj 4 layer is displayed\" );\r\nend;")]
[LuaMethod("getlayer_obj_4", "Returns whether the obj 4 layer is displayed")]
- public bool GetLayerObj4()
- {
- return Settings.ShowOBJ_3;
- }
+ public bool GetLayerObj4() => Settings.ShowOBJ_3;
[LuaMethodExample("snes.setlayer_bg_1( true );")]
[LuaMethod("setlayer_bg_1", "Sets whether the bg 1 layer is displayed")]
diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/StringLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/StringLuaLibrary.cs
index c70b37a1940..93c3ba29544 100644
--- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/StringLuaLibrary.cs
+++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/StringLuaLibrary.cs
@@ -19,7 +19,7 @@ public StringLuaLibrary(ILuaLibraries luaLibsImpl, ApiContainer apiContainer, Ac
[LuaMethod("hex", "Converts the number to a string representation of the hexadecimal value of the given number")]
public static string Hex(long num)
{
- var hex = $"{num:X}";
+ string hex = $"{num:X}";
if (hex.Length == 1)
{
hex = $"0{hex}";
@@ -32,7 +32,7 @@ public static string Hex(long num)
[LuaMethod("binary", "Converts the number to a string representation of the binary value of the given number")]
public static string Binary(long num)
{
- var binary = Convert.ToString(num, 2);
+ string binary = Convert.ToString(num, 2);
binary = binary.TrimStart('0');
return binary;
}
@@ -41,7 +41,7 @@ public static string Binary(long num)
[LuaMethod("octal", "Converts the number to a string representation of the octal value of the given number")]
public static string Octal(long num)
{
- var octal = Convert.ToString(num, 8);
+ string octal = Convert.ToString(num, 8);
if (octal.Length == 1)
{
octal = $"0{octal}";
diff --git a/src/BizHawk.Client.Common/lua/LuaSandbox.cs b/src/BizHawk.Client.Common/lua/LuaSandbox.cs
index e1f5a203d0a..0c6a62baaeb 100644
--- a/src/BizHawk.Client.Common/lua/LuaSandbox.cs
+++ b/src/BizHawk.Client.Common/lua/LuaSandbox.cs
@@ -12,10 +12,7 @@ public class LuaSandbox
public static Action DefaultLogger { get; set; }
- public void SetSandboxCurrentDirectory(string dir)
- {
- _currentDirectory = dir;
- }
+ public void SetSandboxCurrentDirectory(string dir) => _currentDirectory = dir;
private string _currentDirectory;
@@ -58,7 +55,7 @@ private void Sandbox(Action callback, Action exceptionCallback)
}
catch (NLua.Exceptions.LuaException ex)
{
- var exStr = ex.ToString() + '\n';
+ string exStr = ex.ToString() + '\n';
if (ex.InnerException is not null)
{
exStr += ex.InnerException.ToString() + '\n';
@@ -79,7 +76,7 @@ private void Sandbox(Action callback, Action exceptionCallback)
public static LuaSandbox CreateSandbox(LuaThread thread, string initialDirectory)
{
- var sandbox = new LuaSandbox();
+ LuaSandbox sandbox = new();
SandboxForThread.Add(thread, sandbox);
sandbox.SetSandboxCurrentDirectory(initialDirectory);
return sandbox;
@@ -108,9 +105,6 @@ public static LuaSandbox GetSandbox(LuaThread thread)
}
}
- public static void Sandbox(LuaThread thread, Action callback, Action exceptionCallback = null)
- {
- GetSandbox(thread).Sandbox(callback, exceptionCallback);
- }
+ public static void Sandbox(LuaThread thread, Action callback, Action exceptionCallback = null) => GetSandbox(thread).Sandbox(callback, exceptionCallback);
}
}
diff --git a/src/BizHawk.Client.Common/lua/NLuaTableHelper.cs b/src/BizHawk.Client.Common/lua/NLuaTableHelper.cs
index 0ef2ddab795..22a6e9603d1 100644
--- a/src/BizHawk.Client.Common/lua/NLuaTableHelper.cs
+++ b/src/BizHawk.Client.Common/lua/NLuaTableHelper.cs
@@ -45,10 +45,10 @@ public LuaTable ListToTable(IReadOnlyList list, int indexFrom = 1)
public LuaTable MemoryBlockToTable(IReadOnlyList bytes, long startAddr)
{
- var length = bytes.Count;
+ int length = bytes.Count;
var table = CreateTable();
- var iArray = 0;
- var iDict = startAddr;
+ int iArray = 0;
+ long iDict = startAddr;
while (iArray < length) table[iDict++] = bytes[iArray++];
return table;
}
@@ -59,7 +59,7 @@ public LuaTable ObjectToTable(object obj)
foreach (var method in obj.GetType().GetMethods())
{
if (!method.IsPublic) continue;
- var foundAttrs = method.GetCustomAttributes(typeof(LuaMethodAttribute), false);
+ object[] foundAttrs = method.GetCustomAttributes(typeof(LuaMethodAttribute), false);
table[method.Name] = _lua.RegisterFunction(
foundAttrs.Length == 0 ? string.Empty : ((LuaMethodAttribute) foundAttrs[0]).Name, // empty string will default to the actual method name
obj,
@@ -90,11 +90,11 @@ public LuaTable ObjectToTable(object obj)
case string s:
if (s[0] is '#' && (s.Length is 7 or 9))
{
- var i1 = uint.Parse(s.Substring(1), NumberStyles.HexNumber);
+ uint i1 = uint.Parse(s.Substring(1), NumberStyles.HexNumber);
if (s.Length is 7) i1 |= 0xFF000000U;
return ParseColor(unchecked((int) i1), safe, logCallback);
}
- var fromName = Color.FromName(s);
+ Color fromName = Color.FromName(s);
if (fromName.IsNamedColor) return fromName;
if (safe) logCallback($"ParseColor: not a known color name (\"{s}\")");
return null;
diff --git a/src/BizHawk.Client.Common/movie/BasicMovieInfo.cs b/src/BizHawk.Client.Common/movie/BasicMovieInfo.cs
index 82361ffc242..e68ada702f6 100644
--- a/src/BizHawk.Client.Common/movie/BasicMovieInfo.cs
+++ b/src/BizHawk.Client.Common/movie/BasicMovieInfo.cs
@@ -47,15 +47,15 @@ public TimeSpan TimeLength
{
double numSeconds;
- if (Header.TryGetValue(HeaderKeys.CycleCount, out var numCyclesStr) && Header.TryGetValue(HeaderKeys.ClockRate, out var clockRateStr))
+ if (Header.TryGetValue(HeaderKeys.CycleCount, out string numCyclesStr) && Header.TryGetValue(HeaderKeys.ClockRate, out string clockRateStr))
{
- var numCycles = Convert.ToUInt64(numCyclesStr);
- var clockRate = Convert.ToDouble(clockRateStr, CultureInfo.InvariantCulture);
+ ulong numCycles = Convert.ToUInt64(numCyclesStr);
+ double clockRate = Convert.ToDouble(clockRateStr, CultureInfo.InvariantCulture);
numSeconds = numCycles / clockRate;
}
else
{
- var numFrames = (ulong)FrameCount;
+ ulong numFrames = (ulong)FrameCount;
numSeconds = numFrames / FrameRate;
}
@@ -67,7 +67,7 @@ public double FrameRate
{
get
{
- if (SystemID == VSystemID.Raw.Arcade && Header.TryGetValue(HeaderKeys.VsyncAttoseconds, out var vsyncAttoStr))
+ if (SystemID == VSystemID.Raw.Arcade && Header.TryGetValue(HeaderKeys.VsyncAttoseconds, out string vsyncAttoStr))
{
const decimal attosInSec = 1000000000000000000;
return (double)(attosInSec / Convert.ToUInt64(vsyncAttoStr));
@@ -96,7 +96,7 @@ public virtual string SystemID
public virtual ulong Rerecords
{
- get => Header.TryGetValue(HeaderKeys.Rerecords, out var rerecords) ? ulong.Parse(rerecords) : 0;
+ get => Header.TryGetValue(HeaderKeys.Rerecords, out string rerecords) ? ulong.Parse(rerecords) : 0;
set => Header[HeaderKeys.Rerecords] = value.ToString();
}
@@ -146,7 +146,7 @@ public virtual string FirmwareHash
public bool Load()
{
- var file = new FileInfo(Filename);
+ FileInfo file = new(Filename);
if (!file.Exists)
{
return false;
@@ -154,7 +154,7 @@ public bool Load()
try
{
- using var bl = ZipStateLoader.LoadAndDetect(Filename, true);
+ using ZipStateLoader bl = ZipStateLoader.LoadAndDetect(Filename, true);
if (bl is null) return false;
ClearBeforeLoad();
LoadFields(bl);
@@ -187,7 +187,7 @@ protected virtual void LoadFields(ZipStateLoader bl)
{
if (!string.IsNullOrWhiteSpace(line))
{
- var pair = line.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
+ string[] pair = line.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (pair.Length > 1)
{
diff --git a/src/BizHawk.Client.Common/movie/MovieConversionExtensions.cs b/src/BizHawk.Client.Common/movie/MovieConversionExtensions.cs
index f42c10f0f7e..fd53d0c1dea 100644
--- a/src/BizHawk.Client.Common/movie/MovieConversionExtensions.cs
+++ b/src/BizHawk.Client.Common/movie/MovieConversionExtensions.cs
@@ -23,7 +23,7 @@ public static class MovieConversionExtensions
public static ITasMovie ToTasMovie(this IMovie old)
{
string newFilename = ConvertFileNameToTasMovie(old.Filename);
- var tas = (ITasMovie)old.Session.Get(newFilename);
+ ITasMovie tas = (ITasMovie)old.Session.Get(newFilename);
tas.CopyLog(old.GetLogEntries());
tas.LogKey = old.LogKey;
@@ -38,7 +38,7 @@ public static ITasMovie ToTasMovie(this IMovie old)
tas.SyncSettingsJson = old.SyncSettingsJson;
tas.Comments.Clear();
- foreach (var comment in old.Comments)
+ foreach (string comment in old.Comments)
{
tas.Comments.Add(comment);
}
@@ -72,7 +72,7 @@ public static IMovie ToBk2(this IMovie old)
bk2.SyncSettingsJson = old.SyncSettingsJson;
bk2.Comments.Clear();
- foreach (var comment in old.Comments)
+ foreach (string comment in old.Comments)
{
bk2.Comments.Add(comment);
}
@@ -94,7 +94,7 @@ public static ITasMovie ConvertToSavestateAnchoredMovie(this ITasMovie old, int
{
string newFilename = ConvertFileNameToTasMovie(old.Filename);
- var tas = (ITasMovie)old.Session.Get(newFilename);
+ ITasMovie tas = (ITasMovie)old.Session.Get(newFilename);
tas.BinarySavestate = savestate;
tas.LagLog.Clear();
@@ -126,12 +126,12 @@ public static ITasMovie ConvertToSavestateAnchoredMovie(this ITasMovie old, int
}
tas.Subtitles.Clear();
- foreach (Subtitle sub in old.Subtitles)
+ foreach (var sub in old.Subtitles)
{
tas.Subtitles.Add(sub);
}
- foreach (TasMovieMarker marker in old.Markers)
+ foreach (var marker in old.Markers)
{
if (marker.Frame > frame)
{
@@ -149,7 +149,7 @@ public static ITasMovie ConvertToSaveRamAnchoredMovie(this ITasMovie old, byte[]
{
string newFilename = ConvertFileNameToTasMovie(old.Filename);
- var tas = (ITasMovie)old.Session.Get(newFilename);
+ ITasMovie tas = (ITasMovie)old.Session.Get(newFilename);
tas.SaveRam = saveRam;
tas.TasStateManager.Clear();
tas.LagLog.Clear();
@@ -172,7 +172,7 @@ public static ITasMovie ConvertToSaveRamAnchoredMovie(this ITasMovie old, byte[]
}
tas.Subtitles.Clear();
- foreach (Subtitle sub in old.Subtitles)
+ foreach (var sub in old.Subtitles)
{
tas.Subtitles.Add(sub);
}
@@ -227,7 +227,7 @@ public static void PopulateWithDefaultHeaderValues(
{
foreach (var firmware in firmwareManager.RecentlyServed)
{
- var key = firmware.ID.MovieHeaderKey;
+ string key = firmware.ID.MovieHeaderKey;
if (!movie.HeaderEntries.ContainsKey(key))
{
movie.HeaderEntries.Add(key, firmware.Hash);
@@ -309,7 +309,7 @@ internal static string ConvertFileNameToTasMovie(string oldFileName)
if (oldFileName is null) return null;
var (dir, fileNoExt, _) = oldFileName.SplitPathToDirFileAndExt();
if (dir is null) return string.Empty;
- var newFileName = Path.Combine(dir, $"{fileNoExt}.{TasMovie.Extension}");
+ string newFileName = Path.Combine(dir, $"{fileNoExt}.{TasMovie.Extension}");
int fileSuffix = 0;
while (File.Exists(newFileName))
{
diff --git a/src/BizHawk.Client.Common/movie/MovieService.cs b/src/BizHawk.Client.Common/movie/MovieService.cs
index a7f43490f6c..ebdb6aa8012 100644
--- a/src/BizHawk.Client.Common/movie/MovieService.cs
+++ b/src/BizHawk.Client.Common/movie/MovieService.cs
@@ -16,14 +16,11 @@ public static class MovieService
///
public static IEnumerable MovieExtensions => new[] { Bk2Movie.Extension, TasMovie.Extension };
- public static bool IsValidMovieExtension(string ext)
- {
- return MovieExtensions.Contains(ext.Replace(".", ""), StringComparer.OrdinalIgnoreCase);
- }
+ public static bool IsValidMovieExtension(string ext) => MovieExtensions.Contains(ext.Replace(".", ""), StringComparer.OrdinalIgnoreCase);
public static bool IsCurrentTasVersion(string movieVersion)
{
- var actual = ParseTasMovieVersion(movieVersion);
+ double actual = ParseTasMovieVersion(movieVersion);
return actual.HawkFloatEquality(TasMovie.CurrentVersion);
}
@@ -34,7 +31,7 @@ internal static double ParseTasMovieVersion(string movieVersion)
return 1.0F;
}
- var split = movieVersion
+ string[] split = movieVersion
.ToLowerInvariant()
.Split(new[] {"tasproj"}, StringSplitOptions.RemoveEmptyEntries);
@@ -43,17 +40,17 @@ internal static double ParseTasMovieVersion(string movieVersion)
return 1.0F;
}
- var versionStr = split[1]
+ string versionStr = split[1]
.Trim()
.Replace("v", "");
- if (double.TryParse(versionStr, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedWithPeriod))
+ if (double.TryParse(versionStr, NumberStyles.Float, CultureInfo.InvariantCulture, out double parsedWithPeriod))
{
return parsedWithPeriod;
}
// Accept .tasproj files written from <= 2.5 where the host culture settings used ','
- if (double.TryParse(versionStr.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedWithComma))
+ if (double.TryParse(versionStr.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out double parsedWithComma))
{
return parsedWithComma;
}
diff --git a/src/BizHawk.Client.Common/movie/MovieSession.cs b/src/BizHawk.Client.Common/movie/MovieSession.cs
index 21887e484b3..57f0e81ae00 100644
--- a/src/BizHawk.Client.Common/movie/MovieSession.cs
+++ b/src/BizHawk.Client.Common/movie/MovieSession.cs
@@ -53,16 +53,11 @@ public MovieSession(
public IMovieController MovieController { get; private set; } = new Bk2Controller("", NullController.Instance.Definition);
- public IMovieController GenerateMovieController(ControllerDefinition definition = null)
- {
+ public IMovieController GenerateMovieController(ControllerDefinition definition = null) =>
// TODO: expose Movie.LogKey and pass in here
- return new Bk2Controller("", definition ?? MovieController.Definition);
- }
+ new Bk2Controller("", definition ?? MovieController.Definition);
- public void SetMovieController(ControllerDefinition definition)
- {
- MovieController = GenerateMovieController(definition);
- }
+ public void SetMovieController(ControllerDefinition definition) => MovieController = GenerateMovieController(definition);
public void HandleFrameBefore()
{
@@ -128,7 +123,7 @@ public bool CheckSavestateTimeline(TextReader reader)
{
if (Movie.IsActive() && ReadOnly)
{
- var result = Movie.CheckTimeLines(reader, out var errorMsg);
+ bool result = Movie.CheckTimeLines(reader, out string errorMsg);
if (!result)
{
Output(errorMsg);
@@ -174,7 +169,7 @@ public bool HandleLoadState(TextReader reader)
Movie.SwitchToRecord();
}
- var result = Movie.ExtractInputLog(reader, out var errorMsg);
+ bool result = Movie.ExtractInputLog(reader, out string errorMsg);
if (!result)
{
Output(errorMsg);
@@ -210,14 +205,14 @@ public void QueueNewMovie(IMovie movie, bool record, string systemId, IDictionar
{
if (string.IsNullOrWhiteSpace(movie.Core))
{
- PopupMessage(preferredCores.TryGetValue(systemId, out var coreName)
+ PopupMessage(preferredCores.TryGetValue(systemId, out string coreName)
? $"No core specified in the movie file, using the preferred core {coreName} instead."
: "No core specified in the movie file, using the default core instead.");
}
else
{
- var keys = preferredCores.Keys.ToList();
- foreach (var k in keys)
+ List keys = preferredCores.Keys.ToList();
+ foreach (string k in keys)
{
preferredCores[k] = movie.Core;
}
@@ -267,7 +262,7 @@ public void StopMovie(bool saveChanges = true)
{
if (Movie.IsActive())
{
- var message = "Movie ";
+ string message = "Movie ";
if (Movie.IsRecording())
{
message += "recording ";
@@ -279,7 +274,7 @@ public void StopMovie(bool saveChanges = true)
message += "stopped.";
- var result = Movie.Stop(saveChanges);
+ bool result = Movie.Stop(saveChanges);
if (result)
{
Output($"{Path.GetFileName(Movie.Filename)} written to disk.");
@@ -323,10 +318,7 @@ public IMovie Get(string path)
private void Output(string message)
=> _dialogParent.DialogController.AddOnScreenMessage(message);
- private void LatchInputToUser()
- {
- MovieOut.Source = MovieIn;
- }
+ private void LatchInputToUser() => MovieOut.Source = MovieIn;
// Latch input from the input log, if available
private void LatchInputToLog()
@@ -350,11 +342,11 @@ private void HandlePlaybackEnd()
bool movieHasValue = Movie.HeaderEntries.TryGetValue(HeaderKeys.CycleCount, out string movieValueStr);
long movieValue = movieHasValue ? Convert.ToInt64(movieValueStr) : 0;
- var valuesMatch = movieValue == coreValue;
+ bool valuesMatch = movieValue == coreValue;
if (!movieHasValue || !valuesMatch)
{
- var previousState = !movieHasValue
+ string previousState = !movieHasValue
? $"The movie is currently missing a cycle count."
: $"The cycle count in the movie ({movieValue}) doesn't match the current value.";
// TODO: Ideally, this would be a Yes/No MessageBox that saves when "Yes" is pressed.
diff --git a/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs b/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs
index 773f7d87851..f1b278af60b 100644
--- a/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs
+++ b/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs
@@ -13,7 +13,7 @@ public static class PlatformFrameRates
private static readonly double NTSCCarrier = 4500000 * 227.5 / 286; // 3.579545454... MHz
private static readonly double PALNCarrier = (15625 * 229.25) + 25; // 3.58205625 MHz
- private static readonly Dictionary Rates = new Dictionary
+ private static readonly Dictionary Rates = new()
{
["NES"] = 60.098813897440515532, // discussion here: http://forums.nesdev.com/viewtopic.php?t=492 ; a rational expression would be (19687500 / 11) / ((341*262-0.529780.5)/3) -> (118125000 / 1965513) -> 60.098813897440515529533511098629 (so our chosen number is very close)
["NES_PAL"] = 50.006977968268290849,
@@ -81,6 +81,6 @@ public static class PlatformFrameRates
};
public static double GetFrameRate(string systemId, bool pal)
- => Rates.TryGetValue(systemId + (pal ? "_PAL" : ""), out var d) ? d : 60.0;
+ => Rates.TryGetValue(systemId + (pal ? "_PAL" : ""), out double d) ? d : 60.0;
}
}
diff --git a/src/BizHawk.Client.Common/movie/Subtitle.cs b/src/BizHawk.Client.Common/movie/Subtitle.cs
index b8e7c2afe06..78bc98a52cb 100644
--- a/src/BizHawk.Client.Common/movie/Subtitle.cs
+++ b/src/BizHawk.Client.Common/movie/Subtitle.cs
@@ -33,7 +33,7 @@ public Subtitle(Subtitle s)
public override string ToString()
{
- var sb = new StringBuilder("subtitle ");
+ StringBuilder sb = new("subtitle ");
sb
.Append(Frame).Append(' ')
.Append(X).Append(' ')
@@ -47,7 +47,7 @@ public override string ToString()
public string ToSubRip(int index, double fps, bool addColorTag)
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
sb.Append(index);
sb.Append("\r\n");
@@ -59,9 +59,9 @@ public string ToSubRip(int index, double fps, bool addColorTag)
int startTime = (int)(start * 1000 / fps);
int endTime = (int)(end * 1000 / fps);
- var startString = $"{startTime / 3600000:d2}:{(startTime / 60000) % 60:d2}:{(startTime / 1000) % 60:d2},{startTime % 1000:d3}";
+ string startString = $"{startTime / 3600000:d2}:{(startTime / 60000) % 60:d2}:{(startTime / 1000) % 60:d2},{startTime % 1000:d3}";
- var endString = $"{endTime / 3600000:d2}:{(endTime / 60000) % 60:d2}:{(endTime / 1000) % 60:d2},{endTime % 1000:d3}";
+ string endString = $"{endTime / 3600000:d2}:{(endTime / 60000) % 60:d2}:{(endTime / 1000) % 60:d2},{endTime % 1000:d3}";
sb.Append(startString);
sb.Append(" --> ");
diff --git a/src/BizHawk.Client.Common/movie/SubtitleList.cs b/src/BizHawk.Client.Common/movie/SubtitleList.cs
index d2a19bd63e6..7d779955e95 100644
--- a/src/BizHawk.Client.Common/movie/SubtitleList.cs
+++ b/src/BizHawk.Client.Common/movie/SubtitleList.cs
@@ -22,7 +22,7 @@ public SubtitleList()
public override string ToString()
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
Sort();
ForEach(subtitle => sb.AppendLine(subtitle.ToString()));
return sb.ToString();
@@ -34,11 +34,11 @@ public bool AddFromString(string subtitleStr)
{
try
{
- var subParts = subtitleStr.Split(' ');
+ string[] subParts = subtitleStr.Split(' ');
// Unfortunately I made the file format space delaminated so this hack is necessary to get the message
- var message = "";
- for (var i = 6; i < subParts.Length; i++)
+ string message = "";
+ for (int i = 6; i < subParts.Length; i++)
{
message += subParts[i] + ' ';
}
@@ -76,8 +76,8 @@ public bool AddFromString(string subtitleStr)
public string ToSubRip(double fps)
{
int index = 1;
- var sb = new StringBuilder();
- var subs = new List();
+ StringBuilder sb = new();
+ List subs = new();
foreach (var subtitle in this)
{
subs.Add(new Subtitle(subtitle));
diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Controller.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Controller.cs
index e2484906088..65612a0e891 100755
--- a/src/BizHawk.Client.Common/movie/bk2/Bk2Controller.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Controller.cs
@@ -31,7 +31,7 @@ public Bk2Controller(string key, ControllerDefinition definition) : this(definit
{
if (!string.IsNullOrEmpty(key))
{
- var groups = key.Split(new[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
+ string[] groups = key.Split(new[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
_type.ControlsFromLog = groups
.Select(group => group.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries).ToList())
@@ -42,7 +42,7 @@ public Bk2Controller(string key, ControllerDefinition definition) : this(definit
public Bk2Controller(ControllerDefinition definition)
{
_type = new Bk2ControllerDefinition(definition);
- foreach ((string axisName, AxisSpec range) in definition.Axes)
+ foreach ((string axisName, var range) in definition.Axes)
{
_myAxisControls[axisName] = range.Neutral;
}
@@ -65,7 +65,7 @@ public void SetFrom(IController source)
_myBoolButtons[button] = source.IsPressed(button);
}
- foreach (var name in Definition.Axes.Keys)
+ foreach (string name in Definition.Axes.Keys)
{
_myAxisControls[name] = source.AxisValue(name);
}
@@ -73,7 +73,7 @@ public void SetFrom(IController source)
public void SetFromSticky(IStickyAdapter controller)
{
- foreach (var button in Definition.BoolButtons)
+ foreach (string button in Definition.BoolButtons)
{
_myBoolButtons[button] = controller.IsSticky(button);
}
@@ -86,8 +86,8 @@ public void SetFromMnemonic(string mnemonic)
{
if (!string.IsNullOrWhiteSpace(mnemonic))
{
- var trimmed = mnemonic.Replace("|", "");
- var iterator = 0;
+ string trimmed = mnemonic.Replace("|", "");
+ int iterator = 0;
foreach (var key in ControlsOrdered)
{
@@ -98,9 +98,9 @@ public void SetFromMnemonic(string mnemonic)
}
else if (key.IsAxis)
{
- var commaIndex = trimmed.Substring(iterator).IndexOf(',');
- var temp = trimmed.Substring(iterator, commaIndex);
- var val = int.Parse(temp.Trim());
+ int commaIndex = trimmed.Substring(iterator).IndexOf(',');
+ string temp = trimmed.Substring(iterator, commaIndex);
+ int val = int.Parse(temp.Trim());
_myAxisControls[key.Name] = val;
iterator += commaIndex + 1;
@@ -109,15 +109,9 @@ public void SetFromMnemonic(string mnemonic)
}
}
- public void SetBool(string buttonName, bool value)
- {
- _myBoolButtons[buttonName] = value;
- }
+ public void SetBool(string buttonName, bool value) => _myBoolButtons[buttonName] = value;
- public void SetAxis(string buttonName, int value)
- {
- _myAxisControls[buttonName] = value;
- }
+ public void SetAxis(string buttonName, int value) => _myAxisControls[buttonName] = value;
private class ControlMap
{
diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs
index 4a6bd55d596..7eb464d8346 100644
--- a/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs
@@ -9,13 +9,13 @@ public class Bk2Header : Dictionary
{
public new string this[string key]
{
- get => TryGetValue(key, out var s) ? s : string.Empty;
+ get => TryGetValue(key, out string s) ? s : string.Empty;
set => base[key] = value;
}
public override string ToString()
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
foreach (var (k, v) in this) sb.Append(k).Append(' ').Append(v).AppendLine();
return sb.ToString();
}
diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs
index 7b5d10ea3fe..8d8985e3a8d 100644
--- a/src/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs
@@ -22,7 +22,7 @@ public Bk2LogEntryGenerator(string systemId, IController source)
_controlsOrdered = _source.Definition.ControlsOrdered.Where(static c => c.Count is not 0).ToList();
foreach (var group in _controlsOrdered)
{
- foreach (var button in group)
+ foreach (string button in group)
{
_mnemonics.Add(button, Bk2MnemonicLookup.Lookup(button, _systemId));
}
@@ -47,13 +47,13 @@ public Bk2LogEntryGenerator(string systemId, IController source)
///
public string GenerateLogKey()
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
sb.Append("LogKey:");
foreach (var group in _source.Definition.ControlsOrdered.Where(static c => c.Count is not 0))
{
sb.Append('#');
- foreach (var button in group)
+ foreach (string button in group)
{
sb.Append(button).Append('|');
}
@@ -67,8 +67,8 @@ public string GenerateLogKey()
///
public IDictionary Map()
{
- var dict = new Dictionary();
- foreach (var button in _source.Definition.OrderedControlsFlat)
+ Dictionary dict = new();
+ foreach (string button in _source.Definition.OrderedControlsFlat)
{
if (_source.Definition.BoolButtons.Contains(button))
{
@@ -85,17 +85,17 @@ public IDictionary Map()
private string CreateLogEntry(bool createEmpty = false)
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
sb.Append('|');
foreach (var group in _controlsOrdered)
{
- foreach (var button in group)
+ foreach (string button in group)
{
if (_source.Definition.Axes.TryGetValue(button, out var range))
{
- var val = createEmpty ? range.Neutral : _source.AxisValue(button);
+ int val = createEmpty ? range.Neutral : _source.AxisValue(button);
sb.Append(val.ToString().PadLeft(5, ' ')).Append(',');
}
else
diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs
index ba03a26230b..2872b8de63d 100644
--- a/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs
@@ -11,7 +11,7 @@ internal static class Bk2MnemonicLookup
{
public static char Lookup(string button, string systemId)
{
- var key = button.Replace("Key ", "");
+ string key = button.Replace("Key ", "");
if (key.StartsWith('P'))
{
if (key.Length > 2 && key[1] == '1' && key[2] >= '0' && key[2] <= '9') // Hack to support 10-20 controllers, TODO: regex this thing instead
@@ -25,12 +25,12 @@ public static char Lookup(string button, string systemId)
}
key = key.RemovePrefix(LibretroHost.LibretroControllerDef.PFX_RETROPAD);
- if (SystemOverrides.TryGetValue(systemId, out var overridesForSys) && overridesForSys.TryGetValue(key, out var c))
+ if (SystemOverrides.TryGetValue(systemId, out var overridesForSys) && overridesForSys.TryGetValue(key, out char c))
{
return c;
}
- if (BaseMnemonicLookupTable.TryGetValue(key, out var c1))
+ if (BaseMnemonicLookupTable.TryGetValue(key, out char c1))
{
return c1;
}
@@ -45,19 +45,19 @@ public static char Lookup(string button, string systemId)
public static string LookupAxis(string button, string systemId)
{
- var key = button
+ string key = button
.Replace("P1 ", "")
.Replace("P2 ", "")
.Replace("P3 ", "")
.Replace("P4 ", "")
.Replace("Key ", "");
- if (AxisSystemOverrides.TryGetValue(systemId, out var overridesForSystem) && overridesForSystem.TryGetValue(key, out var s))
+ if (AxisSystemOverrides.TryGetValue(systemId, out var overridesForSystem) && overridesForSystem.TryGetValue(key, out string s))
{
return s;
}
- if (BaseAxisLookupTable.TryGetValue(key, out var s1))
+ if (BaseAxisLookupTable.TryGetValue(key, out string s1))
{
return s1;
}
@@ -65,7 +65,7 @@ public static string LookupAxis(string button, string systemId)
return button;
}
- private static readonly Dictionary BaseMnemonicLookupTable = new Dictionary
+ private static readonly Dictionary BaseMnemonicLookupTable = new()
{
["Power"] = 'P',
["Reset"] = 'r',
@@ -177,7 +177,7 @@ public static string LookupAxis(string button, string systemId)
["F10"] = '0'
};
- private static readonly Dictionary> SystemOverrides = new Dictionary>
+ private static readonly Dictionary> SystemOverrides = new()
{
[VSystemID.Raw.NES] = new()
{
@@ -687,7 +687,7 @@ public static string LookupAxis(string button, string systemId)
},
};
- private static readonly Dictionary BaseAxisLookupTable = new Dictionary
+ private static readonly Dictionary BaseAxisLookupTable = new()
{
["Zapper X"] = "zapX",
["Zapper Y"] = "zapY",
@@ -707,7 +707,7 @@ public static string LookupAxis(string button, string systemId)
["Disk Index"] = "Disk",
};
- private static readonly Dictionary> AxisSystemOverrides = new Dictionary>
+ private static readonly Dictionary> AxisSystemOverrides = new()
{
[VSystemID.Raw.A78] = new()
{
diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs
index afb9e7dda0c..bcd2152002a 100644
--- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs
@@ -34,7 +34,7 @@ public override ulong Rerecords
public virtual bool StartsFromSavestate
{
// ReSharper disable SimplifyConditionalTernaryExpression
- get => Header.TryGetValue(HeaderKeys.StartsFromSavestate, out var s) ? bool.Parse(s) : false;
+ get => Header.TryGetValue(HeaderKeys.StartsFromSavestate, out string s) && bool.Parse(s);
// ReSharper restore SimplifyConditionalTernaryExpression
set
{
@@ -52,7 +52,7 @@ public virtual bool StartsFromSavestate
public bool StartsFromSaveRam
{
// ReSharper disable SimplifyConditionalTernaryExpression
- get => Header.TryGetValue(HeaderKeys.StartsFromSaveram, out var s) ? bool.Parse(s) : false;
+ get => Header.TryGetValue(HeaderKeys.StartsFromSaveram, out string s) && bool.Parse(s);
// ReSharper restore SimplifyConditionalTernaryExpression
set
{
@@ -180,9 +180,9 @@ public override string FirmwareHash
protected string CommentsString()
{
- var sb = new StringBuilder();
+ StringBuilder sb = new();
- foreach (var comment in Comments)
+ foreach (string comment in Comments)
{
sb.AppendLine(comment);
}
diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs
index 3f5d53e0d7b..0bd56671cd0 100644
--- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs
@@ -10,10 +10,7 @@ namespace BizHawk.Client.Common
{
public partial class Bk2Movie
{
- public void Save()
- {
- Write(Filename);
- }
+ public void Save() => Write(Filename);
public void SaveBackup()
{
@@ -22,7 +19,7 @@ public void SaveBackup()
return;
}
- var backupName = Filename;
+ string backupName = Filename;
backupName = backupName.Insert(Filename.LastIndexOf(".", StringComparison.Ordinal), $".{DateTime.Now:yyyy-MM-dd HH.mm.ss}");
backupName = Path.Combine(Session.BackupDirectory, Path.GetFileName(backupName));
@@ -40,7 +37,7 @@ protected virtual void Write(string fn, bool isBackup = false)
Header[HeaderKeys.EmulatorVersion] = VersionInfo.GetEmuVersion();
CreateDirectoryIfNotExists(fn);
- using var bs = new ZipStateSaver(fn, Session.Settings.MovieCompressionLevel);
+ using ZipStateSaver bs = new(fn, Session.Settings.MovieCompressionLevel);
AddLumps(bs, isBackup);
if (!isBackup)
@@ -69,17 +66,14 @@ private void SetCycleValues()
private static void CreateDirectoryIfNotExists(string fn)
{
- var file = new FileInfo(fn);
+ FileInfo file = new(fn);
if (file.Directory != null && !file.Directory.Exists)
{
Directory.CreateDirectory(file.Directory.ToString());
}
}
- protected virtual void AddLumps(ZipStateSaver bs, bool isBackup = false)
- {
- AddBk2Lumps(bs);
- }
+ protected virtual void AddLumps(ZipStateSaver bs, bool isBackup = false) => AddBk2Lumps(bs);
protected void AddBk2Lumps(ZipStateSaver bs)
{
@@ -160,7 +154,7 @@ private void LoadBk2Fields(ZipStateLoader bl)
bl.GetLump(BinaryStateLump.Framebuffer, false,
br =>
{
- var fb = br.ReadAllBytes();
+ byte[] fb = br.ReadAllBytes();
SavestateFramebuffer = new int[fb.Length / sizeof(int)];
Buffer.BlockCopy(fb, 0, SavestateFramebuffer, 0, fb.Length);
});
diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs
index 9b407f3d494..660b98124b4 100644
--- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs
@@ -23,7 +23,7 @@ public void WriteInputLog(TextWriter writer)
writer.WriteLine($"LogKey:{LogKey}");
}
- foreach (var record in Log)
+ foreach (string record in Log)
{
writer.WriteLine(record);
}
@@ -60,7 +60,7 @@ public virtual bool ExtractInputLog(TextReader reader, out string errorMessage)
}
else if (line.StartsWithOrdinal("Frame "))
{
- var strs = line.Split(' ');
+ string[] strs = line.Split(' ');
try
{
stateFrame = int.Parse(strs[1]);
@@ -82,7 +82,7 @@ public virtual bool ExtractInputLog(TextReader reader, out string errorMessage)
errorMessage = "Savestate Frame number failed to parse";
}
- var stateFramei = stateFrame ?? 0;
+ int stateFramei = stateFrame ?? 0;
if (stateFramei.StrictlyBoundedBy(0.RangeTo(Log.Count)))
{
@@ -113,8 +113,8 @@ public bool CheckTimeLines(TextReader reader, out string errorMessage)
{
// This function will compare the movie data to the savestate movie data to see if they match
errorMessage = "";
- var newLog = new List();
- var stateFrame = 0;
+ List newLog = new();
+ int stateFrame = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
@@ -124,7 +124,7 @@ public bool CheckTimeLines(TextReader reader, out string errorMessage)
}
else if (line.StartsWithOrdinal("Frame "))
{
- var strs = line.Split(' ');
+ string[] strs = line.Split(' ');
try
{
stateFrame = int.Parse(strs[1]);
@@ -154,7 +154,7 @@ public bool CheckTimeLines(TextReader reader, out string errorMessage)
return false;
}
- for (var i = 0; i < stateFrame; i++)
+ for (int i = 0; i < stateFrame; i++)
{
if (Log[i] != newLog[i])
{
@@ -166,7 +166,7 @@ public bool CheckTimeLines(TextReader reader, out string errorMessage)
if (stateFrame > newLog.Count) // stateFrame is greater than state input log, so movie finished mode
{
- if (Mode == MovieMode.Play || Mode == MovieMode.Finished)
+ if (Mode is MovieMode.Play or MovieMode.Finished)
{
Mode = MovieMode.Finished;
return true;
diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs
index 84aadc9e5d5..3a67eb6b4f5 100755
--- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs
@@ -13,10 +13,7 @@ public Bk2Movie(IMovieSession session, string filename) : base(filename)
Header[HeaderKeys.MovieVersion] = "BizHawk v2.0.0";
}
- public virtual void Attach(IEmulator emulator)
- {
- Emulator = emulator;
- }
+ public virtual void Attach(IEmulator emulator) => Emulator = emulator;
protected bool IsAttached() => Emulator != null;
@@ -52,7 +49,7 @@ public Bk2LogEntryGenerator LogGeneratorInstance(IController source)
public void CopyLog(IEnumerable log)
{
Log.Clear();
- foreach (var entry in log)
+ foreach (string entry in log)
{
Log.Add(entry);
}
diff --git a/src/BizHawk.Client.Common/movie/bk2/StringLogs.cs b/src/BizHawk.Client.Common/movie/bk2/StringLogs.cs
index 3a4cf026725..32c24643775 100644
--- a/src/BizHawk.Client.Common/movie/bk2/StringLogs.cs
+++ b/src/BizHawk.Client.Common/movie/bk2/StringLogs.cs
@@ -43,8 +43,8 @@ public static IStringLog MakeStringLog()
public static string ToInputLog(this IStringLog log)
{
- var sb = new StringBuilder();
- foreach (var record in log)
+ StringBuilder sb = new();
+ foreach (string record in log)
{
sb.AppendLine(record);
}
@@ -72,7 +72,7 @@ internal class ListStringLog : List, IStringLog
{
public IStringLog Clone()
{
- var ret = new ListStringLog();
+ ListStringLog ret = new();
ret.AddRange(this);
return ret;
}
@@ -89,7 +89,7 @@ public void Dispose() { }
internal class StreamStringLog : IStringLog
{
private readonly Stream _stream;
- private readonly List _offsets = new List();
+ private readonly List _offsets = new();
private readonly BinaryWriter _bw;
private readonly BinaryReader _br;
private readonly bool _mDisk;
@@ -99,7 +99,7 @@ public StreamStringLog(bool disk)
_mDisk = disk;
if (disk)
{
- var path = TempFileManager.GetTempFilename("movieOnDisk");
+ string path = TempFileManager.GetTempFilename("movieOnDisk");
_stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4 * 1024, FileOptions.DeleteOnClose);
}
else
@@ -114,7 +114,7 @@ public StreamStringLog(bool disk)
public IStringLog Clone()
{
- var ret = new StreamStringLog(_mDisk); // doesn't necessarily make sense to copy the mDisk value, they could be designated for different targets...
+ StreamStringLog ret = new(_mDisk); // doesn't necessarily make sense to copy the mDisk value, they could be designated for different targets...
for (int i = 0; i < Count; i++)
{
ret.Add(this[i]);
@@ -123,10 +123,7 @@ public IStringLog Clone()
return ret;
}
- public void Dispose()
- {
- _stream.Dispose();
- }
+ public void Dispose() => _stream.Dispose();
public int Count => _offsets.Count;
@@ -144,11 +141,9 @@ public void Add(string str)
_bw.Flush();
}
- public void RemoveAt(int index)
- {
+ public void RemoveAt(int index) =>
// no garbage collection in the disk file... oh well.
_offsets.RemoveAt(index);
- }
public string this[int index]
{
@@ -177,7 +172,7 @@ public void Insert(int index, string val)
public void InsertRange(int index, IEnumerable collection)
{
- foreach (var item in collection)
+ foreach (string item in collection)
{
Insert(index++, item);
}
@@ -185,7 +180,7 @@ public void InsertRange(int index, IEnumerable collection)
public void AddRange(IEnumerable collection)
{
- foreach (var item in collection)
+ foreach (string item in collection)
{
Add(item);
}
@@ -211,20 +206,14 @@ bool IEnumerator.MoveNext()
return true;
}
- void IEnumerator.Reset() { _index = -1; }
-
+ void IEnumerator.Reset() => _index = -1;
+
public void Dispose() { }
}
- IEnumerator IEnumerable.GetEnumerator()
- {
- return new Enumerator { Log = this };
- }
+ IEnumerator IEnumerable.GetEnumerator() => new Enumerator { Log = this };
- IEnumerator IEnumerable.GetEnumerator()
- {
- return new Enumerator { Log = this };
- }
+ IEnumerator IEnumerable.GetEnumerator() => new Enumerator { Log = this };
public void RemoveRange(int index, int count)
{
diff --git a/src/BizHawk.Client.Common/movie/import/BkmImport.cs b/src/BizHawk.Client.Common/movie/import/BkmImport.cs
index 76996cf838a..cfe00c842c4 100644
--- a/src/BizHawk.Client.Common/movie/import/BkmImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/BkmImport.cs
@@ -8,10 +8,10 @@ internal class BkmImport : MovieImporter
{
protected override void RunImport()
{
- var bkm = new BkmMovie { Filename = SourceFile.FullName };
+ BkmMovie bkm = new() { Filename = SourceFile.FullName };
bkm.Load();
- for (var i = 0; i < bkm.InputLogLength; i++)
+ for (int i = 0; i < bkm.InputLogLength; i++)
{
var input = bkm.GetInputState(i, Result.Movie.Emulator.ControllerDefinition, bkm.Header[HeaderKeys.Platform]);
Result.Movie.AppendFrame(input);
@@ -23,7 +23,7 @@ protected override void RunImport()
Result.Movie.SyncSettingsJson = bkm.SyncSettingsJson;
Result.Movie.Comments.Clear();
- foreach (var comment in bkm.Comments)
+ foreach (string comment in bkm.Comments)
{
Result.Movie.Comments.Add(comment);
}
diff --git a/src/BizHawk.Client.Common/movie/import/DsmImport.cs b/src/BizHawk.Client.Common/movie/import/DsmImport.cs
index d2831687dfd..90ba3353a51 100644
--- a/src/BizHawk.Client.Common/movie/import/DsmImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/DsmImport.cs
@@ -27,7 +27,7 @@ protected override void RunImport()
{
Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.NDS;
- var syncSettings = new NDS.NDSSyncSettings();
+ NDS.NDSSyncSettings syncSettings = new();
using var sr = SourceFile.OpenText();
string line;
@@ -44,7 +44,7 @@ protected override void RunImport()
}
else if (line.StartsWithOrdinal("rerecordCount"))
{
- Result.Movie.Rerecords = (ulong) (int.TryParse(ParseHeader(line, "rerecordCount"), out var rerecordCount) ? rerecordCount : default);
+ Result.Movie.Rerecords = (ulong) (int.TryParse(ParseHeader(line, "rerecordCount"), out int rerecordCount) ? rerecordCount : default);
}
else if (line.StartsWithOrdinal("firmNickname"))
{
@@ -108,7 +108,7 @@ private void ImportInputFrame(string line)
if (sections.Length > 1)
{
- var mnemonics = sections[1].Take(_buttons.Length).ToList();
+ System.Collections.Generic.List mnemonics = sections[1].Take(_buttons.Length).ToList();
controller["Right"] = mnemonics[0] != '.';
controller["Left"] = mnemonics[1] != '.';
@@ -125,8 +125,8 @@ private void ImportInputFrame(string line)
controller["Touch"] = sections[1].Substring(21, 1) != "0";
- var touchX = int.Parse(sections[1].Substring(13, 3));
- var touchY = int.Parse(sections[1].Substring(17, 3));
+ int touchX = int.Parse(sections[1].Substring(13, 3));
+ int touchY = int.Parse(sections[1].Substring(17, 3));
controller.AcceptNewAxes(new[]
{
diff --git a/src/BizHawk.Client.Common/movie/import/FcmImport.cs b/src/BizHawk.Client.Common/movie/import/FcmImport.cs
index 7e3946c1cf0..e5b99d406b0 100644
--- a/src/BizHawk.Client.Common/movie/import/FcmImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/FcmImport.cs
@@ -20,8 +20,8 @@ protected override void RunImport()
{
Result.Movie.HeaderEntries[HeaderKeys.Core] = CoreNames.NesHawk;
- using var r = new BinaryReader(SourceFile.Open(FileMode.Open, FileAccess.Read));
- var signature = new string(r.ReadChars(4));
+ using BinaryReader r = new(SourceFile.Open(FileMode.Open, FileAccess.Read));
+ string signature = new(r.ReadChars(4));
if (signature != "FCM\x1A")
{
Result.Errors.Add("This is not a valid .FCM file.");
@@ -30,9 +30,9 @@ protected override void RunImport()
Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.NES;
- var syncSettings = new NES.NESSyncSettings();
+ NES.NESSyncSettings syncSettings = new();
- var controllerSettings = new NESControlSettings
+ NESControlSettings controllerSettings = new()
{
NesLeftPort = nameof(ControllerNES),
NesRightPort = nameof(ControllerNES)
@@ -114,7 +114,7 @@ The savestate offset is . T
Result.Movie.Comments.Add($"{EmulationOrigin} FCEU {emuVersion}");
// 034 name of the ROM used - UTF8 encoded nul-terminated string.
- var gameBytes = new List();
+ List gameBytes = new();
while (r.PeekChar() != 0)
{
gameBytes.Add(r.ReadByte());
@@ -130,7 +130,7 @@ The savestate offset is . T
name and ends at the savestate offset. This string is displayed as "Author Info" in the Windows version of the
emulator.
*/
- var authorBytes = new List();
+ List authorBytes = new();
while (r.PeekChar() != 0)
{
authorBytes.Add(r.ReadByte());
diff --git a/src/BizHawk.Client.Common/movie/import/Fm2Import.cs b/src/BizHawk.Client.Common/movie/import/Fm2Import.cs
index 95a7d3d918e..b695f3856da 100644
--- a/src/BizHawk.Client.Common/movie/import/Fm2Import.cs
+++ b/src/BizHawk.Client.Common/movie/import/Fm2Import.cs
@@ -17,11 +17,11 @@ protected override void RunImport()
{
Result.Movie.HeaderEntries[HeaderKeys.Core] = CoreNames.NesHawk;
const string emulator = "FCEUX";
- var platform = VSystemID.Raw.NES; // TODO: FDS?
+ string platform = VSystemID.Raw.NES; // TODO: FDS?
- var syncSettings = new NES.NESSyncSettings();
+ NES.NESSyncSettings syncSettings = new();
- var controllerSettings = new NESControlSettings
+ NESControlSettings controllerSettings = new()
{
NesLeftPort = nameof(UnpluggedNES),
NesRightPort = nameof(UnpluggedNES)
@@ -46,7 +46,7 @@ protected override void RunImport()
}
else if (line.StartsWith("sub", StringComparison.OrdinalIgnoreCase))
{
- var subtitle = ImportTextSubtitle(line);
+ string subtitle = ImportTextSubtitle(line);
if (!string.IsNullOrEmpty(subtitle))
{
@@ -97,7 +97,7 @@ protected override void RunImport()
}
else if (line.StartsWith("rerecordcount", StringComparison.OrdinalIgnoreCase))
{
- Result.Movie.Rerecords = (ulong) (int.TryParse(ParseHeader(line, "rerecordCount"), out var rerecordCount) ? rerecordCount : default);
+ Result.Movie.Rerecords = (ulong) (int.TryParse(ParseHeader(line, "rerecordCount"), out int rerecordCount) ? rerecordCount : default);
}
else if (line.StartsWith("guid", StringComparison.OrdinalIgnoreCase))
{
diff --git a/src/BizHawk.Client.Common/movie/import/FmvImport.cs b/src/BizHawk.Client.Common/movie/import/FmvImport.cs
index 1b86bf00d24..9eeff7d87d7 100644
--- a/src/BizHawk.Client.Common/movie/import/FmvImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/FmvImport.cs
@@ -15,9 +15,9 @@ internal class FmvImport : MovieImporter
protected override void RunImport()
{
using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read);
- using var r = new BinaryReader(fs);
+ using BinaryReader r = new(fs);
// 000 4-byte signature: 46 4D 56 1A "FMV\x1A"
- var signature = new string(r.ReadChars(4));
+ string signature = new(r.ReadChars(4));
if (signature != "FMV\x1A")
{
Result.Errors.Add("This is not a valid .FMV file.");
@@ -35,7 +35,7 @@ protected override void RunImport()
}
Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.NES;
- var syncSettings = new NES.NESSyncSettings();
+ NES.NESSyncSettings syncSettings = new();
// other bits: unknown, set to 0
// 005 1-byte flags:
@@ -89,7 +89,7 @@ the file.
Result.Warnings.Add("No input recorded.");
}
- var controllerSettings = new NESControlSettings
+ NESControlSettings controllerSettings = new()
{
NesLeftPort = controller1 ? nameof(ControllerNES) : nameof(UnpluggedNES),
NesRightPort = controller2 ? nameof(ControllerNES) : nameof(UnpluggedNES)
diff --git a/src/BizHawk.Client.Common/movie/import/GmvImport.cs b/src/BizHawk.Client.Common/movie/import/GmvImport.cs
index d05504675cc..dd31d3d94a5 100644
--- a/src/BizHawk.Client.Common/movie/import/GmvImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/GmvImport.cs
@@ -14,10 +14,10 @@ internal class GmvImport : MovieImporter
protected override void RunImport()
{
using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read);
- using var r = new BinaryReader(fs);
+ using BinaryReader r = new(fs);
// 000 16-byte signature and format version: "Gens Movie TEST9"
- string signature = new string(r.ReadChars(15));
+ string signature = new(r.ReadChars(15));
if (signature != "Gens Movie TEST")
{
Result.Errors.Add("This is not a valid .GMV file.");
@@ -27,7 +27,7 @@ protected override void RunImport()
Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.GEN;
// 00F ASCII-encoded GMV file format version. The most recent is 'A'. (?)
- string version = new string(r.ReadChars(1));
+ string version = new(r.ReadChars(1));
Result.Movie.Comments.Add($"{MovieOrigin} .GMV version {version}");
Result.Movie.Comments.Add($"{EmulationOrigin} Gens");
@@ -63,7 +63,7 @@ protected override void RunImport()
// bit 5: if "1", movie is 3-player movie; if "0", movie is 2-player movie
bool threePlayers = ((flags >> 5) & 0x1) != 0;
- LibGPGX.InputData input = new LibGPGX.InputData();
+ LibGPGX.InputData input = new();
input.dev[0] = player1Config == '6'
? LibGPGX.INPUT_DEVICE.DEVICE_PAD6B
: LibGPGX.INPUT_DEVICE.DEVICE_PAD3B;
@@ -72,7 +72,7 @@ protected override void RunImport()
? LibGPGX.INPUT_DEVICE.DEVICE_PAD6B
: LibGPGX.INPUT_DEVICE.DEVICE_PAD3B;
- var ss = new GPGX.GPGXSyncSettings
+ GPGX.GPGXSyncSettings ss = new()
{
UseSixButton = player1Config == '6' || player2Config == '6',
ControlTypeLeft = GPGX.ControlType.Normal,
@@ -88,7 +88,7 @@ protected override void RunImport()
: LibGPGX.INPUT_DEVICE.DEVICE_PAD3B;
}
- var controlConverter = new GPGXControlConverter(input, false);
+ GPGXControlConverter controlConverter = new(input, false);
SimpleController controller = new(controlConverter.ControllerDef);
diff --git a/src/BizHawk.Client.Common/movie/import/IMovieImport.cs b/src/BizHawk.Client.Common/movie/import/IMovieImport.cs
index b3a5e8576b4..fe78e180cea 100644
--- a/src/BizHawk.Client.Common/movie/import/IMovieImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/IMovieImport.cs
@@ -40,7 +40,7 @@ public ImportResult Import(
return Result;
}
- var newFileName = $"{SourceFile.FullName}.{Bk2Movie.Extension}";
+ string newFileName = $"{SourceFile.FullName}.{Bk2Movie.Extension}";
Result.Movie = session.Get(newFileName);
RunImport();
@@ -87,15 +87,15 @@ private string PromptForRom(MatchesMovieHash matchesMovieHash)
if (!_dialogParent.ModalMessageBox2(messageBoxText, "ROM required to populate hash", useOKCancel: true))
return null;
- var result = _dialogParent.ShowFileOpenDialog(
+ string result = _dialogParent.ShowFileOpenDialog(
filter: RomLoader.RomFilter,
initDir: Config.PathEntries.RomAbsolutePath(Result.Movie.SystemID));
if (result is null)
return null; // skip hash migration when the dialog was canceled
- using var rom = new HawkFile(result);
+ using HawkFile rom = new(result);
if (rom.IsArchive) rom.BindFirst();
- var romData = (ReadOnlySpan) rom.ReadAllBytes();
+ ReadOnlySpan romData = (ReadOnlySpan) rom.ReadAllBytes();
if (romData.Length % 1024 == 512)
romData = romData.Slice(512, romData.Length - 512);
if (matchesMovieHash(romData))
@@ -161,7 +161,7 @@ public class ImportResult
public static ImportResult Error(string errorMsg)
{
- var result = new ImportResult();
+ ImportResult result = new();
result.Errors.Add(errorMsg);
return result;
}
diff --git a/src/BizHawk.Client.Common/movie/import/LsmvImport.cs b/src/BizHawk.Client.Common/movie/import/LsmvImport.cs
index f05c6099bc5..1e1772ab40b 100644
--- a/src/BizHawk.Client.Common/movie/import/LsmvImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/LsmvImport.cs
@@ -1,5 +1,4 @@
using System;
-using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
@@ -28,7 +27,7 @@ protected override void RunImport()
Result.Movie.HeaderEntries[HeaderKeys.Core] = CoreNames.SubBsnes115;
// .LSMV movies are .zip files containing data files.
- using var fs = new FileStream(SourceFile.FullName, FileMode.Open, FileAccess.Read);
+ using FileStream fs = new(SourceFile.FullName, FileMode.Open, FileAccess.Read);
{
byte[] data = new byte[4];
fs.Read(data, 0, 4);
@@ -40,9 +39,9 @@ protected override void RunImport()
fs.Position = 0;
}
- using var zip = new ZipArchive(fs, ZipArchiveMode.Read, true);
+ using ZipArchive zip = new(fs, ZipArchiveMode.Read, true);
- var ss = new BsnesCore.SnesSyncSettings();
+ BsnesCore.SnesSyncSettings ss = new();
string platform = VSystemID.Raw.SNES;
@@ -92,7 +91,7 @@ protected override void RunImport()
string authors = Encoding.UTF8.GetString(stream.ReadAllBytes());
string authorList = "";
string authorLast = "";
- using (var reader = new StringReader(authors))
+ using (StringReader reader = new(authors))
{
// Each author is on a different line.
while (reader.ReadLine() is string line)
@@ -156,7 +155,7 @@ protected override void RunImport()
break;
}
- bool pal = gametype == "snes_pal" || gametype == "sgb_pal";
+ bool pal = gametype is "snes_pal" or "sgb_pal";
Result.Movie.HeaderEntries[HeaderKeys.Pal] = pal.ToString();
}
else if (item.FullName == "input")
@@ -167,7 +166,7 @@ protected override void RunImport()
// Insert an empty frame in lsmv snes movies
// see https://github.com/TASEmulators/BizHawk/issues/721
Result.Movie.AppendFrame(EmptyLmsvFrame());
- using (var reader = new StringReader(input))
+ using (StringReader reader = new(input))
{
while(reader.ReadLine() is string line)
{
@@ -229,15 +228,13 @@ protected override void RunImport()
{
using var stream = item.Open();
string subtitles = Encoding.UTF8.GetString(stream.ReadAllBytes());
- using (var reader = new StringReader(subtitles))
+ using StringReader reader = new(subtitles);
+ while (reader.ReadLine() is string line)
{
- while (reader.ReadLine() is string line)
+ string subtitle = ImportTextSubtitle(line);
+ if (!string.IsNullOrEmpty(subtitle))
{
- var subtitle = ImportTextSubtitle(line);
- if (!string.IsNullOrEmpty(subtitle))
- {
- Result.Movie.Subtitles.AddFromString(subtitle);
- }
+ Result.Movie.Subtitles.AddFromString(subtitle);
}
}
}
@@ -269,7 +266,7 @@ private IController EmptyLmsvFrame()
{
SimpleController emptyController = new(_controllers.Definition);
- foreach (var button in emptyController.Definition.BoolButtons)
+ foreach (string button in emptyController.Definition.BoolButtons)
{
emptyController[button] = false;
}
@@ -318,7 +315,7 @@ private void ImportTextFrame(string line)
{
if (player > _playerCount) break;
- IReadOnlyList buttons = controllers.Definition.ControlsOrdered[player];
+ var buttons = controllers.Definition.ControlsOrdered[player];
if (buttons[0].EndsWithOrdinal("Up")) // hack to identify gamepad / multitap which have a different button order in bizhawk compared to lsnes
{
buttons = new[] { "B", "Y", "Select", "Start", "Up", "Down", "Left", "Right", "A", "X", "L", "R" }
diff --git a/src/BizHawk.Client.Common/movie/import/Mc2Import.cs b/src/BizHawk.Client.Common/movie/import/Mc2Import.cs
index edf9fc3f586..b1843f81016 100644
--- a/src/BizHawk.Client.Common/movie/import/Mc2Import.cs
+++ b/src/BizHawk.Client.Common/movie/import/Mc2Import.cs
@@ -13,7 +13,7 @@ internal class Mc2Import : MovieImporter
protected override void RunImport()
{
- var ss = new PCEngine.PCESyncSettings
+ PCEngine.PCESyncSettings ss = new()
{
Port1 = PceControllerType.Unplugged,
Port2 = PceControllerType.Unplugged,
@@ -46,7 +46,7 @@ protected override void RunImport()
}
else if (line.StartsWith("ports", StringComparison.OrdinalIgnoreCase))
{
- var portNumStr = ParseHeader(line, "ports");
+ string portNumStr = ParseHeader(line, "ports");
if (int.TryParse(portNumStr, out int ports))
{
// Ugh
@@ -145,7 +145,7 @@ protected override void RunImport()
// Import a frame from a text-based format.
private void ImportTextFrame(string line)
{
- var buttons = new[] { "Up", "Down", "Left", "Right", "B1", "B2", "Run", "Select" };
+ string[] buttons = new[] { "Up", "Down", "Left", "Right", "B1", "B2", "Run", "Select" };
SimpleController controllers = new(_deck.Definition);
diff --git a/src/BizHawk.Client.Common/movie/import/MmvImport.cs b/src/BizHawk.Client.Common/movie/import/MmvImport.cs
index 7e05ebb6980..48c11d03536 100644
--- a/src/BizHawk.Client.Common/movie/import/MmvImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/MmvImport.cs
@@ -13,10 +13,10 @@ internal class MmvImport : MovieImporter
protected override void RunImport()
{
using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read);
- using var r = new BinaryReader(fs);
+ using BinaryReader r = new(fs);
// 0000: 4-byte signature: "MMV\0"
- string signature = new string(r.ReadChars(4));
+ string signature = new(r.ReadChars(4));
if (signature != "MMV\0")
{
Result.Errors.Add("This is not a valid .MMV file.");
@@ -94,8 +94,8 @@ protected override void RunImport()
byte[] md5 = r.ReadBytes(16);
Result.Movie.HeaderEntries[HeaderKeys.Md5] = md5.BytesToHexString().ToLowerInvariant();
- var ss = new SMS.SmsSyncSettings();
- var cd = new SMSControllerDeck(ss.Port1, ss.Port2, isGameGear, ss.UseKeyboard);
+ SMS.SmsSyncSettings ss = new();
+ SMSControllerDeck cd = new(ss.Port1, ss.Port2, isGameGear, ss.UseKeyboard);
SimpleController controllers = new(cd.Definition);
/*
diff --git a/src/BizHawk.Client.Common/movie/import/MovieImport.cs b/src/BizHawk.Client.Common/movie/import/MovieImport.cs
index 72310e478e0..eddea48bda1 100644
--- a/src/BizHawk.Client.Common/movie/import/MovieImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/MovieImport.cs
@@ -23,7 +23,7 @@ public static bool IsValidMovieExtension(string extension)
.Any(e => string.Equals(extension, e.Extension, StringComparison.OrdinalIgnoreCase));
}
- public static readonly FilesystemFilterSet AvailableImporters = new FilesystemFilterSet(
+ public static readonly FilesystemFilterSet AvailableImporters = new(
Importers.Values.OrderBy(attr => attr.Emulator)
.Select(attr => new FilesystemFilter(attr.Emulator, new[] { attr.Extension.Substring(1) })) // substring removes initial '.'
.ToArray())
@@ -53,9 +53,6 @@ public static ImportResult ImportFile(
: ImportResult.Error($"No importer found for file type {ext}");
}
- private static Type ImporterForExtension(string ext)
- {
- return Importers.First(i => string.Equals(i.Value.Extension, ext, StringComparison.OrdinalIgnoreCase)).Key;
- }
+ private static Type ImporterForExtension(string ext) => Importers.First(i => string.Equals(i.Value.Extension, ext, StringComparison.OrdinalIgnoreCase)).Key;
}
}
diff --git a/src/BizHawk.Client.Common/movie/import/PjmImport.cs b/src/BizHawk.Client.Common/movie/import/PjmImport.cs
index cacff790eaa..f5f962c1728 100644
--- a/src/BizHawk.Client.Common/movie/import/PjmImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/PjmImport.cs
@@ -14,7 +14,7 @@ protected override void RunImport()
Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.PSX;
using var fs = SourceFile.OpenRead();
- using var br = new BinaryReader(fs);
+ using BinaryReader br = new(fs);
var info = ParseHeader(Result.Movie, "PJM ", br);
fs.Seek(info.ControllerDataOffset, SeekOrigin.Begin);
@@ -31,9 +31,9 @@ protected override void RunImport()
protected MiscHeaderInfo ParseHeader(IMovie movie, string expectedMagic, BinaryReader br)
{
- var info = new MiscHeaderInfo();
+ MiscHeaderInfo info = new();
- string magic = new string(br.ReadChars(4));
+ string magic = new(br.ReadChars(4));
if (magic != expectedMagic)
{
Result.Errors.Add($"Not a {expectedMagic}file: invalid magic number in file header.");
@@ -125,7 +125,7 @@ protected MiscHeaderInfo ParseHeader(IMovie movie, string expectedMagic, BinaryR
return info;
}
- var syncSettings = new Octoshock.SyncSettings
+ Octoshock.SyncSettings syncSettings = new()
{
FIOConfig =
{
@@ -172,7 +172,7 @@ protected MiscHeaderInfo ParseHeader(IMovie movie, string expectedMagic, BinaryR
protected void ParseBinaryInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo info)
{
- var settings = new Octoshock.SyncSettings();
+ Octoshock.SyncSettings settings = new();
settings.FIOConfig.Devices8 = new[]
{
info.Player1Type,
@@ -282,7 +282,7 @@ protected void ParseBinaryInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo
protected void ParseTextInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo info)
{
- Octoshock.SyncSettings settings = new Octoshock.SyncSettings();
+ Octoshock.SyncSettings settings = new();
settings.FIOConfig.Devices8 = new[]
{
info.Player1Type,
@@ -307,7 +307,7 @@ protected void ParseTextInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo i
for (int frame = 0; frame < info.FrameCount; ++frame)
{
- var mnemonicStr = new string(br.ReadChars(strCount));
+ string mnemonicStr = new(br.ReadChars(strCount));
// Junk whitespace at the end of a file
if (string.IsNullOrWhiteSpace(mnemonicStr))
@@ -321,10 +321,10 @@ protected void ParseTextInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo i
Result.Errors.Add("Unable to parse text input, unknown configuration");
}
- var split = mnemonicStr.Replace("\r\n", "").Split('|');
- var player1Str = split[0];
- var player2Str = split[1];
- var controlStr = split[2];
+ string[] split = mnemonicStr.Replace("\r\n", "").Split('|');
+ string player1Str = split[0];
+ string player2Str = split[1];
+ string controlStr = split[2];
if (info.Player1Type != OctoshockDll.ePeripheralType.None)
{
// As L3 and R3 don't exist on a standard gamepad, handle them separately later. Unfortunately
diff --git a/src/BizHawk.Client.Common/movie/import/PxmImport.cs b/src/BizHawk.Client.Common/movie/import/PxmImport.cs
index c2200d7cc6b..3e1b0c27265 100644
--- a/src/BizHawk.Client.Common/movie/import/PxmImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/PxmImport.cs
@@ -20,7 +20,7 @@ protected override void RunImport()
movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.PSX;
using var fs = SourceFile.OpenRead();
- using var br = new BinaryReader(fs);
+ using BinaryReader br = new(fs);
var info = ParseHeader(movie, "PXM ", br);
fs.Seek(info.ControllerDataOffset, SeekOrigin.Begin);
diff --git a/src/BizHawk.Client.Common/movie/import/SmvImport.cs b/src/BizHawk.Client.Common/movie/import/SmvImport.cs
index b6889eb760e..2305ab262a0 100644
--- a/src/BizHawk.Client.Common/movie/import/SmvImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/SmvImport.cs
@@ -19,10 +19,10 @@ protected override void RunImport()
Result.Movie.HeaderEntries[HeaderKeys.Core] = CoreNames.Snes9X;
using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read);
- using var r = new BinaryReader(fs);
+ using BinaryReader r = new(fs);
// 000 4-byte signature: 53 4D 56 1A "SMV\x1A"
- string signature = new string(r.ReadChars(4));
+ string signature = new(r.ReadChars(4));
if (signature != "SMV\x1A")
{
Result.Errors.Add("This is not a valid .SMV file.");
@@ -33,7 +33,7 @@ protected override void RunImport()
// 004 4-byte little-endian unsigned int: version number
uint versionNumber = r.ReadUInt32();
- var version = versionNumber switch
+ string version = versionNumber switch
{
1 => "1.43",
4 => "1.51",
@@ -74,7 +74,7 @@ recording time in Unix epoch format
}
int highestControllerIndex = 1 + Array.LastIndexOf(controllersUsed, true);
- var ss = new Snes9x.SyncSettings();
+ Snes9x.SyncSettings ss = new();
switch (highestControllerIndex)
{
@@ -190,7 +190,7 @@ is used (and MOVIE_SYNC_DATA_EXISTS is set), 0 bytes otherwise.
Result.Movie.HeaderEntries[HeaderKeys.GameName] = gameName;
}
- var _controllers = new Snes9xControllers(ss);
+ Snes9xControllers _controllers = new(ss);
Result.Movie.LogKey = new Bk2LogEntryGenerator("SNES", new Bk2Controller(_controllers.ControllerDefinition)).GenerateLogKey();
SimpleController controllers = new(_controllers.ControllerDefinition);
@@ -261,7 +261,7 @@ is being recorded.
{
for (int i = 0; i < 2; i++)
{
- var peripheral = "";
+ string peripheral = "";
switch (controllerTypes[i])
{
case 0: // NONE
diff --git a/src/BizHawk.Client.Common/movie/import/VbmImport.cs b/src/BizHawk.Client.Common/movie/import/VbmImport.cs
index 3226e06a3b9..93f1a541c3a 100644
--- a/src/BizHawk.Client.Common/movie/import/VbmImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/VbmImport.cs
@@ -16,11 +16,11 @@ internal class VbmImport : MovieImporter
protected override void RunImport()
{
using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read);
- using var r = new BinaryReader(fs);
+ using BinaryReader r = new(fs);
bool is_GBC = false;
// 000 4-byte signature: 56 42 4D 1A "VBM\x1A"
- string signature = new string(r.ReadChars(4));
+ string signature = new(r.ReadChars(4));
if (signature != "VBM\x1A")
{
Result.Errors.Add("This is not a valid .VBM file.");
@@ -200,7 +200,7 @@ recording time in Unix epoch format
Result.Movie.Comments.Add(movieDescription);
r.BaseStream.Position = firstFrameOffset;
- SimpleController controllers = isGBA
+ var controllers = isGBA
? GbaController()
: GbController();
diff --git a/src/BizHawk.Client.Common/movie/import/YmvImport.cs b/src/BizHawk.Client.Common/movie/import/YmvImport.cs
index 20c1b39b899..617516e60f9 100644
--- a/src/BizHawk.Client.Common/movie/import/YmvImport.cs
+++ b/src/BizHawk.Client.Common/movie/import/YmvImport.cs
@@ -13,7 +13,7 @@ internal class YmvImport : MovieImporter
protected override void RunImport()
{
Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.SAT;
- var ss = new Emulation.Cores.Waterbox.NymaCore.NymaSyncSettings
+ Emulation.Cores.Waterbox.NymaCore.NymaSyncSettings ss = new()
{
PortDevices =
{
@@ -109,7 +109,7 @@ private void ImportTextFrame(string line)
}.MakeImmutable());
// Split up the sections of the frame.
- var sections = line.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
+ string[] sections = line.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
if (sections.Length != 2)
{
Result.Errors.Add("Unsupported input configuration");
diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs
index 6734a7b62e8..e7c9e198135 100644
--- a/src/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs
+++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs
@@ -14,7 +14,7 @@ public BkmControllerAdapter(ControllerDefinition definition, string systemId)
{
// We do need to map the definition name to the legacy
// controller names that were used back in the bkm days
- var name = systemId switch
+ string name = systemId switch
{
"Lynx" => "Lynx Controller",
"SNES" => "SNES Controller",
@@ -39,15 +39,9 @@ public BkmControllerAdapter(ControllerDefinition definition, string systemId)
public ControllerDefinition Definition { get; set; }
- public bool IsPressed(string button)
- {
- return _myBoolButtons[button];
- }
+ public bool IsPressed(string button) => _myBoolButtons[button];
- public int AxisValue(string name)
- {
- return _myAxisControls[name];
- }
+ public int AxisValue(string name) => _myAxisControls[name];
public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => throw new NotImplementedException(); // no idea --yoshi
@@ -104,7 +98,7 @@ public void SetControllersAsMnemonic(string mnemonic)
}
}
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
@@ -164,7 +158,7 @@ public void SetControllersAsMnemonic(string mnemonic)
Force("Power", mnemonic[1] != '.');
}
- if (ControlType == "SMS Controller" || ControlType == "TI83 Controller" || ControlType == "ColecoVision Basic Controller")
+ if (ControlType is "SMS Controller" or "TI83 Controller" or "ColecoVision Basic Controller")
{
start = 1;
}
@@ -176,8 +170,8 @@ public void SetControllersAsMnemonic(string mnemonic)
return;
}
- Force("Reset", mnemonic[1] != '.' && mnemonic[1] != '0');
- Force("Select", mnemonic[2] != '.' && mnemonic[2] != '0');
+ Force("Reset", mnemonic[1] is not '.' and not '0');
+ Force("Select", mnemonic[2] is not '.' and not '0');
start = 4;
}
@@ -191,7 +185,7 @@ public void SetControllersAsMnemonic(string mnemonic)
}
string prefix = "";
- if (ControlType != "Gameboy Controller" && ControlType != "TI83 Controller")
+ if (ControlType is not "Gameboy Controller" and not "TI83 Controller")
{
prefix = $"P{player} ";
}
@@ -206,33 +200,27 @@ public void SetControllersAsMnemonic(string mnemonic)
{
int srcIndex = BkmMnemonicConstants.Players[ControlType] * (BkmMnemonicConstants.Buttons[ControlType].Count + 1);
int ctr = start;
- foreach (var command in BkmMnemonicConstants.Commands[ControlType].Keys)
+ foreach (string command in BkmMnemonicConstants.Commands[ControlType].Keys)
{
Force(command, c[srcIndex + ctr++]);
}
}
}
- private readonly WorkingDictionary _myBoolButtons = new WorkingDictionary();
- private readonly WorkingDictionary _myAxisControls = new WorkingDictionary();
+ private readonly WorkingDictionary _myBoolButtons = new();
+ private readonly WorkingDictionary _myAxisControls = new();
private bool IsGenesis6Button() => Definition.BoolButtons.Contains("P1 X");
- private void Force(string button, bool state)
- {
- _myBoolButtons[button] = state;
- }
+ private void Force(string button, bool state) => _myBoolButtons[button] = state;
- private void Force(string name, int state)
- {
- _myAxisControls[name] = state;
- }
+ private void Force(string name, int state) => _myAxisControls[name] = state;
private string ControlType => Definition.Name;
private void SetGBAControllersAsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
if (mnemonic.Length < 2)
{
@@ -253,7 +241,7 @@ private void SetGBAControllersAsMnemonic(string mnemonic)
private void SetGenesis6ControllersAsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
if (mnemonic.Length < 2)
@@ -265,7 +253,7 @@ private void SetGenesis6ControllersAsMnemonic(string mnemonic)
{
Force("Power", true);
}
- else if (mnemonic[1] != '.' && mnemonic[1] != '0')
+ else if (mnemonic[1] is not '.' and not '0')
{
Force("Reset", true);
}
@@ -294,7 +282,7 @@ private void SetGenesis6ControllersAsMnemonic(string mnemonic)
private void SetGenesis3ControllersAsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
if (mnemonic.Length < 2)
@@ -306,7 +294,7 @@ private void SetGenesis3ControllersAsMnemonic(string mnemonic)
{
Force("Power", true);
}
- else if (mnemonic[1] != '.' && mnemonic[1] != '0')
+ else if (mnemonic[1] is not '.' and not '0')
{
Force("Reset", true);
}
@@ -335,7 +323,7 @@ private void SetGenesis3ControllersAsMnemonic(string mnemonic)
private void SetSNESControllersAsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
if (mnemonic.Length < 2)
@@ -347,7 +335,7 @@ private void SetSNESControllersAsMnemonic(string mnemonic)
{
Force("Power", true);
}
- else if (mnemonic[1] != '.' && mnemonic[1] != '0')
+ else if (mnemonic[1] is not '.' and not '0')
{
Force("Reset", true);
}
@@ -362,7 +350,7 @@ private void SetSNESControllersAsMnemonic(string mnemonic)
}
int start = 3;
- foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys)
+ foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys)
{
Force($"P{player} {button}", c[srcIndex + start++]);
}
@@ -371,7 +359,7 @@ private void SetSNESControllersAsMnemonic(string mnemonic)
private void SetLynxControllersAsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
if (mnemonic.Length < 2)
@@ -394,7 +382,7 @@ private void SetLynxControllersAsMnemonic(string mnemonic)
}
int start = 3;
- foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys)
+ foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys)
{
Force(button, c[srcIndex + start++]);
}
@@ -403,7 +391,7 @@ private void SetLynxControllersAsMnemonic(string mnemonic)
private void SetN64ControllersAsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
if (mnemonic.Length < 2)
@@ -415,7 +403,7 @@ private void SetN64ControllersAsMnemonic(string mnemonic)
{
Force("Power", true);
}
- else if (mnemonic[1] != '.' && mnemonic[1] != '0')
+ else if (mnemonic[1] is not '.' and not '0')
{
Force("Reset", true);
}
@@ -445,7 +433,7 @@ private void SetN64ControllersAsMnemonic(string mnemonic)
private void SetSaturnControllersAsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
if (mnemonic.Length < 2)
@@ -457,7 +445,7 @@ private void SetSaturnControllersAsMnemonic(string mnemonic)
{
Force("Power", true);
}
- else if (mnemonic[1] != '.' && mnemonic[1] != '0')
+ else if (mnemonic[1] is not '.' and not '0')
{
Force("Reset", true);
}
@@ -481,7 +469,7 @@ private void SetSaturnControllersAsMnemonic(string mnemonic)
private void SetAtari7800AsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
if (mnemonic.Length < 5)
@@ -527,7 +515,7 @@ private void SetAtari7800AsMnemonic(string mnemonic)
private void SetDualGameBoyControllerAsMnemonic(string mnemonic)
{
- var checker = new MnemonicChecker(mnemonic);
+ MnemonicChecker checker = new(mnemonic);
_myBoolButtons.Clear();
for (int i = 0; i < BkmMnemonicConstants.DgbMnemonic.Length; i++)
{
@@ -541,7 +529,7 @@ private void SetDualGameBoyControllerAsMnemonic(string mnemonic)
private void SetWonderSwanControllerAsMnemonic(string mnemonic)
{
- var checker = new MnemonicChecker(mnemonic);
+ MnemonicChecker checker = new(mnemonic);
_myBoolButtons.Clear();
for (int i = 0; i < BkmMnemonicConstants.WsMnemonic.Length; i++)
{
@@ -555,7 +543,7 @@ private void SetWonderSwanControllerAsMnemonic(string mnemonic)
private void SetC64ControllersAsMnemonic(string mnemonic)
{
- var c = new MnemonicChecker(mnemonic);
+ MnemonicChecker c = new(mnemonic);
_myBoolButtons.Clear();
for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++)
@@ -568,7 +556,7 @@ private void SetC64ControllersAsMnemonic(string mnemonic)
}
int start = 1;
- foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys)
+ foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys)
{
Force($"P{player} {button}", c[srcIndex + start++]);
}
diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs
index db21ab74055..fcb20439364 100644
--- a/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs
+++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs
@@ -19,7 +19,7 @@ public BkmHeader()
public string SavestateBinaryBase64Blob
{
- get => TryGetValue(HeaderKeys.SavestateBinaryBase64Blob, out var s) ? s : null;
+ get => TryGetValue(HeaderKeys.SavestateBinaryBase64Blob, out string s) ? s : null;
set
{
if (value == null)
@@ -35,7 +35,7 @@ public string SavestateBinaryBase64Blob
public new string this[string key]
{
- get => TryGetValue(key, out var s) ? s : string.Empty;
+ get => TryGetValue(key, out string s) ? s : string.Empty;
set => base[key] = value;
}
@@ -50,7 +50,7 @@ public bool ParseLineFromFile(string line)
{
if (!string.IsNullOrWhiteSpace(line))
{
- var splitLine = line.Split(new[] { ' ' }, 2);
+ string[] splitLine = line.Split(new[] { ' ' }, 2);
if (HeaderKeys.Contains(splitLine[0]) && !ContainsKey(splitLine[0]))
{
diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs
index 13a56785f1b..6efbde21168 100644
--- a/src/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs
+++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs
@@ -4,7 +4,7 @@ namespace BizHawk.Client.Common
{
internal static class BkmMnemonicConstants
{
- public static readonly Dictionary> Buttons = new Dictionary>
+ public static readonly Dictionary> Buttons = new()
{
["Gameboy Controller"] = new Dictionary
{
@@ -95,12 +95,12 @@ internal static class BkmMnemonicConstants
}
};
- public static readonly Dictionary> Analogs = new Dictionary>
+ public static readonly Dictionary> Analogs = new()
{
["Nintendo 64 Controller"] = new Dictionary { ["X Axis"] = "X" , ["Y Axis"] = "Y" }
};
- public static readonly Dictionary> Commands = new Dictionary>
+ public static readonly Dictionary> Commands = new()
{
["Atari 2600 Basic Controller"] = new Dictionary { ["Reset"] = "r", ["Select"] = "s" },
["Atari 7800 ProLine Joystick Controller"] = new Dictionary { ["Reset"] = "r", ["Select"] = "s" },
@@ -118,7 +118,7 @@ internal static class BkmMnemonicConstants
["GPGX 3-Button Controller"] = new Dictionary { ["Power"] = "P", ["Reset"] = "r" }
};
- public static readonly Dictionary Players = new Dictionary
+ public static readonly Dictionary Players = new()
{
["Gameboy Controller"] = 1,
["GBA Controller"] = 1,
diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs
index b70c152c265..f59bd08e534 100644
--- a/src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs
+++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs
@@ -9,7 +9,7 @@ namespace BizHawk.Client.Common
{
internal class BkmMovie
{
- private readonly List _log = new List();
+ private readonly List _log = new();
public BkmHeader Header { get; } = new BkmHeader();
public string Filename { get; set; } = "";
public bool Loaded { get; private set; }
@@ -19,7 +19,7 @@ public BkmControllerAdapter GetInputState(int frame, ControllerDefinition defini
{
if (frame < InputLogLength && frame >= 0)
{
- var adapter = new BkmControllerAdapter(definition, sytemId);
+ BkmControllerAdapter adapter = new(definition, sytemId);
adapter.SetControllersAsMnemonic(_log[frame]);
return adapter;
}
@@ -41,7 +41,7 @@ public string SyncSettingsJson
public bool Load()
{
- var file = new FileInfo(Filename);
+ FileInfo file = new(Filename);
if (file.Exists == false)
{
diff --git a/src/BizHawk.Client.Common/movie/interfaces/IMovie.cs b/src/BizHawk.Client.Common/movie/interfaces/IMovie.cs
index 3ccefb589be..68f71345338 100644
--- a/src/BizHawk.Client.Common/movie/interfaces/IMovie.cs
+++ b/src/BizHawk.Client.Common/movie/interfaces/IMovie.cs
@@ -210,8 +210,8 @@ public static FilesystemFilterSet GetFSFilterSet(this IMovie/*?*/ movie)
public static bool IsPlaying(this IMovie movie) => movie?.Mode == MovieMode.Play;
public static bool IsRecording(this IMovie movie) => movie?.Mode == MovieMode.Record;
public static bool IsFinished(this IMovie movie) => movie?.Mode == MovieMode.Finished;
- public static bool IsPlayingOrFinished(this IMovie movie) => movie?.Mode == MovieMode.Play || movie?.Mode == MovieMode.Finished;
- public static bool IsPlayingOrRecording(this IMovie movie) => movie?.Mode == MovieMode.Play || movie?.Mode == MovieMode.Record;
+ public static bool IsPlayingOrFinished(this IMovie movie) => movie?.Mode is MovieMode.Play or MovieMode.Finished;
+ public static bool IsPlayingOrRecording(this IMovie movie) => movie?.Mode is MovieMode.Play or MovieMode.Record;
///
/// Emulation is currently right after the movie's last input frame,
/// but no further frames have been emulated.
diff --git a/src/BizHawk.Client.Common/movie/tasproj/StateDictionary.cs b/src/BizHawk.Client.Common/movie/tasproj/StateDictionary.cs
index ffdb67fa1da..747f72c676d 100644
--- a/src/BizHawk.Client.Common/movie/tasproj/StateDictionary.cs
+++ b/src/BizHawk.Client.Common/movie/tasproj/StateDictionary.cs
@@ -51,15 +51,9 @@ public void SetState(int frame, Stream stream)
public bool IsReadOnly => false;
- public void Add(int key, byte[] value)
- {
- this[key] = value;
- }
+ public void Add(int key, byte[] value) => this[key] = value;
- public void Add(KeyValuePair item)
- {
- this[item.Key] = item.Value;
- }
+ public void Add(KeyValuePair item) => this[item.Key] = item.Value;
public void Clear()
{
@@ -69,20 +63,11 @@ public void Clear()
_streams.Clear();
}
- public bool Contains(KeyValuePair item)
- {
- throw new NotImplementedException();
- }
+ public bool Contains(KeyValuePair item) => throw new NotImplementedException();
- public bool ContainsKey(int key)
- {
- return _streams.ContainsKey(key);
- }
+ public bool ContainsKey(int key) => _streams.ContainsKey(key);
- public void CopyTo(KeyValuePair[] array, int arrayIndex)
- {
- throw new NotImplementedException();
- }
+ public void CopyTo(KeyValuePair[] array, int arrayIndex) => throw new NotImplementedException();
public IEnumerator> GetEnumerator()
{
@@ -101,10 +86,7 @@ public bool Remove(int key)
return false;
}
- public bool Remove(KeyValuePair item)
- {
- throw new NotImplementedException();
- }
+ public bool Remove(KeyValuePair item) => throw new NotImplementedException();
public bool TryGetValue(int key, out byte[] value)
{
@@ -122,9 +104,6 @@ public bool TryGetValue(int key, out byte[] value)
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- public void Dispose()
- {
- Clear();
- }
+ public void Dispose() => Clear();
}
}
diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasBranch.cs b/src/BizHawk.Client.Common/movie/tasproj/TasBranch.cs
index b4ace9f0c58..ef3c3ecace0 100644
--- a/src/BizHawk.Client.Common/movie/tasproj/TasBranch.cs
+++ b/src/BizHawk.Client.Common/movie/tasproj/TasBranch.cs
@@ -10,7 +10,7 @@ namespace BizHawk.Client.Common
{
public class TasBranch
{
- internal struct ForSerialization
+ internal readonly struct ForSerialization
{
public readonly int Frame;
@@ -116,7 +116,7 @@ public void Replace(TasBranch old, TasBranch newBranch)
public new bool Remove(TasBranch item)
{
- var result = base.Remove(item);
+ bool result = base.Remove(item);
if (result)
{
_movie.FlagChanges();
@@ -127,13 +127,13 @@ public void Replace(TasBranch old, TasBranch newBranch)
public void Save(ZipStateSaver bs)
{
- var nheader = new IndexedStateLump(BinaryStateLump.BranchHeader);
- var ncore = new IndexedStateLump(BinaryStateLump.BranchCoreData);
- var ninput = new IndexedStateLump(BinaryStateLump.BranchInputLog);
- var nframebuffer = new IndexedStateLump(BinaryStateLump.BranchFrameBuffer);
- var ncoreframebuffer = new IndexedStateLump(BinaryStateLump.BranchCoreFrameBuffer);
- var nmarkers = new IndexedStateLump(BinaryStateLump.BranchMarkers);
- var nusertext = new IndexedStateLump(BinaryStateLump.BranchUserText);
+ IndexedStateLump nheader = new(BinaryStateLump.BranchHeader);
+ IndexedStateLump ncore = new(BinaryStateLump.BranchCoreData);
+ IndexedStateLump ninput = new(BinaryStateLump.BranchInputLog);
+ IndexedStateLump nframebuffer = new(BinaryStateLump.BranchFrameBuffer);
+ IndexedStateLump ncoreframebuffer = new(BinaryStateLump.BranchCoreFrameBuffer);
+ IndexedStateLump nmarkers = new(BinaryStateLump.BranchMarkers);
+ IndexedStateLump nusertext = new(BinaryStateLump.BranchUserText);
foreach (var b in this)
{
bs.PutLump(nheader, tw => tw.WriteLine(JsonConvert.SerializeObject(b.ForSerial)));
@@ -151,13 +151,13 @@ public void Save(ZipStateSaver bs)
bs.PutLump(nframebuffer, s =>
{
- var vp = new BitmapBufferVideoProvider(b.OSDFrameBuffer);
+ BitmapBufferVideoProvider vp = new(b.OSDFrameBuffer);
QuickBmpFile.Save(vp, s, b.OSDFrameBuffer.Width, b.OSDFrameBuffer.Height);
});
bs.PutLump(ncoreframebuffer, s =>
{
- var vp = new BitmapBufferVideoProvider(b.CoreFrameBuffer);
+ BitmapBufferVideoProvider vp = new(b.CoreFrameBuffer);
QuickBmpFile.Save(vp, s, b.CoreFrameBuffer.Width, b.CoreFrameBuffer.Height);
});
@@ -177,23 +177,23 @@ public void Save(ZipStateSaver bs)
public void Load(ZipStateLoader bl, ITasMovie movie)
{
- var nheader = new IndexedStateLump(BinaryStateLump.BranchHeader);
- var ncore = new IndexedStateLump(BinaryStateLump.BranchCoreData);
- var ninput = new IndexedStateLump(BinaryStateLump.BranchInputLog);
- var nframebuffer = new IndexedStateLump(BinaryStateLump.BranchFrameBuffer);
- var ncoreframebuffer = new IndexedStateLump(BinaryStateLump.BranchCoreFrameBuffer);
- var nmarkers = new IndexedStateLump(BinaryStateLump.BranchMarkers);
- var nusertext = new IndexedStateLump(BinaryStateLump.BranchUserText);
+ IndexedStateLump nheader = new(BinaryStateLump.BranchHeader);
+ IndexedStateLump ncore = new(BinaryStateLump.BranchCoreData);
+ IndexedStateLump ninput = new(BinaryStateLump.BranchInputLog);
+ IndexedStateLump nframebuffer = new(BinaryStateLump.BranchFrameBuffer);
+ IndexedStateLump ncoreframebuffer = new(BinaryStateLump.BranchCoreFrameBuffer);
+ IndexedStateLump nmarkers = new(BinaryStateLump.BranchMarkers);
+ IndexedStateLump nusertext = new(BinaryStateLump.BranchUserText);
Clear();
while (true)
{
- var b = new TasBranch();
+ TasBranch b = new();
if (!bl.GetLump(nheader, abort: false, tr =>
{
- var header = (dynamic)JsonConvert.DeserializeObject(tr.ReadLine());
+ dynamic header = JsonConvert.DeserializeObject(tr.ReadLine());
b.Frame = (int)header.Frame;
var timestamp = header.TimeStamp;
diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs b/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs
index 303d7c5a860..6e820025310 100644
--- a/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs
+++ b/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs
@@ -7,14 +7,14 @@ namespace BizHawk.Client.Common
{
public class TasLagLog
{
- private Dictionary _lagLog = new Dictionary