Decompiled source of Course Mod Jolfing It v1.0.1

CustomHoleLoader.dll

Decompiled 10 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Eflatun.SceneReference;
using HarmonyLib;
using JBooth.MicroSplat;
using Microsoft.CodeAnalysis;
using Mirror;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CustomHoleLoader")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CustomHoleLoader")]
[assembly: AssemblyTitle("CustomHoleLoader")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 CustomHoleLoader
{
	internal static class CustomCourse
	{
		private const string DonutGuid = "062288400701289469e7157fb26e4444";

		public static CourseData Course;

		private static readonly StringTable HoleNameTable = (StringTable)2;

		private static bool done;

		public static void Inject()
		{
			if (done || Plugin.Holes.Count == 0)
			{
				return;
			}
			CourseCollection allCourses = GameManager.AllCourses;
			if (allCourses == null || allCourses.Courses == null || allCourses.Courses.Count == 0 || allCourses.allHoles.Count == 0)
			{
				return;
			}
			done = true;
			try
			{
				InjectInternal(allCourses);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Couldn't add the custom course: {arg}");
			}
		}

		private static void InjectInternal(CourseCollection all)
		{
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Expected O, but got Unknown
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Invalid comparison between Unknown and I4
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Expected I4, but got Unknown
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Invalid comparison between Unknown and I4
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			HoleData val = ((IEnumerable<HoleData>)all.allHoles).FirstOrDefault((Func<HoleData, bool>)((HoleData h) => (Object)(object)h != (Object)null && h.Scene != null && SafeGuid(h.Scene) == "062288400701289469e7157fb26e4444")) ?? all.allHoles[0];
			Course = Object.Instantiate<CourseData>(val.ParentCourse ?? all.Courses[0]);
			((Object)Course).name = Plugin.CourseName.Value;
			((Object)Course).hideFlags = (HideFlags)32;
			Set(Course, "LocalizedName", null);
			Traverse.Create((object)Course).Field("includeAllHoles").SetValue((object)false);
			Traverse.Create((object)Course).Field("difficultyCourse").SetValue((object)false);
			Set(Course, "MenuOrder", all.Courses.Max((CourseData c) => c.MenuOrder) + 1);
			List<HoleData> list = new List<HoleData>();
			foreach (CustomHole hole in Plugin.Holes)
			{
				HoleData val2 = Object.Instantiate<HoleData>(((Object)(object)hole.Data != (Object)null) ? hole.Data : val);
				((Object)val2).name = "Custom_" + hole.Scene;
				((Object)val2).hideFlags = (HideFlags)32;
				RegisterScene(hole);
				Set(val2, "Scene", (object)new SceneReference(hole.Guid));
				Set(val2, "DontShowNewHoleNotification", true);
				if ((int)val2.Difficulty < 0 || (int)val2.Difficulty > 2)
				{
					Set(val2, "Difficulty", Enum.ToObject(((object)val2.Difficulty).GetType(), Mathf.Clamp((int)val2.Difficulty, 0, 2)));
				}
				if ((Object)(object)hole.Data == (Object)null)
				{
					Plugin.Log.LogWarning((object)$"'{hole.Scene}' has no hole data in its pack, so it uses Donut's par ({val2.Par}).");
				}
				Sprite val3 = LoadPicture(hole);
				Set(val2, "ScreenshotsThumbnail", ((Object)(object)val3 != (Object)null) ? new List<Sprite> { val3 } : new List<Sprite>());
				string text = "HOLE_INFO_HoleNameCustom_" + ((Object)val2).name.Replace(" ", "");
				LocalizationManager.AddStringToAllLocales(HoleNameTable, text, hole.Scene);
				Traverse.Create((object)val2).Field("runtimeLocalizedName").SetValue((object)LocalizationManager.GetLocalizedString(HoleNameTable, text));
				Traverse.Create((object)val2).Field("usingCustomLocString").SetValue((object)true);
				list.Add(val2);
			}
			Set(Course, "Holes", list.ToArray());
			Sprite val4 = LoadCourseIcon();
			if ((Object)(object)val4 != (Object)null)
			{
				Set(Course, "CategoryIcon", val4);
			}
			all.Courses.Add(Course);
			foreach (HoleData item in list)
			{
				item.RuntimeInitialize(Course, all.allHoles.Count);
				all.allHolesGlobalIndices[item] = all.allHoles.Count;
				all.allHoles.Add(item);
			}
			Course.RuntimeInitialize();
			Plugin.Log.LogInfo((object)($"Added course '{((Object)Course).name}' (tab {all.Courses.Count}) with {list.Count} hole(s): " + string.Join(", ", list.Select((HoleData h) => $"{((Object)h).name.Substring(7)} (par {h.Par}, #{h.GlobalIndex})"))));
		}

		private static void Set(object o, string prop, object value)
		{
			FieldInfo fieldInfo = AccessTools.Field(o.GetType(), "<" + prop + ">k__BackingField");
			if (fieldInfo == null)
			{
				throw new MissingFieldException(o.GetType().Name, prop);
			}
			fieldInfo.SetValue(o, value);
		}

		private static string SafeGuid(SceneReference s)
		{
			try
			{
				return s.Guid;
			}
			catch
			{
				return null;
			}
		}

		private static void RegisterScene(CustomHole ch)
		{
			_ = SceneGuidToPathMapProvider.SceneGuidToPathMap;
			Traverse obj = Traverse.Create(typeof(SceneGuidToPathMapProvider));
			obj.Field("_sceneGuidToPathMap").GetValue<Dictionary<string, string>>()[ch.Guid] = ch.ScenePath;
			obj.Field("_scenePathToGuidMap").GetValue<Dictionary<string, string>>()[ch.ScenePath] = ch.Guid;
		}

		private static Sprite LoadCourseIcon()
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			string dir = Path.GetDirectoryName(typeof(CustomCourse).Assembly.Location);
			string text = new string[2] { "CourseIcon.png", "CourseIcon.jpg" }.Select((string f) => Path.Combine(dir, f)).FirstOrDefault(File.Exists);
			if (text == null)
			{
				return null;
			}
			try
			{
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, File.ReadAllBytes(text)))
				{
					return null;
				}
				if (text.EndsWith(".jpg"))
				{
					CutAwayWhiteBackground(val);
				}
				((Object)val).hideFlags = (HideFlags)32;
				Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				((Object)obj).hideFlags = (HideFlags)32;
				Plugin.Log.LogInfo((object)$"Course icon: {text} ({((Texture)val).width}x{((Texture)val).height})");
				return obj;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't load course icon " + text + ": " + ex.Message));
				return null;
			}
		}

		private static void CutAwayWhiteBackground(Texture2D tex)
		{
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			int width = ((Texture)tex).width;
			int height = ((Texture)tex).height;
			Color32[] px = tex.GetPixels32();
			bool[] bg = new bool[px.Length];
			Queue<int> q = new Queue<int>();
			for (int i = 0; i < width; i++)
			{
				Seed(i);
				Seed((height - 1) * width + i);
			}
			for (int j = 0; j < height; j++)
			{
				Seed(j * width);
				Seed(j * width + width - 1);
			}
			while (q.Count > 0)
			{
				int num = q.Dequeue();
				int num2 = num % width;
				int num3 = num / width;
				if (num2 > 0)
				{
					Seed(num - 1);
				}
				if (num2 < width - 1)
				{
					Seed(num + 1);
				}
				if (num3 > 0)
				{
					Seed(num - width);
				}
				if (num3 < height - 1)
				{
					Seed(num + width);
				}
			}
			for (int k = 0; k < px.Length; k++)
			{
				if (bg[k])
				{
					px[k].a = 0;
					continue;
				}
				int num4 = k % width;
				int num5 = k / width;
				if (((num4 > 0 && bg[k - 1]) || (num4 < width - 1 && bg[k + 1]) || (num5 > 0 && bg[k - width]) || (num5 < height - 1 && bg[k + width])) && Whiteish(px[k], 190))
				{
					px[k].a = 110;
				}
			}
			tex.SetPixels32(px);
			tex.Apply();
			void Seed(int num6)
			{
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				if (!bg[num6] && Whiteish(px[num6], 225))
				{
					bg[num6] = true;
					q.Enqueue(num6);
				}
			}
			static bool Whiteish(Color32 c, int lim)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				if (c.r >= lim && c.g >= lim)
				{
					return c.b >= lim;
				}
				return false;
			}
		}

		private static Sprite LoadPicture(CustomHole ch)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (ch.Thumbnail == null)
			{
				if (!((Object)(object)ch.Data != (Object)null) || ch.Data.ScreenshotsThumbnail == null)
				{
					return null;
				}
				return ch.Data.ScreenshotsThumbnail.FirstOrDefault();
			}
			try
			{
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, File.ReadAllBytes(ch.Thumbnail)))
				{
					return null;
				}
				((Object)val).hideFlags = (HideFlags)32;
				Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
				((Object)obj).hideFlags = (HideFlags)32;
				return obj;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't load picture " + ch.Thumbnail + ": " + ex.Message));
				return null;
			}
		}
	}
	[HarmonyPatch(typeof(CourseData), "RuntimeInitialize")]
	internal static class CourseDataInitPatch
	{
		internal static bool lastCourseReady;

		private static void Postfix(CourseData __instance)
		{
			CourseCollection allCourses = GameManager.AllCourses;
			if (allCourses != null && !((Object)(object)__instance == (Object)(object)CustomCourse.Course) && (Object)(object)((IEnumerable<CourseData>)allCourses.Courses).LastOrDefault((Func<CourseData, bool>)((CourseData c) => (Object)(object)c != (Object)(object)CustomCourse.Course && c.ShouldInitCourses)) == (Object)(object)__instance)
			{
				lastCourseReady = true;
			}
		}
	}
	[HarmonyPatch]
	internal static class CourseCollectionLoadedPatch
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.Method(AccessTools.FirstInner(typeof(CourseCollection), (Func<Type, bool>)((Type t) => t.Name.StartsWith("<RuntimeInitialize>"))), "MoveNext", (Type[])null, (Type[])null);
		}

		private static void Postfix()
		{
			if (CourseDataInitPatch.lastCourseReady)
			{
				CustomCourse.Inject();
			}
		}
	}
	[HarmonyPatch(typeof(MatchSetupMenu), "InitializeCourses")]
	internal static class MatchSetupInitPatch
	{
		private static void Prefix()
		{
			CustomCourse.Inject();
		}
	}
	[BepInPlugin("com.pigpooteamelf.customholeloader", "CustomHoleLoader", "1.0.1")]
	public class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		internal static ConfigEntry<string> ReplaceHoleGuid;

		internal static ConfigEntry<string> ReplaceWithScene;

		internal static ConfigEntry<string> TerrainMaterialName;

		internal static ConfigEntry<string> CourseName;

		private static readonly List<AssetBundle> bundles = new List<AssetBundle>();

		internal static readonly List<CustomHole> Holes = new List<CustomHole>();

		private void Awake()
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			CourseName = ((BaseUnityPlugin)this).Config.Bind<string>("General", "CourseName", "Jolfing It", "Name of the extra course tab in Match Setup that holds every custom hole.");
			TerrainMaterialName = ((BaseUnityPlugin)this).Config.Bind<string>("Terrain", "TerrainMaterial", "Regular terrain", "The game's MicroSplat terrain material to use on custom holes (Forest holes use 'Regular terrain').");
			ReplaceHoleGuid = ((BaseUnityPlugin)this).Config.Bind<string>("Testing", "ReplaceRealHoleGuid", "", "Optional: scene GUID of a real hole to swap for a custom one (Donut is 062288400701289469e7157fb26e4444). Empty = off.");
			ReplaceWithScene = ((BaseUnityPlugin)this).Config.Bind<string>("Testing", "ReplaceWithScene", "", "Custom hole scene used by ReplaceRealHoleGuid. Empty = the first one.");
			LoadBundles();
			SceneManager.sceneLoaded += OnSceneLoaded;
			new Harmony("com.pigpooteamelf.customholeloader").PatchAll();
		}

		private void LoadBundles()
		{
			List<string> list = new List<string>();
			try
			{
				list.AddRange((from f in Directory.GetFiles(Paths.PluginPath, "customhole_*", SearchOption.AllDirectories)
					where Path.GetExtension(f) == ""
					select f).Select(Path.GetDirectoryName).Distinct());
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Couldn't search for hole packs: " + ex.Message));
			}
			Dictionary<string, HoleData> dictionary = new Dictionary<string, HoleData>();
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (string item in list.Distinct().OrderBy<string, string>((string d) => d, StringComparer.Ordinal))
			{
				foreach (string item2 in (from f in Directory.GetFiles(item, "customhole_*")
					where Path.GetExtension(f) == ""
					orderby f.EndsWith("_scene") ? 1 : 0
					select f).ThenBy<string, string>((string f) => f, StringComparer.Ordinal).ToList())
				{
					if (!hashSet.Add(Path.GetFileName(item2)))
					{
						Log.LogWarning((object)("Skipped " + item2 + ": a hole bundle with that name is already loaded (installed twice?)"));
						continue;
					}
					AssetBundle val = AssetBundle.LoadFromFile(item2);
					if ((Object)(object)val == (Object)null)
					{
						Log.LogError((object)("Couldn't load bundle " + item2 + " (wrong platform, or the same hole is installed twice?)"));
						continue;
					}
					bundles.Add(val);
					if (!val.isStreamedSceneAssetBundle)
					{
						HoleData[] array = val.LoadAllAssets<HoleData>();
						foreach (HoleData val2 in array)
						{
							dictionary[((Object)val2).name.EndsWith("_HoleData") ? ((Object)val2).name.Substring(0, ((Object)val2).name.Length - 9) : ((Object)val2).name] = val2;
						}
						continue;
					}
					string[] allScenePaths = val.GetAllScenePaths();
					foreach (string text in allScenePaths)
					{
						string name = Path.GetFileNameWithoutExtension(text);
						if (Holes.Any((CustomHole h) => h.Scene == name))
						{
							Log.LogWarning((object)("Two custom holes are called '" + name + "'; ignoring the one in " + item2));
							continue;
						}
						string text2 = Path.Combine(item, name + ".png");
						Holes.Add(new CustomHole
						{
							Scene = name,
							ScenePath = text,
							Guid = CustomHole.MakeGuid(name),
							Thumbnail = (File.Exists(text2) ? text2 : null)
						});
					}
				}
			}
			Holes.Sort((CustomHole a, CustomHole c) => string.CompareOrdinal(a.Scene, c.Scene));
			foreach (CustomHole hole in Holes)
			{
				dictionary.TryGetValue(hole.Scene, out hole.Data);
				Log.LogInfo((object)("Custom hole '" + hole.Scene + "' (" + hole.ScenePath + "): par " + (((Object)(object)hole.Data != (Object)null) ? hole.Data.Par.ToString() : "? (no hole data)") + ", picture " + ((hole.Thumbnail != null) ? "yes" : "no") + ", id " + hole.Guid));
			}
			if (Holes.Count == 0)
			{
				Log.LogWarning((object)"No custom holes found.");
			}
		}

		internal static CustomHole FindByGuid(string guid)
		{
			return Holes.FirstOrDefault((CustomHole h) => h.Guid == guid);
		}

		internal static bool IsCustom(Scene s)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (((Scene)(ref s)).IsValid())
			{
				return Holes.Any((CustomHole h) => h.Scene == ((Scene)(ref s)).name);
			}
			return false;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			Log.LogInfo((object)("Scene loaded: '" + ((Scene)(ref scene)).name + "' (" + ((Scene)(ref scene)).path + ")"));
			if (IsCustom(scene))
			{
				HoleFixer.FixTerrain(scene);
				HoleFixer.FixShaders(scene);
			}
			else
			{
				RealAssets.Collect();
			}
		}
	}
	internal class CustomHole
	{
		public string Scene;

		public string ScenePath;

		public string Guid;

		public string Thumbnail;

		public HoleData Data;

		public static string MakeGuid(string scene)
		{
			using MD5 mD = MD5.Create();
			return string.Concat(from x in mD.ComputeHash(Encoding.UTF8.GetBytes("customhole:" + scene))
				select x.ToString("x2"));
		}
	}
	[HarmonyPatch(typeof(NetworkManager), "ServerChangeScene")]
	internal static class ServerChangeScenePatch
	{
		private static void Prefix(ref string __0)
		{
			Plugin.Log.LogInfo((object)("ServerChangeScene('" + __0 + "')"));
			if (__0 == null || !__0.StartsWith("addr:/"))
			{
				return;
			}
			string text = __0.Substring(6);
			CustomHole customHole = Plugin.FindByGuid(text);
			string text2 = Plugin.ReplaceHoleGuid.Value.Trim();
			if (customHole == null && text2.Length > 0 && text == text2)
			{
				string want = Plugin.ReplaceWithScene.Value.Trim();
				customHole = Plugin.Holes.FirstOrDefault((CustomHole h) => want.Length == 0 || h.Scene.Equals(want, StringComparison.OrdinalIgnoreCase));
			}
			if (customHole != null)
			{
				RealAssets.Collect();
				Plugin.Log.LogInfo((object)("Loading custom hole '" + customHole.Scene + "' for '" + __0 + "'"));
				__0 = customHole.Scene;
			}
		}
	}
	[HarmonyPatch(typeof(IngameSceneBootstrap), "Awake")]
	internal static class BootstrapAwakePatch
	{
		private static void Prefix(IngameSceneBootstrap __instance)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.IsCustom(((Component)__instance).gameObject.scene))
			{
				return;
			}
			HoleFixer.FixTerrain(((Component)__instance).gameObject.scene);
			Traverse val = Traverse.Create((object)__instance).Field("entitySpawners");
			if (!(val.GetValue() is Array array))
			{
				return;
			}
			List<Object> list = (from Object x in array
				where x != (Object)null
				select x).ToList();
			if (list.Count < array.Length)
			{
				Array array2 = Array.CreateInstance(array.GetType().GetElementType(), list.Count);
				for (int num = 0; num < list.Count; num++)
				{
					array2.SetValue(list[num], num);
				}
				val.SetValue((object)array2);
				ManualLogSource log = Plugin.Log;
				object arg = array.Length - list.Count;
				Scene scene = ((Component)__instance).gameObject.scene;
				log.LogInfo((object)$"Removed {arg} empty spawner slot(s) from '{((Scene)(ref scene)).name}'.");
			}
		}
	}
	[HarmonyPatch(typeof(MicroSplatTerrain), "OnEnable")]
	internal static class MicroSplatOnEnablePatch
	{
		private static void Prefix(MicroSplatTerrain __instance)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.IsCustom(((Component)__instance).gameObject.scene))
			{
				HoleFixer.FixTerrain(((Component)__instance).gameObject.scene);
			}
		}
	}
	internal static class RealAssets
	{
		public static Material TerrainMaterial;

		public static MicroSplatPropData PropData;

		public static MicroSplatKeywords Keywords;

		public static TerrainSettings Settings;

		public static readonly Dictionary<string, TerrainLayer> Layers = new Dictionary<string, TerrainLayer>();

		public static readonly Dictionary<string, Shader> Shaders = new Dictionary<string, Shader>();

		public static readonly HashSet<Shader> ShaderSet = new HashSet<Shader>();

		public static readonly Dictionary<string, Material> Materials = new Dictionary<string, Material>();

		public static readonly HashSet<Material> CustomMaterials = new HashSet<Material>();

		public static readonly HashSet<Shader> CustomShaders = new HashSet<Shader>();

		public const string ErrorShader = "Hidden/InternalErrorShader";

		public static bool IsRealShader(Shader s)
		{
			if ((Object)(object)s != (Object)null && s.isSupported && ((Object)s).name != "Hidden/InternalErrorShader" && ShaderSet.Contains(s))
			{
				return !CustomShaders.Contains(s);
			}
			return false;
		}

		public static void Collect()
		{
			string matName = Plugin.TerrainMaterialName.Value;
			Shader[] array = Resources.FindObjectsOfTypeAll<Shader>();
			foreach (Shader val in array)
			{
				if ((Object)(object)val != (Object)null && val.isSupported && ((Object)val).name != "Hidden/InternalErrorShader" && !CustomShaders.Contains(val) && ShaderSet.Add(val) && !Shaders.ContainsKey(((Object)val).name))
				{
					Shaders[((Object)val).name] = val;
				}
			}
			Material[] array2 = Resources.FindObjectsOfTypeAll<Material>();
			foreach (Material val2 in array2)
			{
				if ((Object)(object)val2 != (Object)null && !CustomMaterials.Contains(val2) && !Materials.ContainsKey(((Object)val2).name) && IsRealShader(val2.shader))
				{
					Materials[((Object)val2).name] = val2;
				}
			}
			if ((Object)(object)TerrainMaterial == (Object)null)
			{
				TerrainMaterial = ((IEnumerable<Material>)Resources.FindObjectsOfTypeAll<Material>()).FirstOrDefault((Func<Material, bool>)((Material m) => ((Object)m).name == matName && (Object)(object)m.shader != (Object)null && m.shader.isSupported));
			}
			if ((Object)(object)PropData == (Object)null)
			{
				PropData = ((IEnumerable<MicroSplatPropData>)Resources.FindObjectsOfTypeAll<MicroSplatPropData>()).FirstOrDefault((Func<MicroSplatPropData, bool>)((MicroSplatPropData p) => ((Object)p).name == matName + "_propdata"));
			}
			if ((Object)(object)Keywords == (Object)null)
			{
				Keywords = ((IEnumerable<MicroSplatKeywords>)Resources.FindObjectsOfTypeAll<MicroSplatKeywords>()).FirstOrDefault((Func<MicroSplatKeywords, bool>)((MicroSplatKeywords k) => ((Object)k).name == matName + "_keywords"));
			}
			if ((Object)(object)Settings == (Object)null)
			{
				Settings = (from t in Resources.FindObjectsOfTypeAll<TerrainSettings>()
					orderby LayerSettings(t).Length descending
					select t).FirstOrDefault();
			}
			if ((Object)(object)Settings != (Object)null)
			{
				TerrainLayerSettings[] array3 = LayerSettings(Settings);
				for (int i = 0; i < array3.Length; i++)
				{
					TerrainLayer value = Traverse.Create((object)array3[i]).Property("LayerAsset", (object[])null).GetValue<TerrainLayer>();
					if ((Object)(object)value != (Object)null && !Layers.ContainsKey(((Object)value).name))
					{
						Layers[((Object)value).name] = value;
					}
				}
			}
			Plugin.Log.LogInfo((object)("Real game assets: terrain material " + (((Object)(object)TerrainMaterial != (Object)null) ? ("'" + ((Object)TerrainMaterial).name + "' (" + ((Object)TerrainMaterial.shader).name + ")") : "not found yet") + ", propdata " + (((Object)(object)PropData != (Object)null) ? "yes" : "no") + ", keywords " + (((Object)(object)Keywords != (Object)null) ? "yes" : "no") + ", " + string.Format("terrain settings {0}, {1} terrain layers, {2} shaders, ", ((Object)(object)Settings != (Object)null) ? ((Object)Settings).name : "no", Layers.Count, Shaders.Count) + string.Format("{0} materials (Ocean: {1}).", Materials.Count, Materials.ContainsKey("Ocean") ? "yes" : "no")));
		}

		public static TerrainLayerSettings[] LayerSettings(TerrainSettings t)
		{
			return (TerrainLayerSettings[])(((object)Traverse.Create((object)t).Property("Layers", (object[])null).GetValue<TerrainLayerSettings[]>()) ?? ((object)new TerrainLayerSettings[0]));
		}
	}
	internal static class HoleFixer
	{
		private const string Tag = "HoleEdit_OriginalShader";

		private static readonly HashSet<int> terrainFixed = new HashSet<int>();

		public static void FixTerrain(Scene scene)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			if (!terrainFixed.Add(SceneHandle.op_Implicit(((Scene)(ref scene)).handle)))
			{
				return;
			}
			foreach (Terrain item in ((Scene)(ref scene)).GetRootGameObjects().SelectMany((GameObject r) => r.GetComponentsInChildren<Terrain>(true)).ToList())
			{
				TerrainData terrainData = item.terrainData;
				if ((Object)(object)terrainData == (Object)null)
				{
					continue;
				}
				TerrainLayer[] terrainLayers = terrainData.terrainLayers;
				List<string> list = new List<string>();
				for (int num = 0; num < terrainLayers.Length; num++)
				{
					if (!((Object)(object)terrainLayers[num] == (Object)null))
					{
						if (RealAssets.Layers.TryGetValue(((Object)terrainLayers[num]).name, out var value))
						{
							terrainLayers[num] = value;
						}
						else
						{
							list.Add(((Object)terrainLayers[num]).name);
						}
					}
				}
				terrainData.terrainLayers = terrainLayers;
				Plugin.Log.LogInfo((object)("Terrain '" + ((Object)item).name + "': layers now " + string.Join(", ", terrainLayers.Select((TerrainLayer l) => (!((Object)(object)l != (Object)null)) ? "null" : ((Object)l).name)) + ((list.Count > 0) ? (" (no real layer for: " + string.Join(", ", list) + ")") : "")));
			}
			foreach (IngameSceneBootstrap item2 in ((Scene)(ref scene)).GetRootGameObjects().SelectMany((GameObject r) => r.GetComponentsInChildren<IngameSceneBootstrap>(true)))
			{
				if ((Object)(object)RealAssets.Settings != (Object)null)
				{
					Traverse.Create((object)item2).Field("terrainSettings").SetValue((object)RealAssets.Settings);
				}
				string value2 = Traverse.Create((object)item2).Field("sceneAssetGuid").GetValue<string>();
				if (string.IsNullOrEmpty(value2))
				{
					continue;
				}
				string text = Path.Combine(Application.streamingAssetsPath, "HoleData", value2 + "_TerrainData.bin");
				try
				{
					if (File.Exists(text))
					{
						File.Delete(text);
						Plugin.Log.LogInfo((object)("Deleted old terrain cache " + text));
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Couldn't delete " + text + ": " + ex.Message));
				}
			}
			foreach (MicroSplatTerrain item3 in ((Scene)(ref scene)).GetRootGameObjects().SelectMany((GameObject r) => r.GetComponentsInChildren<MicroSplatTerrain>(true)))
			{
				if ((Object)(object)RealAssets.TerrainMaterial == (Object)null)
				{
					Plugin.Log.LogError((object)("The game's '" + Plugin.TerrainMaterialName.Value + "' material wasn't found, so the terrain will be pink. Go through the main menu before starting the hole."));
					continue;
				}
				if ((Object)(object)item3.baseMapShader != (Object)null && RealAssets.Shaders.TryGetValue(((Object)item3.baseMapShader).name, out var value3))
				{
					item3.baseMapShader = value3;
				}
				((MicroSplatObject)item3).templateMaterial = RealAssets.TerrainMaterial;
				if ((Object)(object)RealAssets.PropData != (Object)null)
				{
					((MicroSplatObject)item3).propData = RealAssets.PropData;
				}
				if ((Object)(object)RealAssets.Keywords != (Object)null)
				{
					((MicroSplatObject)item3).keywordSO = RealAssets.Keywords;
				}
				if (((Behaviour)item3).isActiveAndEnabled)
				{
					item3.Sync();
				}
				Plugin.Log.LogInfo((object)("MicroSplat terrain '" + ((Object)item3).name + "' now uses the game's '" + ((Object)RealAssets.TerrainMaterial).name + "' (" + ((Object)RealAssets.TerrainMaterial.shader).name + ")."));
			}
		}

		public static void FixShaders(Scene scene)
		{
			List<Renderer> list = ((Scene)(ref scene)).GetRootGameObjects().SelectMany((GameObject r) => r.GetComponentsInChildren<Renderer>(true)).ToList();
			HashSet<Material> hashSet = new HashSet<Material>();
			foreach (Renderer item in list)
			{
				Material[] sharedMaterials = item.sharedMaterials;
				foreach (Material val in sharedMaterials)
				{
					if ((Object)(object)val != (Object)null)
					{
						hashSet.Add(val);
						RealAssets.CustomMaterials.Add(val);
					}
				}
			}
			foreach (Material item2 in hashSet)
			{
				if ((Object)(object)item2.shader != (Object)null && !RealAssets.ShaderSet.Contains(item2.shader))
				{
					RealAssets.CustomShaders.Add(item2.shader);
				}
			}
			HashSet<string> hashSet2 = new HashSet<string>();
			foreach (Renderer item3 in list)
			{
				Material[] sharedMaterials2 = item3.sharedMaterials;
				bool flag = false;
				for (int num2 = 0; num2 < sharedMaterials2.Length; num2++)
				{
					Material val2 = sharedMaterials2[num2];
					if (!((Object)(object)val2 == (Object)null) && RealAssets.Materials.TryGetValue(((Object)val2).name, out var value) && !((Object)(object)value == (Object)(object)val2))
					{
						string text = val2.GetTag("HoleEdit_OriginalShader", false, "");
						if (text.Length == 0 && (Object)(object)val2.shader != (Object)null && ((Object)val2.shader).name != "Hidden/InternalErrorShader")
						{
							text = ((Object)val2.shader).name;
						}
						if (text.Length <= 0 || !(text != ((Object)value.shader).name))
						{
							sharedMaterials2[num2] = value;
							flag = true;
							hashSet2.Add(((Object)val2).name);
						}
					}
				}
				if (flag)
				{
					item3.sharedMaterials = sharedMaterials2;
				}
			}
			Plugin.Log.LogInfo((object)string.Format("Material swap: {0} replaced with the game's own ({1}).", hashSet2.Count, string.Join(", ", hashSet2.OrderBy((string s) => s))));
			hashSet.Clear();
			foreach (Renderer item4 in list)
			{
				Material[] sharedMaterials = item4.sharedMaterials;
				foreach (Material val3 in sharedMaterials)
				{
					if ((Object)(object)val3 != (Object)null)
					{
						hashSet.Add(val3);
					}
				}
			}
			if ((Object)(object)RenderSettings.skybox != (Object)null)
			{
				hashSet.Add(RenderSettings.skybox);
			}
			int num3 = 0;
			int num4 = 0;
			HashSet<string> hashSet3 = new HashSet<string>();
			foreach (Material item5 in hashSet)
			{
				if (RealAssets.IsRealShader(item5.shader) && item5.GetTag("HoleEdit_OriginalShader", false, "").Length == 0)
				{
					num4++;
					continue;
				}
				string text2 = item5.GetTag("HoleEdit_OriginalShader", false, "");
				if (text2.Length == 0 && (Object)(object)item5.shader != (Object)null && ((Object)item5.shader).name != "Hidden/InternalErrorShader")
				{
					text2 = ((Object)item5.shader).name;
				}
				if (text2.Length == 0)
				{
					hashSet3.Add(((Object)item5).name + " (pink error shader, original shader unknown)");
					continue;
				}
				if (!RealAssets.Shaders.TryGetValue(text2, out var value2))
				{
					Shader val4 = Shader.Find(text2);
					value2 = (((Object)(object)val4 != (Object)null && (Object)(object)val4 != (Object)(object)item5.shader && val4.isSupported && !RealAssets.CustomShaders.Contains(val4)) ? val4 : null);
				}
				if ((Object)(object)value2 != (Object)null)
				{
					int renderQueue = item5.renderQueue;
					item5.shader = value2;
					item5.renderQueue = renderQueue;
					num3++;
				}
				else
				{
					hashSet3.Add(((Object)item5).name + " (" + text2 + ")");
				}
			}
			Plugin.Log.LogInfo((object)$"Shader fix: {num3} fixed, {num4} already real, {hashSet3.Count} shader names not found ({hashSet.Count} materials).");
			if (hashSet3.Count > 0)
			{
				Plugin.Log.LogWarning((object)("No game shader loaded for: " + string.Join(", ", hashSet3)));
			}
		}
	}
	[HarmonyPatch]
	internal static class LetBallRollPatch
	{
		private static readonly Dictionary<GolfBall, float> rollingSince = new Dictionary<GolfBall, float>();

		private const float MaxRollSeconds = 12f;

		private const float StillSpeed = 0.25f;

		private static MethodBase TargetMethod()
		{
			return AccessTools.GetDeclaredMethods(typeof(GolfBall)).First((MethodInfo m) => m.Name.Contains("g__ShouldReturnToBounds"));
		}

		internal static bool OnlyOutsideArea(GolfBall ball)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			LevelBoundsTracker value = Traverse.Create((object)ball).Field("levelBoundsTracker").GetValue<LevelBoundsTracker>();
			if ((Object)(object)value != (Object)null && !BoundsStateExtensions.IsInOutOfBoundsHazard(value.AuthoritativeBoundsState))
			{
				return !BallOutOfBoundsTriggerManager.IsBallInOutOfBoundsTrigger(ball);
			}
			return false;
		}

		private static void Postfix(GolfBall __instance, ref bool __result)
		{
			//IL_0017: 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)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (!__result)
			{
				rollingSince.Remove(__instance);
			}
			else
			{
				if (!Plugin.IsCustom(((Component)__instance).gameObject.scene))
				{
					return;
				}
				try
				{
					if (!OnlyOutsideArea(__instance))
					{
						return;
					}
					Rigidbody value = Traverse.Create((object)__instance).Field("rigidbody").GetValue<Rigidbody>();
					int num;
					if (!__instance.IsStationary)
					{
						if ((Object)(object)value != (Object)null)
						{
							Vector3 linearVelocity = value.linearVelocity;
							num = ((((Vector3)(ref linearVelocity)).magnitude < 0.25f) ? 1 : 0);
						}
						else
						{
							num = 0;
						}
					}
					else
					{
						num = 1;
					}
					if (!rollingSince.TryGetValue(__instance, out var value2))
					{
						value2 = (rollingSince[__instance] = Time.time);
					}
					if (num != 0 || Time.time - value2 > 12f)
					{
						rollingSince.Remove(__instance);
					}
					else
					{
						__result = false;
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Roll check failed: " + ex.Message));
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class LetBallLandPatch
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.GetDeclaredMethods(typeof(GolfBall)).First((MethodInfo m) => m.Name.Contains("g__ShouldBeReturnedFromOutOfBounds"));
		}

		private static void Postfix(GolfBall __instance, ref bool __result)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (!__result || !Plugin.IsCustom(((Component)__instance).gameObject.scene))
			{
				return;
			}
			try
			{
				if (LetBallRollPatch.OnlyOutsideArea(__instance))
				{
					__result = false;
					Plugin.Log.LogInfo((object)"Ball landed outside the playable area: letting it roll.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Landing check failed: " + ex.Message));
			}
		}
	}
}