using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Stonewards_Visuals.Configuration;
using Stonewards_Visuals.Patches;
using Stonewards_Visuals.Upscaling;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.NVIDIA;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.github.glarmer.Stonewards_Visuals")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+8af6da7117bd1eab8239509932b13001e331e8e3")]
[assembly: AssemblyProduct("com.github.glarmer.Stonewards_Visuals")]
[assembly: AssemblyTitle("Stonewards Visuals")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[CompilerGenerated]
internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
int ICollection.Count => _items.Length;
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
object IList.this[int index]
{
get
{
return _items[index];
}
set
{
throw new NotSupportedException();
}
}
bool IList.IsFixedSize => true;
bool IList.IsReadOnly => true;
int IReadOnlyCollection<T>.Count => _items.Length;
T IReadOnlyList<T>.this[int index] => _items[index];
int ICollection<T>.Count => _items.Length;
bool ICollection<T>.IsReadOnly => true;
T IList<T>.this[int index]
{
get
{
return _items[index];
}
set
{
throw new NotSupportedException();
}
}
public <>z__ReadOnlyArray(T[] items)
{
_items = items;
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_items).GetEnumerator();
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_items).CopyTo(array, index);
}
int IList.Add(object value)
{
throw new NotSupportedException();
}
void IList.Clear()
{
throw new NotSupportedException();
}
bool IList.Contains(object value)
{
return ((IList)_items).Contains(value);
}
int IList.IndexOf(object value)
{
return ((IList)_items).IndexOf(value);
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
void IList.Remove(object value)
{
throw new NotSupportedException();
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return ((IEnumerable<T>)_items).GetEnumerator();
}
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<T>.Contains(T item)
{
return ((ICollection<T>)_items).Contains(item);
}
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
((ICollection<T>)_items).CopyTo(array, arrayIndex);
}
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
int IList<T>.IndexOf(T item)
{
return ((IList<T>)_items).IndexOf(item);
}
void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
void IList<T>.RemoveAt(int index)
{
throw new NotSupportedException();
}
}
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
internal sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte P_0)
{
NullableFlags = new byte[1] { P_0 };
}
public NullableAttribute(byte[] P_0)
{
NullableFlags = P_0;
}
}
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
internal sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte P_0)
{
Flag = P_0;
}
}
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
internal sealed class RefSafetyRulesAttribute : Attribute
{
public readonly int Version;
public RefSafetyRulesAttribute(int P_0)
{
Version = P_0;
}
}
}
namespace BepInEx
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
[Conditional("CodeGeneration")]
internal sealed class BepInAutoPluginAttribute : Attribute
{
public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
{
}
}
}
namespace BepInEx.Preloader.Core.Patching
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
[Conditional("CodeGeneration")]
internal sealed class PatcherAutoPluginAttribute : Attribute
{
public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
{
}
}
}
namespace Stonewards_Visuals
{
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("com.github.glarmer.Stonewards_Visuals", "Stonewards Visuals", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
private ModConfigurationUI _ui;
private Camera? _lastCamera;
private float _nextCameraCheck;
private Harmony? _harmony;
public const string Id = "com.github.glarmer.Stonewards_Visuals";
internal static ManualLogSource Log { get; private set; }
public static Plugin Instance { get; private set; }
public ConfigurationHandler ConfigurationHandler { get; private set; }
public Settings Settings { get; private set; }
internal DLSSController? DLSSController { get; private set; }
internal bool UpscalerLibAvailable { get; private set; }
public static string Name => "Stonewards Visuals";
public static string Version => "1.0.0";
private void Awake()
{
//IL_0075: Unknown result type (might be due to invalid IL or missing references)
//IL_007f: Expected O, but got Unknown
//IL_008f: Unknown result type (might be due to invalid IL or missing references)
//IL_0095: Expected O, but got Unknown
Log = ((BaseUnityPlugin)this).Logger;
if ((Object)(object)Instance == (Object)null)
{
Instance = this;
}
UpscalerLibAvailable = OptionalUpscalerLib.IsInstalled;
if (!UpscalerLibAvailable)
{
Log.LogInfo((object)"UpscalerLib is not installed. DLSS options will be hidden and DLSS will remain off.");
}
ConfigurationHandler = new ConfigurationHandler(((BaseUnityPlugin)this).Config);
Settings = new Settings();
if (!UpscalerLibAvailable)
{
ConfigurationHandler.ForceDLSSOff();
}
_harmony = new Harmony("com.github.glarmer.Stonewards_Visuals");
_harmony.PatchAll();
GameObject val = new GameObject("StonewardsVisuals");
Object.DontDestroyOnLoad((Object)(object)val);
if (UpscalerLibAvailable)
{
DLSSController = val.AddComponent<DLSSController>();
}
_ui = val.AddComponent<ModConfigurationUI>();
List<Option> list = new List<Option>(3)
{
Option.Bool("Enable Render Scale", ConfigurationHandler.ConfigEnableRenderScale),
Option.Float("Render Scale", ConfigurationHandler.ConfigRenderScale, 0.1f, 2f, 0.1f, () => !ConfigurationHandler.EnableRenderScale || ConfigurationHandler.DLSSEnabled, () => (!ConfigurationHandler.DLSSEnabled) ? ConfigurationHandler.ConfigRenderScale.Value.ToString("F3") : $"{Stonewards_Visuals.Settings.GetDLSSRenderScale(ConfigurationHandler.DLSSMode):F2} ({ConfigurationHandler.DLSSMode})"),
Option.Int("Upscaling Filter", ConfigurationHandler.ConfigUpscalingFilter, 0, 4, 1, () => ConfigurationHandler.DLSSEnabled, () => ConfigurationHandler.ConfigUpscalingFilter.Value switch
{
0 => "Auto",
1 => "Linear",
2 => "Nearest Neighbor",
3 => "FSR 1.0",
4 => "STP",
_ => "???",
})
};
if (UpscalerLibAvailable)
{
list.AddRange(new <>z__ReadOnlyArray<Option>(new Option[4]
{
Option.Int("DLSS", ConfigurationHandler.ConfigDLSSMode, 0, 5, 1, null, () => ConfigurationHandler.DLSSMode switch
{
DLSSMode.Off => "Off",
DLSSMode.Quality => "Quality (67%)",
DLSSMode.Balanced => "Balanced (58%)",
DLSSMode.Performance => "Performance (50%)",
DLSSMode.UltraPerformance => "Ultra Performance (33%)",
DLSSMode.DLAA => "DLAA (100%)",
_ => "???",
}),
Option.Int("DLSS Preset", ConfigurationHandler.ConfigDLSSPreset, 0, 4, 1, () => !ConfigurationHandler.DLSSEnabled, () => ConfigurationHandler.DLSSPresetMode switch
{
DLSSPresetMode.PresetF => "Preset F (CNN)",
DLSSPresetMode.PresetJ => "Preset J (Transformer)",
DLSSPresetMode.PresetK => "Preset K (Transformer)",
DLSSPresetMode.PresetL => "Preset L (Transformer DLSS 4.5)",
DLSSPresetMode.PresetM => "Preset M (Transformer DLSS 4.5)",
_ => "???",
}),
Option.Bool("DLSS Jitter", ConfigurationHandler.ConfigDLSSJitter, () => !ConfigurationHandler.DLSSEnabled),
Option.Float("DLSS Jitter Strength", ConfigurationHandler.ConfigDLSSJitterStrength, 0f, 1f, 0.05f, () => !ConfigurationHandler.DLSSEnabled || !ConfigurationHandler.DLSSJitterEnabled, () => $"{ConfigurationHandler.DLSSJitterStrength * 100f:F0}%")
}));
}
list.AddRange(new <>z__ReadOnlyArray<Option>(new Option[9]
{
Option.Bool("Anisotropic Filtering", ConfigurationHandler.ConfigAnisotropicFiltering),
Option.Float("LOD Quality", ConfigurationHandler.ConfigLODQuality, 0.1f, 10f, 0.1f),
Option.Int("Shadowmap Resolution", ConfigurationHandler.ConfigShadowmapResolution, 0, 10240, 1024),
Option.Int("Shadow Distance", ConfigurationHandler.ConfigShadowDistance, 0, 1000, 25),
Option.Int("Shadow Cascades", ConfigurationHandler.ConfigShadowCascades, 1, 10),
Option.Bool("Soft Shadows", ConfigurationHandler.ConfigSoftShadows),
Option.Int("Camera Antialiasing", ConfigurationHandler.ConfigCameraAA, 0, 3, 1, () => ConfigurationHandler.DLSSEnabled, () => ConfigurationHandler.ConfigCameraAA.Value switch
{
0 => "None",
1 => "FXAA",
2 => "SMAA",
3 => "TAA",
_ => "???",
}),
Option.Int("MSAA", ConfigurationHandler.ConfigMSAA, 0, 8, 2, () => ConfigurationHandler.DLSSEnabled, () => ConfigurationHandler.ConfigMSAA.Value switch
{
0 => "Off",
2 => "2x",
4 => "4x",
8 => "8x",
_ => ConfigurationHandler.ConfigMSAA.Value + "x",
}),
Option.InputAction("Menu Key", ConfigurationHandler.ConfigMenuKey)
}));
_ui.Init(list);
SceneManager.sceneLoaded += OnSceneLoaded;
Settings.SetAllSettings();
RefreshCamera();
Log.LogInfo((object)("Plugin " + Name + " is loaded for Stonewards!"));
}
private void Update()
{
if (!(Time.unscaledTime < _nextCameraCheck))
{
_nextCameraCheck = Time.unscaledTime + 1f;
RefreshCamera();
}
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
_lastCamera = null;
RefreshCamera();
Settings.SetAllSettings();
}
private void RefreshCamera()
{
Camera main = Camera.main;
if (!((Object)(object)main == (Object)null) && !((Object)(object)main == (Object)(object)_lastCamera))
{
_lastCamera = main;
DLSSController?.Refresh(main);
Settings.SetAllCameraSettings(main);
Log.LogInfo((object)("Using camera '" + ((Object)main).name + "' for Stonewards visual settings."));
}
}
private void OnDestroy()
{
Harmony? harmony = _harmony;
if (harmony != null)
{
harmony.UnpatchSelf();
}
_harmony = null;
SceneManager.sceneLoaded -= OnSceneLoaded;
ConfigurationHandler?.Dispose();
if ((Object)(object)Instance == (Object)(object)this)
{
Instance = null;
}
}
}
public class Settings
{
private readonly ConfigurationHandler _configurationHandler = Plugin.Instance.ConfigurationHandler;
internal static float GetDLSSRenderScale(DLSSMode mode)
{
return mode switch
{
DLSSMode.Quality => 0.67f,
DLSSMode.Balanced => 0.58f,
DLSSMode.Performance => 0.5f,
DLSSMode.UltraPerformance => 1f / 3f,
DLSSMode.DLAA => 1f,
_ => 1f,
};
}
public void SetAllSettings()
{
SetDLSS();
SetLODQuality();
SetShadowDistance();
SetShadowCascades();
SetAnisotropicFiltering();
SetSoftShadows();
SetShadowmapResolution();
}
public void SetAllCameraSettings(Camera? camera = null)
{
SetPostProcessAA(camera);
SetDLSS();
}
public void SetSoftShadows()
{
RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
if (val != null)
{
BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic;
FieldInfo field = ((object)val).GetType().GetField("m_SoftShadowsSupported", bindingAttr);
if (field != null)
{
field.SetValue(val, _configurationHandler.SoftShadows);
}
else
{
Plugin.Log.LogWarning((object)"This URP version does not expose the soft-shadow setting.");
}
Plugin.Log.LogInfo((object)("Soft Shadows applied: " + _configurationHandler.SoftShadows));
}
}
public void SetShadowmapResolution()
{
RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
if (val != null)
{
val.mainLightShadowmapResolution = _configurationHandler.ShadowmapResolution;
Plugin.Log.LogInfo((object)("Shadowmap Resolution applied: " + _configurationHandler.ShadowmapResolution));
}
}
public void SetAnisotropicFiltering()
{
QualitySettings.anisotropicFiltering = (AnisotropicFiltering)(_configurationHandler.AnisotropicFiltering ? 2 : 0);
Plugin.Log.LogInfo((object)("Anisotropic Filtering applied: " + _configurationHandler.AnisotropicFiltering));
}
public void SetPostProcessAA(Camera? camera = null)
{
if (camera == null)
{
camera = Camera.main;
}
UniversalAdditionalCameraData val = default(UniversalAdditionalCameraData);
if ((Object)(object)camera != (Object)null && ((Component)camera).TryGetComponent<UniversalAdditionalCameraData>(ref val))
{
val.antialiasing = (AntialiasingMode)((!Plugin.Instance.ConfigurationHandler.DLSSEnabled) ? Plugin.Instance.ConfigurationHandler.CameraAA : 0);
if (Plugin.Instance.ConfigurationHandler.MSAA != 0 && Plugin.Instance.ConfigurationHandler.CameraAA == 3)
{
Plugin.Instance.ConfigurationHandler.ConfigMSAA.Value = 0;
}
}
Plugin.Log.LogInfo((object)("Camera AA applied: " + _configurationHandler.CameraAA));
}
public void SetMSAA()
{
RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
if (val != null)
{
val.msaaSampleCount = (Plugin.Instance.ConfigurationHandler.DLSSEnabled ? 1 : Plugin.Instance.ConfigurationHandler.MSAA);
if (Plugin.Instance.ConfigurationHandler.MSAA != 0 && Plugin.Instance.ConfigurationHandler.CameraAA == 3)
{
Plugin.Instance.ConfigurationHandler.ConfigCameraAA.Value = 2;
}
}
Plugin.Log.LogInfo((object)("MSAA applied: " + _configurationHandler.MSAA));
}
public void SetResolutionScale()
{
if (!_configurationHandler.EnableRenderScale)
{
ResolutionManagerStartPatch.RestoreGameTargetHeight();
Plugin.Log.LogInfo((object)"Render Scale skipped: Enable Render Scale is off.");
return;
}
RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
if (val != null)
{
float num = (val.renderScale = (_configurationHandler.DLSSEnabled ? GetDLSSRenderScale(_configurationHandler.DLSSMode) : _configurationHandler.RenderScale));
Plugin.Log.LogInfo((object)(_configurationHandler.DLSSEnabled ? $"Render Scale applied: {num} (DLSS {_configurationHandler.DLSSMode})" : ("Render Scale applied: " + num)));
ResolutionManagerStartPatch.ApplyTargetHeightFromRenderScale();
}
}
public void SetUpscaler()
{
//IL_003b: Unknown result type (might be due to invalid IL or missing references)
//IL_0040: Unknown result type (might be due to invalid IL or missing references)
RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
if (val != null)
{
val.upscalingFilter = (UpscalingFilterSelection)(_configurationHandler.DLSSEnabled ? 1 : _configurationHandler.UpscalingFilter);
Plugin.Log.LogInfo((object)("Upscaling Filter applied: " + ((object)val.upscalingFilter/*cast due to .constrained prefix*/).ToString()));
}
}
public void SetDLSS()
{
SetResolutionScale();
SetUpscaler();
SetPostProcessAA();
SetMSAA();
Plugin.Instance.DLSSController?.ResetHistory();
Plugin.Log.LogInfo((object)("DLSS mode applied: " + _configurationHandler.DLSSMode));
}
public void SetLODQuality()
{
QualitySettings.lodBias = _configurationHandler.LodQuality;
Plugin.Log.LogInfo((object)("LOD Bias applied: " + _configurationHandler.LodQuality));
}
public void SetShadowDistance()
{
RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
if (val != null)
{
val.shadowDistance = _configurationHandler.ShadowDistance;
Plugin.Log.LogInfo((object)("Shadow Distance applied: " + _configurationHandler.ShadowDistance));
}
}
public void SetShadowCascades()
{
RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
if (val != null)
{
val.shadowCascadeCount = _configurationHandler.ShadowCascades;
Plugin.Log.LogInfo((object)("Shadow Cascades applied: " + _configurationHandler.ShadowCascades));
}
}
}
}
namespace Stonewards_Visuals.Upscaling
{
internal sealed class DLSSController : MonoBehaviour
{
private StonewardsDLSSRendererFeature? _feature;
private ScriptableRenderer? _renderer;
private Camera? _camera;
private int _jitterIndex;
private Matrix4x4 _savedProjectionMatrix;
private Camera? _jitteredCamera;
private bool _jitterApplied;
private static readonly float[] HaltonX = GenerateHalton(2, 32);
private static readonly float[] HaltonY = GenerateHalton(3, 32);
private static readonly FieldInfo RendererFeaturesField = AccessTools.Field(typeof(ScriptableRenderer), "m_RendererFeatures");
public void Refresh(Camera? camera = null)
{
if ((Object)(object)camera != (Object)null)
{
_camera = camera;
}
else if ((Object)(object)_camera == (Object)null)
{
_camera = Camera.main;
}
ApplyCameraRequirements();
EnsureFeatureInstalled();
_feature?.SetTargetCamera(_camera);
_feature?.SetDLSSActive(Plugin.Instance.ConfigurationHandler.DLSSEnabled);
}
public void ResetHistory()
{
_jitterIndex = 0;
_feature?.ResetHistory();
Refresh();
}
private void OnEnable()
{
RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering += OnEndCameraRendering;
}
private void OnDisable()
{
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering -= OnEndCameraRendering;
RestoreJitteredProjection();
}
private void ApplyCameraRequirements()
{
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
if (!((Object)(object)_camera == (Object)null) && Plugin.Instance.ConfigurationHandler.DLSSEnabled)
{
Camera? camera = _camera;
camera.depthTextureMode = (DepthTextureMode)(camera.depthTextureMode | 5);
UniversalAdditionalCameraData val = default(UniversalAdditionalCameraData);
if (((Component)_camera).TryGetComponent<UniversalAdditionalCameraData>(ref val))
{
val.requiresDepthTexture = true;
val.requiresColorTexture = true;
val.resetHistory = true;
}
}
}
private void EnsureFeatureInstalled()
{
UniversalAdditionalCameraData val = default(UniversalAdditionalCameraData);
if ((Object)(object)_camera == (Object)null || !((Component)_camera).TryGetComponent<UniversalAdditionalCameraData>(ref val))
{
return;
}
ScriptableRenderer scriptableRenderer = val.scriptableRenderer;
if (scriptableRenderer == null)
{
return;
}
if ((Object)(object)_feature == (Object)null)
{
_feature = ScriptableObject.CreateInstance<StonewardsDLSSRendererFeature>();
((Object)_feature).name = "Stonewards Visuals DLSS";
((ScriptableRendererFeature)_feature).Create();
((ScriptableRendererFeature)_feature).SetActive(false);
}
List<ScriptableRendererFeature> rendererFeatures = GetRendererFeatures(scriptableRenderer);
if (rendererFeatures != null && (_renderer != scriptableRenderer || !rendererFeatures.Contains((ScriptableRendererFeature)(object)_feature)))
{
if (_renderer != null)
{
GetRendererFeatures(_renderer)?.Remove((ScriptableRendererFeature)(object)_feature);
}
rendererFeatures.Add((ScriptableRendererFeature)(object)_feature);
_renderer = scriptableRenderer;
Plugin.Log.LogInfo((object)"DLSS renderer feature installed.");
}
}
private void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
{
//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
//IL_0106: Unknown result type (might be due to invalid IL or missing references)
ConfigurationHandler configurationHandler = Plugin.Instance.ConfigurationHandler;
if ((Object)(object)camera != (Object)(object)_camera || !configurationHandler.DLSSEnabled || !configurationHandler.DLSSJitterEnabled || configurationHandler.DLSSJitterStrength <= 0f)
{
if ((Object)(object)camera == (Object)(object)_jitteredCamera)
{
RestoreJitteredProjection();
}
return;
}
_jitterIndex = (_jitterIndex + 1) % HaltonX.Length;
float num = Mathf.Clamp01(configurationHandler.DLSSJitterStrength);
float num2 = (HaltonX[_jitterIndex] - 0.5f) * num;
float num3 = (HaltonY[_jitterIndex] - 0.5f) * num;
int num4 = Mathf.Max(camera.pixelWidth, 1);
int num5 = Mathf.Max(camera.pixelHeight, 1);
camera.ResetProjectionMatrix();
_savedProjectionMatrix = camera.projectionMatrix;
camera.nonJitteredProjectionMatrix = _savedProjectionMatrix;
Matrix4x4 savedProjectionMatrix = _savedProjectionMatrix;
savedProjectionMatrix.m02 += num2 / (float)num4 * 2f;
savedProjectionMatrix.m12 += num3 / (float)num5 * 2f;
camera.projectionMatrix = savedProjectionMatrix;
_jitteredCamera = camera;
_jitterApplied = true;
}
private void OnEndCameraRendering(ScriptableRenderContext context, Camera camera)
{
if ((Object)(object)camera == (Object)(object)_jitteredCamera)
{
RestoreJitteredProjection();
}
}
private void RestoreJitteredProjection()
{
//IL_001e: Unknown result type (might be due to invalid IL or missing references)
//IL_002f: Unknown result type (might be due to invalid IL or missing references)
if (_jitterApplied && !((Object)(object)_jitteredCamera == (Object)null))
{
_jitteredCamera.projectionMatrix = _savedProjectionMatrix;
_jitteredCamera.nonJitteredProjectionMatrix = _savedProjectionMatrix;
_jitteredCamera = null;
_jitterApplied = false;
}
}
private void OnDestroy()
{
RestoreJitteredProjection();
if (_renderer != null && (Object)(object)_feature != (Object)null)
{
GetRendererFeatures(_renderer)?.Remove((ScriptableRendererFeature)(object)_feature);
}
if ((Object)(object)_feature != (Object)null)
{
((ScriptableRendererFeature)_feature).Dispose();
Object.Destroy((Object)(object)_feature);
_feature = null;
}
}
private static List<ScriptableRendererFeature>? GetRendererFeatures(ScriptableRenderer renderer)
{
return RendererFeaturesField?.GetValue(renderer) as List<ScriptableRendererFeature>;
}
private static float[] GenerateHalton(int radix, int count)
{
float[] array = new float[count];
for (int i = 0; i < count; i++)
{
array[i] = Halton(i + 1, radix);
}
return array;
}
private static float Halton(int index, int radix)
{
float num = 0f;
float num2 = 1f / (float)radix;
while (index > 0)
{
num += (float)(index % radix) * num2;
index /= radix;
num2 /= (float)radix;
}
return num;
}
}
internal enum DLSSMode
{
Off,
Quality,
Balanced,
Performance,
UltraPerformance,
DLAA
}
internal enum DLSSPresetMode
{
PresetF,
PresetJ,
PresetK,
PresetL,
PresetM
}
internal static class OptionalUpscalerLib
{
public const string PluginGuid = "com.github.glarmer.UpscalerLib";
private const string NvidiaNativeLoaderTypeName = "UpscalerLib.Native.NvidiaNativeLoader";
private static bool _resolved;
private static Type? _nvidiaNativeLoaderType;
private static MethodInfo? _ensureLoadedMethod;
private static PropertyInfo? _nativeDirectoryProperty;
public static bool IsInstalled => Chainloader.PluginInfos.ContainsKey("com.github.glarmer.UpscalerLib");
public static string NativeDirectory
{
get
{
Resolve();
return (_nativeDirectoryProperty?.GetValue(null) as string) ?? string.Empty;
}
}
public static bool EnsureNvidiaLoaded()
{
if (!IsInstalled)
{
return false;
}
Resolve();
if (_ensureLoadedMethod == null)
{
return false;
}
try
{
object obj = _ensureLoadedMethod.Invoke(null, new object[1] { Plugin.Log });
return obj is bool && (bool)obj;
}
catch (Exception ex)
{
Plugin.Log.LogWarning((object)("UpscalerLib NVIDIA loader failed " + ex.GetType().Name + ": " + ex.Message));
return false;
}
}
private static void Resolve()
{
if (_resolved)
{
return;
}
_resolved = true;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
_nvidiaNativeLoaderType = assembly.GetType("UpscalerLib.Native.NvidiaNativeLoader", throwOnError: false);
if (_nvidiaNativeLoaderType != null)
{
break;
}
}
if (!(_nvidiaNativeLoaderType == null))
{
_ensureLoadedMethod = _nvidiaNativeLoaderType.GetMethod("EnsureLoaded", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(ManualLogSource) }, null);
_nativeDirectoryProperty = _nvidiaNativeLoaderType.GetProperty("NativeDirectory", BindingFlags.Static | BindingFlags.Public);
}
}
}
internal sealed class StonewardsDLSSRendererFeature : ScriptableRendererFeature
{
private sealed class StonewardsDLSSPass : ScriptableRenderPass, IDisposable
{
private sealed class PassData
{
public bool ShouldReinitializeContext;
public uint InputWidth;
public uint InputHeight;
public uint OutputWidth;
public uint OutputHeight;
public bool InputIsHDR;
public bool InvertedDepth;
public DLSSQuality Quality;
public DLSSPresetMode PresetMode;
public DLSSCommandExecutionData ExecutionData;
public TextureHandle ColorInput;
public TextureHandle Depth;
public TextureHandle MotionVectors;
public TextureHandle ColorOutput;
}
private GraphicsDevice? _device;
private DLSSContext? _context;
private DLSSQuality _contextQuality = (DLSSQuality)2;
private DLSSPresetMode _contextPresetMode = DLSSPresetMode.PresetK;
private DLSSPreset _contextActivePreset = (DLSSPreset)4;
private Vector2Int _contextInputResolution;
private Vector2Int _contextOutputResolution;
private bool _contextInputWasHDR;
private int _contextCreateCount;
private int _contextDestroyCount;
private bool _resetHistory = true;
private bool _availabilityChecked;
private bool _available;
public StonewardsDLSSPass()
{
//IL_0002: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_0033: Unknown result type (might be due to invalid IL or missing references)
//IL_003d: Expected O, but got Unknown
((ScriptableRenderPass)this).renderPassEvent = (RenderPassEvent)600;
((ScriptableRenderPass)this).profilingSampler = new ProfilingSampler("Stonewards Visuals DLSS");
((ScriptableRenderPass)this).ConfigureInput((ScriptableRenderPassInput)9);
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
//IL_0034: Unknown result type (might be due to invalid IL or missing references)
//IL_0039: Unknown result type (might be due to invalid IL or missing references)
//IL_003b: Unknown result type (might be due to invalid IL or missing references)
//IL_0040: Unknown result type (might be due to invalid IL or missing references)
//IL_0054: Unknown result type (might be due to invalid IL or missing references)
//IL_004c: Unknown result type (might be due to invalid IL or missing references)
//IL_0059: Unknown result type (might be due to invalid IL or missing references)
//IL_005c: Unknown result type (might be due to invalid IL or missing references)
//IL_0061: Unknown result type (might be due to invalid IL or missing references)
//IL_0082: Unknown result type (might be due to invalid IL or missing references)
//IL_0087: Unknown result type (might be due to invalid IL or missing references)
//IL_0089: Unknown result type (might be due to invalid IL or missing references)
//IL_0098: Unknown result type (might be due to invalid IL or missing references)
//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
//IL_0145: Unknown result type (might be due to invalid IL or missing references)
//IL_014d: Unknown result type (might be due to invalid IL or missing references)
//IL_0152: Unknown result type (might be due to invalid IL or missing references)
//IL_015a: Unknown result type (might be due to invalid IL or missing references)
//IL_015f: Unknown result type (might be due to invalid IL or missing references)
//IL_017f: Unknown result type (might be due to invalid IL or missing references)
//IL_0181: Unknown result type (might be due to invalid IL or missing references)
//IL_01af: Unknown result type (might be due to invalid IL or missing references)
//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
//IL_0200: Unknown result type (might be due to invalid IL or missing references)
//IL_0210: Unknown result type (might be due to invalid IL or missing references)
//IL_0211: Unknown result type (might be due to invalid IL or missing references)
//IL_0218: Unknown result type (might be due to invalid IL or missing references)
//IL_021a: Unknown result type (might be due to invalid IL or missing references)
//IL_0221: Unknown result type (might be due to invalid IL or missing references)
//IL_0223: Unknown result type (might be due to invalid IL or missing references)
//IL_022a: Unknown result type (might be due to invalid IL or missing references)
//IL_022c: Unknown result type (might be due to invalid IL or missing references)
//IL_0238: Unknown result type (might be due to invalid IL or missing references)
//IL_023d: Unknown result type (might be due to invalid IL or missing references)
//IL_0294: Unknown result type (might be due to invalid IL or missing references)
ConfigurationHandler configurationHandler = Plugin.Instance.ConfigurationHandler;
if (!configurationHandler.DLSSEnabled || !EnsureAvailable())
{
return;
}
UniversalResourceData val = frameData.Get<UniversalResourceData>();
if (val.isActiveTargetBackBuffer)
{
return;
}
UniversalCameraData val2 = frameData.Get<UniversalCameraData>();
TextureHandle cameraColor = val.cameraColor;
TextureHandle cameraDepthTexture = val.cameraDepthTexture;
TextureHandle depth = (((TextureHandle)(ref cameraDepthTexture)).IsValid() ? val.cameraDepthTexture : val.cameraDepth);
TextureHandle motionVectorColor = val.motionVectorColor;
if (!((TextureHandle)(ref cameraColor)).IsValid() || !((TextureHandle)(ref depth)).IsValid() || !((TextureHandle)(ref motionVectorColor)).IsValid())
{
return;
}
TextureDesc descriptor = ((TextureHandle)(ref cameraColor)).GetDescriptor(renderGraph);
int num = Math.Max(descriptor.width, 1);
int num2 = Math.Max(descriptor.height, 1);
int num3 = Math.Max(val2.camera.pixelWidth, 1);
int num4 = Math.Max(val2.camera.pixelHeight, 1);
TextureDesc val3 = descriptor;
val3.width = num3;
val3.height = num4;
val3.format = GraphicsFormatUtility.GetLinearFormat(descriptor.format);
val3.msaaSamples = (MSAASamples)1;
val3.useMipMap = false;
val3.autoGenerateMips = false;
val3.useDynamicScale = false;
val3.anisoLevel = 0;
val3.discardBuffer = false;
val3.enableRandomWrite = true;
val3.name = "_StonewardsVisualsDLSSOutput";
val3.clearBuffer = false;
val3.filterMode = (FilterMode)1;
TextureHandle val4 = renderGraph.CreateTexture(ref val3);
DLSSQuality quality = ToDLSSQuality(configurationHandler.DLSSMode);
DLSSPresetMode dLSSPresetMode = configurationHandler.DLSSPresetMode;
Vector2Int inputResolution = default(Vector2Int);
((Vector2Int)(ref inputResolution))..ctor(num, num2);
Vector2Int outputResolution = default(Vector2Int);
((Vector2Int)(ref outputResolution))..ctor(num3, num4);
bool inputIsHDR = GraphicsFormatUtility.IsHDRFormat(descriptor.format);
PassData passData = default(PassData);
IUnsafeRenderGraphBuilder val5 = renderGraph.AddUnsafePass<PassData>("Stonewards Visuals DLSS", ref passData, ((ScriptableRenderPass)this).profilingSampler, "./src/Stonewards_Visuals/Upscaling/StonewardsDLSSRendererFeature.cs", 148);
try
{
passData.ShouldReinitializeContext = ShouldReinitializeContext(quality, dLSSPresetMode, inputResolution, outputResolution, inputIsHDR);
passData.InputWidth = (uint)num;
passData.InputHeight = (uint)num2;
passData.OutputWidth = (uint)num3;
passData.OutputHeight = (uint)num4;
passData.InputIsHDR = inputIsHDR;
passData.InvertedDepth = SystemInfo.usesReversedZBuffer;
passData.Quality = quality;
passData.PresetMode = dLSSPresetMode;
passData.ColorInput = cameraColor;
passData.Depth = depth;
passData.MotionVectors = motionVectorColor;
passData.ColorOutput = val4;
passData.ExecutionData = CreateExecutionData(num, num2);
((IBaseRenderGraphBuilder)val5).UseTexture(ref cameraColor, (AccessFlags)1);
((IBaseRenderGraphBuilder)val5).UseTexture(ref depth, (AccessFlags)1);
((IBaseRenderGraphBuilder)val5).UseTexture(ref motionVectorColor, (AccessFlags)1);
((IBaseRenderGraphBuilder)val5).UseTexture(ref val4, (AccessFlags)2);
((IBaseRenderGraphBuilder)val5).AllowGlobalStateModification(true);
val5.SetRenderFunc<PassData>((BaseRenderFunc<PassData, UnsafeGraphContext>)delegate(PassData data, UnsafeGraphContext context)
{
//IL_0040: Unknown result type (might be due to invalid IL or missing references)
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_004c: Unknown result type (might be due to invalid IL or missing references)
//IL_0055: Unknown result type (might be due to invalid IL or missing references)
//IL_0067: Unknown result type (might be due to invalid IL or missing references)
//IL_0079: Unknown result type (might be due to invalid IL or missing references)
//IL_008b: Unknown result type (might be due to invalid IL or missing references)
//IL_009a: Unknown result type (might be due to invalid IL or missing references)
//IL_009b: Unknown result type (might be due to invalid IL or missing references)
CommandBuffer nativeCommandBuffer = CommandBufferHelpers.GetNativeCommandBuffer(context.cmd);
if (data.ShouldReinitializeContext)
{
DestroyContext(nativeCommandBuffer);
CreateContext(nativeCommandBuffer, data);
}
if (_context != null && _device != null)
{
_context.executeData = data.ExecutionData;
DLSSTextureTable val6 = default(DLSSTextureTable);
((DLSSTextureTable)(ref val6)).colorInput = TextureHandle.op_Implicit(data.ColorInput);
((DLSSTextureTable)(ref val6)).depth = TextureHandle.op_Implicit(data.Depth);
((DLSSTextureTable)(ref val6)).motionVectors = TextureHandle.op_Implicit(data.MotionVectors);
((DLSSTextureTable)(ref val6)).colorOutput = TextureHandle.op_Implicit(data.ColorOutput);
DLSSTextureTable val7 = val6;
_device.ExecuteDLSS(nativeCommandBuffer, _context, ref val7);
_resetHistory = false;
}
});
}
finally
{
((IDisposable)val5)?.Dispose();
}
val.cameraColor = val4;
}
public void ResetHistory()
{
_resetHistory = true;
}
public void Dispose()
{
//IL_0011: Unknown result type (might be due to invalid IL or missing references)
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_0022: Expected O, but got Unknown
if (_context != null && _device != null)
{
CommandBuffer val = new CommandBuffer
{
name = "Stonewards Visuals DLSS Dispose"
};
_device.DestroyFeature(val, _context);
Graphics.ExecuteCommandBuffer(val);
val.Release();
_context = null;
_resetHistory = true;
}
}
private bool EnsureAvailable()
{
//IL_0064: Unknown result type (might be due to invalid IL or missing references)
//IL_006a: Invalid comparison between Unknown and I4
//IL_006c: Unknown result type (might be due to invalid IL or missing references)
//IL_0073: Invalid comparison between Unknown and I4
//IL_007f: Unknown result type (might be due to invalid IL or missing references)
//IL_0084: Unknown result type (might be due to invalid IL or missing references)
if (_availabilityChecked)
{
return _available;
}
_availabilityChecked = true;
try
{
if (!OptionalUpscalerLib.EnsureNvidiaLoaded())
{
Plugin.Log.LogWarning((object)"DLSS unavailable because the nvidia Unity plugin did not load.");
return false;
}
LogDLSS();
if (!SystemInfo.graphicsDeviceVendor.ToLowerInvariant().Contains("nvidia"))
{
Plugin.Log.LogWarning((object)"DLSS unavailable as the current GPU is not a Nvidia one.");
return false;
}
if ((int)SystemInfo.graphicsDeviceType != 2 && (int)SystemInfo.graphicsDeviceType != 18)
{
Plugin.Log.LogWarning((object)("DLSS unavailable because Unity's Nvidia plugin needs a Direct3D graphics device. Current API is " + ((object)SystemInfo.graphicsDeviceType/*cast due to .constrained prefix*/).ToString() + "."));
return false;
}
string projectID = typeof(Plugin).Assembly.GetName().Name ?? "Stonewards_Visuals";
_device = CreateGraphicsDevice(projectID);
if (_device == null)
{
Plugin.Log.LogWarning((object)"DLSS unavailable because failed to create nvidia graphics device.");
return false;
}
_available = _device.IsFeatureAvailable((GraphicsDeviceFeature)0);
if (!_available)
{
Plugin.Log.LogWarning((object)"DLSS unavailable because nvidia device does not report DLSS support.");
}
}
catch (Exception ex)
{
Plugin.Log.LogWarning((object)("DLSS unavailable: " + ex.GetType().Name + ": " + ex.Message));
_available = false;
}
return _available;
}
private static GraphicsDevice? CreateGraphicsDevice(string projectID)
{
string nativeDirectory = OptionalUpscalerLib.NativeDirectory;
string text = ((nativeDirectory.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) || nativeDirectory.EndsWith(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal)) ? nativeDirectory : (nativeDirectory + Path.DirectorySeparatorChar));
GraphicsDevice val = GraphicsDevice.CreateGraphicsDevice(projectID, text);
if (val != null)
{
return val;
}
Plugin.Log.LogWarning((object)"DLSS probe CreateGraphicsDevice 1 returned null.");
val = GraphicsDevice.CreateGraphicsDevice(projectID);
if (val != null)
{
return val;
}
Plugin.Log.LogWarning((object)"DLSS probe CreateGraphicsDevice 2 returned null.");
val = GraphicsDevice.CreateGraphicsDevice();
if (val == null)
{
Plugin.Log.LogWarning((object)"DLSS probe CreateGraphicsDevice() 3 returned null.");
}
return val;
}
private static void LogDLSS()
{
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_005a: Unknown result type (might be due to invalid IL or missing references)
Plugin.Log.LogInfo((object)("DLSS probe: Unity=" + Application.unityVersion + ", " + $"Platform={Application.platform}, " + "OS='" + SystemInfo.operatingSystem + "', " + $"API={SystemInfo.graphicsDeviceType}, " + "GPU='" + SystemInfo.graphicsDeviceName + "', Vendor='" + SystemInfo.graphicsDeviceVendor + "', DeviceVersion='" + SystemInfo.graphicsDeviceVersion + "', " + $"NVPluginLoaded={NVUnityPlugin.IsLoaded()}, " + $"NVPluginVersion={GraphicsDevice.version}, " + "NativeDir='" + OptionalUpscalerLib.NativeDirectory + "'"));
}
private bool ShouldReinitializeContext(DLSSQuality quality, DLSSPresetMode presetMode, Vector2Int inputResolution, Vector2Int outputResolution, bool inputIsHDR)
{
//IL_0009: Unknown result type (might be due to invalid IL or missing references)
//IL_000e: Unknown result type (might be due to invalid IL or missing references)
//IL_001b: Unknown result type (might be due to invalid IL or missing references)
//IL_0020: Unknown result type (might be due to invalid IL or missing references)
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
//IL_002e: Unknown result type (might be due to invalid IL or missing references)
if (_context != null && _contextQuality == quality && _contextPresetMode == presetMode && !(_contextInputResolution != inputResolution) && !(_contextOutputResolution != outputResolution))
{
return _contextInputWasHDR != inputIsHDR;
}
return true;
}
private void CreateContext(CommandBuffer cmd, PassData data)
{
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_0054: Unknown result type (might be due to invalid IL or missing references)
//IL_0060: Unknown result type (might be due to invalid IL or missing references)
//IL_0068: Unknown result type (might be due to invalid IL or missing references)
//IL_0070: Unknown result type (might be due to invalid IL or missing references)
//IL_0078: Unknown result type (might be due to invalid IL or missing references)
//IL_0080: Unknown result type (might be due to invalid IL or missing references)
//IL_0086: Unknown result type (might be due to invalid IL or missing references)
//IL_0087: Unknown result type (might be due to invalid IL or missing references)
//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
//IL_010b: Unknown result type (might be due to invalid IL or missing references)
//IL_0110: Unknown result type (might be due to invalid IL or missing references)
//IL_0122: Unknown result type (might be due to invalid IL or missing references)
//IL_0127: Unknown result type (might be due to invalid IL or missing references)
//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
if (_device == null)
{
return;
}
DLSSPreset val = ResolvePreset(data.PresetMode);
DLSSCommandInitializationData val2 = default(DLSSCommandInitializationData);
((DLSSCommandInitializationData)(ref val2)).inputRTWidth = data.InputWidth;
((DLSSCommandInitializationData)(ref val2)).inputRTHeight = data.InputHeight;
((DLSSCommandInitializationData)(ref val2)).outputRTWidth = data.OutputWidth;
((DLSSCommandInitializationData)(ref val2)).outputRTHeight = data.OutputHeight;
((DLSSCommandInitializationData)(ref val2)).quality = data.Quality;
((DLSSCommandInitializationData)(ref val2)).presetQualityMode = val;
((DLSSCommandInitializationData)(ref val2)).presetBalancedMode = val;
((DLSSCommandInitializationData)(ref val2)).presetPerformanceMode = val;
((DLSSCommandInitializationData)(ref val2)).presetUltraPerformanceMode = val;
((DLSSCommandInitializationData)(ref val2)).presetDlaaMode = val;
DLSSCommandInitializationData val3 = val2;
((DLSSCommandInitializationData)(ref val3)).SetFlag((DLSSFeatureFlags)1, data.InputIsHDR);
((DLSSCommandInitializationData)(ref val3)).SetFlag((DLSSFeatureFlags)2, true);
((DLSSCommandInitializationData)(ref val3)).SetFlag((DLSSFeatureFlags)8, data.InvertedDepth);
((DLSSCommandInitializationData)(ref val3)).SetFlag((DLSSFeatureFlags)4, false);
DLSSContext val4 = _device.CreateFeature(cmd, ref val3);
if (val4 == null)
{
Plugin.Log.LogWarning((object)"DLSS context creation returned null.");
return;
}
_context = val4;
_contextQuality = data.Quality;
_contextPresetMode = data.PresetMode;
_contextActivePreset = val;
_contextInputResolution = new Vector2Int((int)data.InputWidth, (int)data.InputHeight);
_contextOutputResolution = new Vector2Int((int)data.OutputWidth, (int)data.OutputHeight);
_contextInputWasHDR = data.InputIsHDR;
_resetHistory = true;
_contextCreateCount++;
if (_contextCreateCount <= 8 || _contextCreateCount % 16 == 0)
{
Plugin.Log.LogInfo((object)($"DLSS context created number: {_contextCreateCount}: " + $"{((Vector2Int)(ref _contextInputResolution)).x}x{((Vector2Int)(ref _contextInputResolution)).y} -> " + $"{((Vector2Int)(ref _contextOutputResolution)).x}x{((Vector2Int)(ref _contextOutputResolution)).y}, " + $"quality={_contextQuality}, preset={_contextPresetMode}/{_contextActivePreset}, " + $"hdr={_contextInputWasHDR}"));
}
}
private static DLSSPreset ResolvePreset(DLSSPresetMode presetMode)
{
//IL_001d: Unknown result type (might be due to invalid IL or missing references)
//IL_0021: Unknown result type (might be due to invalid IL or missing references)
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
//IL_002e: Unknown result type (might be due to invalid IL or missing references)
//IL_0033: Unknown result type (might be due to invalid IL or missing references)
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
return (DLSSPreset)(presetMode switch
{
DLSSPresetMode.PresetF => 1,
DLSSPresetMode.PresetJ => 2,
DLSSPresetMode.PresetK => 4,
DLSSPresetMode.PresetL => 8,
DLSSPresetMode.PresetM => 16,
_ => 4,
});
}
private void DestroyContext(CommandBuffer cmd)
{
if (_context != null && _device != null)
{
_device.DestroyFeature(cmd, _context);
_context = null;
_resetHistory = true;
_contextDestroyCount++;
if (_contextDestroyCount <= 8 || _contextDestroyCount % 16 == 0)
{
Plugin.Log.LogInfo((object)$"DLSS context destroyed number: {_contextDestroyCount}.");
}
}
}
private DLSSCommandExecutionData CreateExecutionData(int inputWidth, int inputHeight)
{
//IL_0002: Unknown result type (might be due to invalid IL or missing references)
//IL_0087: Unknown result type (might be due to invalid IL or missing references)
DLSSCommandExecutionData result = default(DLSSCommandExecutionData);
((DLSSCommandExecutionData)(ref result)).mvScaleX = -inputWidth;
((DLSSCommandExecutionData)(ref result)).mvScaleY = -inputHeight;
((DLSSCommandExecutionData)(ref result)).subrectOffsetX = 0u;
((DLSSCommandExecutionData)(ref result)).subrectOffsetY = 0u;
((DLSSCommandExecutionData)(ref result)).subrectWidth = (uint)inputWidth;
((DLSSCommandExecutionData)(ref result)).subrectHeight = (uint)inputHeight;
((DLSSCommandExecutionData)(ref result)).jitterOffsetX = 0f;
((DLSSCommandExecutionData)(ref result)).jitterOffsetY = 0f;
((DLSSCommandExecutionData)(ref result)).preExposure = 1f;
((DLSSCommandExecutionData)(ref result)).invertYAxis = (SystemInfo.graphicsUVStartsAtTop ? 1u : 0u);
((DLSSCommandExecutionData)(ref result)).invertXAxis = 0u;
((DLSSCommandExecutionData)(ref result)).reset = (_resetHistory ? 1 : 0);
return result;
}
private static DLSSQuality ToDLSSQuality(DLSSMode mode)
{
//IL_001b: Unknown result type (might be due to invalid IL or missing references)
//IL_001f: Unknown result type (might be due to invalid IL or missing references)
//IL_0023: Unknown result type (might be due to invalid IL or missing references)
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_002c: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
return (DLSSQuality)(mode switch
{
DLSSMode.Balanced => 1,
DLSSMode.Performance => 0,
DLSSMode.UltraPerformance => 3,
DLSSMode.DLAA => 4,
_ => 2,
});
}
}
private StonewardsDLSSPass _pass;
private Camera? _targetCamera;
public override void Create()
{
if (_pass == null)
{
_pass = new StonewardsDLSSPass();
}
}
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
if (Plugin.Instance.ConfigurationHandler.DLSSEnabled && !((Object)(object)_targetCamera == (Object)null) && !((Object)(object)((CameraData)(ref renderingData.cameraData)).camera != (Object)(object)_targetCamera))
{
if (_pass == null)
{
_pass = new StonewardsDLSSPass();
}
renderer.EnqueuePass((ScriptableRenderPass)(object)_pass);
}
}
public void SetTargetCamera(Camera? camera)
{
_targetCamera = camera;
}
public void ResetHistory()
{
_pass?.ResetHistory();
}
public void SetDLSSActive(bool active)
{
if (!active)
{
_pass?.Dispose();
}
((ScriptableRendererFeature)this).SetActive(active);
}
protected override void Dispose(bool disposing)
{
_pass?.Dispose();
((ScriptableRendererFeature)this).Dispose(disposing);
}
}
}
namespace Stonewards_Visuals.Patches
{
[HarmonyPatch(typeof(ResolutionManager), "Start")]
internal static class ResolutionManagerStartPatch
{
private static int _gameLastTargetHeight = 432;
private static bool _renderScaleOverrideActive;
private static bool _applyingTargetHeight;
internal static bool IsApplyingTargetHeight => _applyingTargetHeight;
[HarmonyPostfix]
private static void Postfix(ResolutionManager __instance)
{
if (!((Object)(object)Plugin.Instance == (Object)null))
{
Plugin.Instance.Settings.SetAllSettings();
ApplyTargetHeightFromRenderScale(__instance);
}
}
internal static void ApplyTargetHeightFromRenderScale(ResolutionManager? instance = null)
{
if ((Object)(object)Plugin.Instance == (Object)null || !Plugin.Instance.ConfigurationHandler.EnableRenderScale)
{
return;
}
ResolutionManager val = instance ?? ResolutionManager.Instance;
if ((Object)(object)val == (Object)null || Screen.height <= 0)
{
return;
}
if (!_renderScaleOverrideActive)
{
_gameLastTargetHeight = ResolutionManager.CurrentTargetHeight;
_renderScaleOverrideActive = true;
}
float activeRenderScale = GetActiveRenderScale();
int num = Mathf.Max(1, Mathf.RoundToInt((float)Screen.height * activeRenderScale));
if (ResolutionManager.CurrentTargetHeight == num)
{
return;
}
_applyingTargetHeight = true;
try
{
ResolutionManager.CurrentTargetHeight = num;
}
finally
{
_applyingTargetHeight = false;
}
}
internal static void RestoreGameTargetHeight()
{
if (_renderScaleOverrideActive)
{
ResolutionManager.CurrentTargetHeight = _gameLastTargetHeight;
_renderScaleOverrideActive = false;
}
}
private static float GetActiveRenderScale()
{
if (!Plugin.Instance.ConfigurationHandler.DLSSEnabled)
{
return Plugin.Instance.ConfigurationHandler.RenderScale;
}
return Settings.GetDLSSRenderScale(Plugin.Instance.ConfigurationHandler.DLSSMode);
}
}
[HarmonyPatch(typeof(ResolutionManager), "UpdateRenderScale")]
internal static class ResolutionManagerUpdateRenderScalePatch
{
[HarmonyPostfix]
private static void Postfix(ResolutionManager __instance)
{
if (!((Object)(object)Plugin.Instance == (Object)null) && Plugin.Instance.ConfigurationHandler.EnableRenderScale && !ResolutionManagerStartPatch.IsApplyingTargetHeight)
{
ResolutionManagerStartPatch.ApplyTargetHeightFromRenderScale(__instance);
}
}
}
}
namespace Stonewards_Visuals.Configuration
{
public sealed class ConfigurationHandler
{
private ConfigFile _config;
public ConfigEntry<bool> ConfigEnableRenderScale;
public ConfigEntry<float> ConfigRenderScale;
public ConfigEntry<int> ConfigUpscalingFilter;
public ConfigEntry<int> ConfigDLSSMode;
public ConfigEntry<int> ConfigDLSSPreset;
public ConfigEntry<bool> ConfigDLSSJitter;
public ConfigEntry<float> ConfigDLSSJitterStrength;
public ConfigEntry<float> ConfigLODQuality;
public ConfigEntry<string> ConfigMenuKey;
public ConfigEntry<int> ConfigShadowDistance;
public ConfigEntry<int> ConfigShadowCascades;
public ConfigEntry<int> ConfigShadowmapResolution;
public ConfigEntry<bool> ConfigSoftShadows;
public ConfigEntry<bool> ConfigAnisotropicFiltering;
public ConfigEntry<int> ConfigCameraAA;
public ConfigEntry<int> ConfigMSAA;
public InputAction? MenuAction { get; set; }
public bool EnableRenderScale => ConfigEnableRenderScale.Value;
public float RenderScale => ConfigRenderScale.Value;
public int UpscalingFilter => ConfigUpscalingFilter.Value;
internal DLSSMode DLSSMode => (DLSSMode)ConfigDLSSMode.Value;
internal DLSSPresetMode DLSSPresetMode => (DLSSPresetMode)ConfigDLSSPreset.Value;
public bool DLSSJitterEnabled => ConfigDLSSJitter.Value;
public float DLSSJitterStrength => ConfigDLSSJitterStrength.Value;
public bool DLSSEnabled
{
get
{
if (Plugin.Instance.UpscalerLibAvailable)
{
return ConfigDLSSMode.Value != 0;
}
return false;
}
}
public float LodQuality => ConfigLODQuality.Value;
public int ShadowDistance => ConfigShadowDistance.Value;
public int ShadowCascades => ConfigShadowCascades.Value;
public int ShadowmapResolution => ConfigShadowmapResolution.Value;
public bool SoftShadows => ConfigSoftShadows.Value;
public bool AnisotropicFiltering => ConfigAnisotropicFiltering.Value;
public int CameraAA => ConfigCameraAA.Value;
public int MSAA => ConfigMSAA.Value;
public ConfigurationHandler(ConfigFile configFile)
{
_config = configFile;
Plugin.Log.LogInfo((object)"ConfigurationHandler initialising");
ConfigEnableRenderScale = Bind("Scaling", "EnableRenderScale", defaultValue: false, "Allows Stonewards Visuals to override the game's internal render scale. When off, the game controls pixelisation and render resolution.", delegate
{
Plugin.Instance.Settings.SetResolutionScale();
});
ConfigRenderScale = Bind("Scaling", "RenderScale", 1f, "Controls the render scale of the game. Native is 1.0 (100%). Range 0.1-2.0", delegate
{
Plugin.Instance.Settings.SetResolutionScale();
}, (float v) => Mathf.Clamp(v, 0.1f, 2f));
ConfigUpscalingFilter = Bind("Scaling", "UpscalingFilter", 1, "Controls what filter the game uses to scale to your monitor resolution. 0 = auto, 1 = linear, 2 = point, 3 = FSR 1.0, 4 = STP", delegate
{
Plugin.Instance.Settings.SetUpscaler();
}, (int v) => Mathf.Clamp(v, 0, 4));
ConfigDLSSMode = Bind("Scaling", "DLSSMode", 0, "Controls NVIDIA DLSS, requires an Nvidia RTX GPU! 0 = Off, 1 = Quality, 2 = Balanced, 3 = Performance, 4 = Ultra Performance, 5 = DLAA.", delegate
{
Plugin.Instance.Settings.SetDLSS();
}, (int v) => Mathf.Clamp(v, 0, 5));
ConfigDLSSPreset = Bind("Scaling", "DLSSPreset", 2, "Controls the DLSS render preset, experiment to your taste M and K are pretty good. 0 = Preset F, 1 = Preset J, 2 = Preset K, 3 = Preset L, 4 = Preset M.", delegate
{
Plugin.Instance.Settings.SetDLSS();
});
ConfigDLSSJitter = Bind("Scaling", "DLSSJitter", defaultValue: true, "Applies sub-pixel projection jitter for DLSS temporal accumulation.", delegate
{
Plugin.Instance.Settings.SetDLSS();
});
ConfigDLSSJitterStrength = Bind("Scaling", "DLSSJitterStrength", 0.4f, "Controls the jitter for DLSS, essentially turn it up until you see shaking or a decrease in visual quality.", delegate
{
Plugin.Instance.Settings.SetDLSS();
}, (float v) => Mathf.Clamp(v, 0f, 1f));
ConfigLODQuality = Bind("LOD", "LODQuality", 2.5f, "Controls the game's LOD bias. Higher values increase detail distance. Range 0.1-10.", delegate
{
Plugin.Instance.Settings.SetLODQuality();
}, (float v) => Mathf.Clamp(v, 0.1f, 10f));
ConfigShadowDistance = Bind("Shadows", "ShadowDistance", 300, "Controls the maximum distance at which shadows render. Range 0-1000.", delegate
{
Plugin.Instance.Settings.SetShadowDistance();
}, (int v) => Mathf.Clamp(v, 0, 1000));
ConfigShadowCascades = Bind("Shadows", "ShadowCascades", 4, "Controls directional-light shadow cascades. Stonewards URP supports 1-4.", delegate
{
Plugin.Instance.Settings.SetShadowCascades();
}, (int v) => Mathf.Clamp(v, 1, 4));
ConfigShadowmapResolution = Bind("Shadows", "ShadowmapResolution", 4096, "Controls the quality of the shadows, can reduce performance so turn it down if you're having issues. Makes the trees less wobbly", delegate
{
Plugin.Instance.Settings.SetShadowmapResolution();
}, (int v) => Mathf.Clamp(v, 1024, 20480));
ConfigSoftShadows = Bind("Shadows", "SoftShadows", defaultValue: true, "Allows shadows to be soft, if your PC is too low spec for a high shadowmap setting this to false can stop the wobblyness of the shadows (but will result in a pixelly effect if the shadowmap res is low)", delegate
{
Plugin.Instance.Settings.SetSoftShadows();
});
ConfigAnisotropicFiltering = Bind("Quality", "AnisotropicFiltering", defaultValue: true, "Helps texture sharpness at angles (set to on)", delegate
{
Plugin.Instance.Settings.SetAnisotropicFiltering();
});
ConfigCameraAA = Bind("AntiAliasing", "CameraAA", 2, "Controls camera anti-aliasing. 0 = None, 1 = FXAA, 2 = SMAA, 3 = TAA.", delegate
{
Plugin.Instance.Settings.SetPostProcessAA();
}, (int v) => Mathf.Clamp(v, 0, 3));
ConfigMSAA = Bind("AntiAliasing", "MSAA", 8, "Controls multi-sample anti-aliasing. Valid values are 0, 2, 4, and 8.", delegate
{
Plugin.Instance.Settings.SetMSAA();
}, (int v) => (v > 0) ? ((v > 2) ? ((v > 4) ? 8 : 4) : 2) : 0);
if (MSAA != 0 && CameraAA == 3)
{
ConfigCameraAA.Value = 2;
}
ConfigMenuKey = Bind("General", "Config Menu Key", "<Keyboard>/f11", "Control path for opening the mod configuration menu (e.g. <Keyboard>/f2, <Keyboard>/space, <Keyboard>/escape)", SetupInputAction);
SetupInputAction();
Plugin.Log.LogInfo((object)"ConfigurationHandler initialised");
}
public void ForceDLSSOff()
{
ConfigDLSSMode.Value = 0;
ConfigDLSSJitter.Value = false;
}
private ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, string description, Action? onChanged = null, Func<T, T>? clamp = null)
{
ConfigEntry<T> entry = _config.Bind<T>(section, key, defaultValue, description);
if (clamp != null)
{
entry.Value = clamp(entry.Value);
}
Plugin.Log.LogInfo((object)$"{key} set to: {entry.Value}");
if (onChanged != null)
{
entry.SettingChanged += delegate
{
if (clamp != null)
{
entry.Value = clamp(entry.Value);
}
onChanged();
};
}
return entry;
}
private void SetupInputAction()
{
//IL_0018: Unknown result type (might be due to invalid IL or missing references)
//IL_0022: Expected O, but got Unknown
//IL_0036: Unknown result type (might be due to invalid IL or missing references)
InputAction? menuAction = MenuAction;
if (menuAction != null)
{
menuAction.Dispose();
}
MenuAction = new InputAction((string)null, (InputActionType)1, (string)null, (string)null, (string)null, (string)null);
InputActionSetupExtensions.AddBinding(MenuAction, ConfigMenuKey.Value, (string)null, (string)null, (string)null);
MenuAction.Enable();
}
public void Dispose()
{
InputAction? menuAction = MenuAction;
if (menuAction != null)
{
menuAction.Dispose();
}
MenuAction = null;
}
}
public class ModConfigurationUI : MonoBehaviour
{
private List<Option> _options = new List<Option>();
private bool _visible;
private int _selectedIndex;
private bool _prevCursorVisible;
private CursorLockMode _prevCursorLock;
private bool _waitingForBinding;
private Option? _bindingTarget;
private Texture2D _whiteTex;
private GUIStyle _titleStyle;
private GUIStyle _rowStyle;
private GUIStyle _hintStyle;
private string titleText = "Stonewards Visuals Settings | v " + Plugin.Version;
private string hintText = "F11: Open/Close • Tab or ↑/↓: Move • Enter/Click: Change • Scroll Wheel or ←/→ Arrows: Adjust Numerical Values • +/-: Scale Menu";
private int RowHeight = 32;
private int PanelWidth = 460;
private int Pad = 12;
private int TitleFontSize = 22;
private int OptionFontSize = 16;
private int HintFontSize = 14;
private Color GetColor(Color c)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
//IL_0007: Invalid comparison between Unknown and I4
//IL_0011: Unknown result type (might be due to invalid IL or missing references)
//IL_000b: Unknown result type (might be due to invalid IL or missing references)
if ((int)SystemInfo.graphicsDeviceType == 21)
{
return ((Color)(ref c)).linear;
}
return c;
}
private void CalculatePanelWidth()
{
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
//IL_0016: Expected O, but got Unknown
//IL_0011: Unknown result type (might be due to invalid IL or missing references)
//IL_0053: Unknown result type (might be due to invalid IL or missing references)
//IL_005d: Expected O, but got Unknown
//IL_0058: Unknown result type (might be due to invalid IL or missing references)
float num = _titleStyle.CalcSize(new GUIContent(titleText)).x;
foreach (Option option in _options)
{
float x = _rowStyle.CalcSize(new GUIContent(option.Label + ": " + option.DisplayValue())).x;
if (x > num)
{
num = x;
}
}
int num2 = CalculateHintWidth();
num = Mathf.Max(num, (float)num2);
PanelWidth = Mathf.Clamp((int)num + Pad * 2, 460, Screen.width - Pad * 2);
}
private int CalculateHintWidth()
{
//IL_000b: Unknown result type (might be due to invalid IL or missing references)
//IL_001a: Expected O, but got Unknown
//IL_0037: Unknown result type (might be due to invalid IL or missing references)
//IL_0043: Expected O, but got Unknown
float num = _hintStyle.CalcHeight(new GUIContent("Test"), 9999f);
float num2 = num * 2f;
for (int i = 200; i < Screen.width - Pad * 2; i += 20)
{
float num3 = _hintStyle.CalcHeight(new GUIContent(hintText), (float)i);
if (num3 <= num2)
{
return i;
}
}
return Screen.width - Pad * 2;
}
private void Scale(int scale)
{
if (scale >= 0 || HintFontSize > 8)
{
TitleFontSize += scale * 2;
OptionFontSize += scale * 2;
HintFontSize += scale * 2;
RowHeight = OptionFontSize + 16;
CalculatePanelWidth();
}
}
public void Init(List<Option> options)
{
_options = options ?? new List<Option>();
_selectedIndex = 0;
hintText = Plugin.Instance.ConfigurationHandler.ConfigMenuKey.Value.Split("/")[^1].ToUpper() + ": Open/Close • Tab or ↑/↓: Move • Enter/Click: Change • Scroll Wheel or ←/→ Arrows: Adjust Numerical Values • +/-: Scale Menu";
}
private void EnsureStyles()
{
//IL_004b: Unknown result type (might be due to invalid IL or missing references)
//IL_0050: Unknown result type (might be due to invalid IL or missing references)
//IL_005c: Unknown result type (might be due to invalid IL or missing references)
//IL_0063: Unknown result type (might be due to invalid IL or missing references)
//IL_006f: Expected O, but got Unknown
//IL_007a: Unknown result type (might be due to invalid IL or missing references)
//IL_007f: Unknown result type (might be due to invalid IL or missing references)
//IL_0086: Unknown result type (might be due to invalid IL or missing references)
//IL_0092: Unknown result type (might be due to invalid IL or missing references)
//IL_0099: Unknown result type (might be due to invalid IL or missing references)
//IL_00a3: Expected O, but got Unknown
//IL_00a8: Expected O, but got Unknown
//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
//IL_00d7: Expected O, but got Unknown
//IL_0013: Unknown result type (might be due to invalid IL or missing references)
//IL_001d: Expected O, but got Unknown
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)_whiteTex == (Object)null)
{
_whiteTex = new Texture2D(1, 1, (TextureFormat)4, false);
_whiteTex.SetPixel(0, 0, GetColor(Color.white));
_whiteTex.Apply();
}
_titleStyle = new GUIStyle(GUI.skin.label)
{
fontSize = TitleFontSize,
alignment = (TextAnchor)3,
fontStyle = (FontStyle)1
};
_rowStyle = new GUIStyle(GUI.skin.button)
{
alignment = (TextAnchor)3,
fontSize = OptionFontSize,
padding = new RectOffset(10, 10, 4, 4)
};
_hintStyle = new GUIStyle(GUI.skin.label)
{
fontSize = HintFontSize,
alignment = (TextAnchor)3,
wordWrap = true
};
}
private void Update()
{
//IL_0024: Unknown result type (might be due to invalid IL or missing references)
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
//IL_002c: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
//IL_0202: Unknown result type (might be due to invalid IL or missing references)
if (_waitingForBinding && ((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame)
{
Enumerator<KeyControl> enumerator = Keyboard.current.allKeys.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
KeyControl current = enumerator.Current;
if (((ButtonControl)current).wasPressedThisFrame)
{
string path = ((InputControl)current).path;
_bindingTarget.StringEntry.Value = path;
Plugin.Log.LogInfo((object)("Rebound " + _bindingTarget.Label + " to " + path));
_waitingForBinding = false;
hintText = _bindingTarget.DisplayValue() + ": Open/Close • Tab or ↑/↓: Move • Enter/Click: Change • Scroll Wheel or ←/→ Arrows: Adjust Numerical Values • +/-: Scale Menu";
_bindingTarget = null;
break;
}
}
return;
}
finally
{
((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
}
}
if (Plugin.Instance.ConfigurationHandler.MenuAction != null && Plugin.Instance.ConfigurationHandler.MenuAction.WasPerformedThisFrame())
{
_visible = !_visible;
if (_visible)
{
OnOpened();
}
else
{
OnClosed();
}
}
if (_visible && _options.Count != 0)
{
if (Input.GetKeyDown((KeyCode)9))
{
bool flag = Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303);
CycleSelection((!flag) ? 1 : (-1));
}
if (Input.GetKeyDown((KeyCode)61) || Input.GetKeyDown((KeyCode)43))
{
Scale(1);
}
if (Input.GetKeyDown((KeyCode)45))
{
Scale(-1);
}
if (Input.GetKeyDown((KeyCode)273))
{
CycleSelection(-1);
}
if (Input.GetKeyDown((KeyCode)274))
{
CycleSelection(1);
}
if (Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271))
{
ToggleSelected();
}
if (Input.GetKeyDown((KeyCode)276))
{
AdjustNumerical(-1);
}
if (Input.GetKeyDown((KeyCode)275))
{
AdjustNumerical(1);
}
float y = ((InputControl<Vector2>)(object)Mouse.current.scroll).ReadValue().y;
if (y > 0f)
{
AdjustNumerical(1);
}
else if (y < 0f)
{
AdjustNumerical(-1);
}
}
}
private void ToggleSelected()
{
Option option = _options[_selectedIndex];
if (option.IsDisabled())
{
return;
}
switch (option.Type)
{
case Option.OptionType.Bool:
option.BoolEntry.Value = !option.BoolEntry.Value;
break;
case Option.OptionType.Int:
{
int num2 = option.IntEntry.Value + option.Step;
if (num2 > option.MaxInt)
{
num2 = option.MinInt;
}
option.IntEntry.Value = num2;
break;
}
case Option.OptionType.Float:
{
float num = option.FloatEntry.Value + option.FloatStep;
if (num > option.MaxFloat)
{
num = option.MinFloat;
}
option.FloatEntry.Value = num;
break;
}
case Option.OptionType.InputAction:
_waitingForBinding = true;
_bindingTarget = option;
break;
case Option.OptionType.String:
break;
}
}
private void AdjustNumerical(int delta)
{
Option option = _options[_selectedIndex];
if (!option.IsDisabled())
{
if (option.Type == Option.OptionType.Int)
{
int value = Mathf.Clamp(option.IntEntry.Value + delta * option.Step, option.MinInt, option.MaxInt);
option.IntEntry.Value = value;
}
else if (option.Type == Option.OptionType.Float)
{
float value2 = Mathf.Clamp(option.FloatEntry.Value + (float)delta * option.FloatStep, option.MinFloat, option.MaxFloat);
option.FloatEntry.Value = value2;
}
}
}
private void OnOpened()
{
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
//IL_0011: Unknown result type (might be due to invalid IL or missing references)
_prevCursorVisible = Cursor.visible;
_prevCursorLock = Cursor.lockState;
Cursor.visible = true;
Cursor.lockState = (CursorLockMode)0;
if (_options.Count > 0 && _options[_selectedIndex].IsDisabled())
{
CycleSelection(1);
}
}
private void OnClosed()
{
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
Cursor.visible = _prevCursorVisible;
Cursor.lockState = _prevCursorLock;
}
private void CycleSelection(int delta)
{
if (_options.Count == 0)
{
return;
}
int selectedIndex = _selectedIndex;
do
{
_selectedIndex = (_selectedIndex + delta) % _options.Count;
if (_selectedIndex < 0)
{
_selectedIndex += _options.Count;
}
}
while (_options[_selectedIndex].IsDisabled() && _selectedIndex != selectedIndex);
}
private void OnGUI()
{
//IL_0021: Unknown result type (might be due to invalid IL or missing references)
//IL_003b: Expected O, but got Unknown
//IL_005d: Unknown result type (might be due to invalid IL or missing references)
//IL_006c: Expected O, but got Unknown
//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
//IL_00db: Unknown result type (might be due to invalid IL or missing references)
//IL_011c: Unknown result type (might be due to invalid IL or missing references)
//IL_018c: Unknown result type (might be due to invalid IL or missing references)
//IL_0329: Unknown result type (might be due to invalid IL or missing references)
//IL_0284: Unknown result type (might be due to invalid IL or missing references)
//IL_01df: Unknown result type (might be due to invalid IL or missing references)
//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
//IL_0249: Unknown result type (might be due to invalid IL or missing references)
//IL_024e: Unknown result type (might be due to invalid IL or missing references)
//IL_0258: Unknown result type (might be due to invalid IL or missing references)
//IL_0265: Unknown result type (might be due to invalid IL or missing references)
//IL_026f: Unknown result type (might be due to invalid IL or missing references)
if (!_visible)
{
return;
}
EnsureStyles();
CalculatePanelWidth();
float num = _titleStyle.CalcHeight(new GUIContent(titleText), (float)(PanelWidth - Pad * 2));
float num2 = _options.Count * (RowHeight + 4);
float num3 = _hintStyle.CalcHeight(new GUIContent("Test"), 9999f);
float num4 = num3 * 2f;
int num5 = Pad + (int)num + 8 + (int)num2 + Pad + (int)num4;
Rect val = default(Rect);
((Rect)(ref val))..ctor(20f, 20f, (float)PanelWidth, (float)num5);
GUI.color = GetColor(new Color(0f, 0f, 0f, 0.75f));
GUI.DrawTexture(val, (Texture)(object)_whiteTex);
GUI.color = Color.white;
Rect val2 = default(Rect);
((Rect)(ref val2))..ctor(((Rect)(ref val)).x + (float)Pad, ((Rect)(ref val)).y + (float)Pad, ((Rect)(ref val)).width - (float)(Pad * 2), num);
GUI.Label(val2, titleText, _titleStyle);
float num6 = ((Rect)(ref val2)).yMax + 8f;
Rect val3 = default(Rect);
for (int i = 0; i < _options.Count; i++)
{
((Rect)(ref val3))..ctor(((Rect)(ref val)).x + (float)Pad, num6, ((Rect)(ref val)).width - (float)(Pad * 2), (float)RowHeight);
Option option = _options[i];
if (((Rect)(ref val3)).Contains(Event.current.mousePosition) && !option.IsDisabled())
{
_selectedIndex = i;
}
if (i == _selectedIndex && !option.IsDisabled())
{
GUI.color = GetColor(new Color(1f, 1f, 1f, 0.24f));
GUI.DrawTexture(val3, (Texture)(object)_whiteTex);
GUI.color = Color.white;
}
GUI.enabled = !option.IsDisabled();
if (option.Label == "Menu Key" && _waitingForBinding)
{
GUI.color = GetColor(new Color(0f, 0f, 0f, 0.6f));
GUI.DrawTexture(val3, (Texture)(object)_whiteTex);
GUI.color = Color.white;
GUI.Button(val3, "Press any key...", _rowStyle);
}
else if (GUI.Button(val3, option.Label + ": " + option.DisplayValue(), _rowStyle) && !option.IsDisabled())
{
ToggleSelected();
}
GUI.enabled = true;
num6 += (float)(RowHeight + 4);
}
Rect val4 = default(Rect);
((Rect)(ref val4))..ctor(((Rect)(ref val)).x + (float)Pad, ((Rect)(ref val)).yMax - (float)Pad - num4, ((Rect)(ref val)).width - (float)(Pad * 2), num4);
GUI.Label(val4, hintText, _hintStyle);
}
private void OnDestroy()
{
if ((Object)(object)_whiteTex != (Object)null)
{
Object.Destroy((Object)(object)_whiteTex);
_whiteTex = null;
}
}
}
public class Option
{
public enum OptionType
{
Bool,
Int,
String,
InputAction,
Float
}
public string Label { get; set; }
public OptionType Type { get; set; }
public ConfigEntry<bool> BoolEntry { get; set; }
public ConfigEntry<int> IntEntry { get; set; }
public ConfigEntry<string> StringEntry { get; set; }
public int MinInt { get; set; }
public int MaxInt { get; set; }
public int Step { get; set; }
public Func<bool> IsDisabled { get; set; } = () => false;
public Func<string> DisplayValue { get; set; } = () => "";
public ConfigEntry<float> FloatEntry { get; set; }
public float MinFloat { get; set; }
public float MaxFloat { get; set; }
public float FloatStep { get; set; }
private Option(string label, OptionType type)
{
Label = label;
Type = type;
}
public static Option Float(string label, ConfigEntry<float> entry, float min, float max, float step = 0.05f, Func<bool>? isDisabled = null, Func<string>? displayValue = null)
{
return new Option(label, OptionType.Float)
{
FloatEntry = entry,
MinFloat = min,
MaxFloat = max,
FloatStep = step,
IsDisabled = (isDisabled ?? ((Func<bool>)(() => false))),
DisplayValue = (displayValue ?? ((Func<string>)(() => entry.Value.ToString("F3"))))
};
}
public static Option Bool(string label, ConfigEntry<bool> entry, Func<bool>? isDisabled = null)
{
return new Option(label, OptionType.Bool)
{
BoolEntry = entry,
IsDisabled = (isDisabled ?? ((Func<bool>)(() => false))),
DisplayValue = () => (!entry.Value) ? "OFF" : "ON"
};
}
public static Option InputAction(string label, ConfigEntry<string> entry, Func<bool>? isDisabled = null)
{
return new Option(label, OptionType.InputAction)
{
StringEntry = entry,
IsDisabled = (isDisabled ?? ((Func<bool>)(() => false))),
DisplayValue = delegate
{
string[] array = entry.Value.Split("/");
return (array.Length <= 1) ? entry.Value : array[^1].ToUpper();
}
};
}
public static Option Int(string label, ConfigEntry<int> entry, int min, int max, int step = 1, Func<bool>? isDisabled = null, Func<string>? displayValue = null)
{
return new Option(label, OptionType.Int)
{
IntEntry = entry,
MinInt = min,
MaxInt = max,
Step = step,
IsDisabled = (isDisabled ?? ((Func<bool>)(() => false))),
DisplayValue = (displayValue ?? ((Func<string>)(() => entry.Value.ToString())))
};
}
}
}
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
internal sealed class IgnoresAccessChecksToAttribute : Attribute
{
public IgnoresAccessChecksToAttribute(string assemblyName)
{
}
}
}