Decompiled source of LobbyRules v1.0.0

BepInEx/plugins/DiceModders.LobbyRules.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using DiceKingdoms.Game;
using DiceKingdoms.Interface;
using DiceModders.ModCore;
using DiceModders.ModCore.Tools;
using DiceModders.UiKit;
using DiceModders.UiKit.Custom;
using DiceModders.UiKit.Native;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Microsoft.CodeAnalysis;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DiceModders")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Gameplay rules the host sets in the lobby for Dice Kingdoms: island size and game values.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DiceModders.LobbyRules")]
[assembly: AssemblyTitle("DiceModders.LobbyRules")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
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 DiceModders.LobbyRules
{
	internal static class CombatPathLimit
	{
		private const int GameLimit = 4000;

		private static readonly byte[] Signature = new byte[8] { 61, 159, 15, 0, 0, 141, 64, 1 };

		private unsafe static byte*[] _sites;

		private static bool _searched;

		private static int _current = 4000;

		internal static void Set(int side, int gameSide)
		{
			Write((side > gameSide && gameSide > 0) ? ((int)Math.Ceiling(4000.0 * ((double)side / (double)gameSide) * ((double)side / (double)gameSide))) : 4000);
		}

		internal static void Reset()
		{
			Write(4000);
		}

		private unsafe static void Write(int limit)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			if (limit == _current)
			{
				return;
			}
			try
			{
				if (!_searched)
				{
					Search();
				}
				if (_sites == null || _sites.Length == 0)
				{
					return;
				}
				byte*[] sites = _sites;
				bool flag = default(bool);
				foreach (byte* ptr in sites)
				{
					if (*(int*)ptr != _current - 1)
					{
						ManualLogSource l = Plugin.L;
						BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(54, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[combat] path limit: unexpected value ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(*(int*)ptr);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (left as it is)");
						}
						l.LogWarning(val);
						return;
					}
				}
				sites = _sites;
				foreach (byte* ptr2 in sites)
				{
					if (!VirtualProtect((IntPtr)ptr2, (UIntPtr)4uL, 64u, out var old))
					{
						throw new InvalidOperationException("VirtualProtect failed");
					}
					*(int*)ptr2 = limit - 1;
					VirtualProtect((IntPtr)ptr2, (UIntPtr)4uL, old, out var _);
					FlushInstructionCache(GetCurrentProcess(), (IntPtr)ptr2, (UIntPtr)4uL);
				}
				ManualLogSource l2 = Plugin.L;
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(49, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[combat] soldier path search limit ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(limit);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" steps (game ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(4000);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(")");
				}
				l2.LogInfo(val2);
				_current = limit;
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[combat] path limit: " + ex.Message));
			}
		}

		private unsafe static void Search()
		{
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			_searched = true;
			IntPtr intPtr = GetModuleHandleW("lib_burst_generated.dll");
			if (intPtr == IntPtr.Zero)
			{
				intPtr = LoadLibraryW(Path.Combine(Application.dataPath, "Plugins", "x86_64", "lib_burst_generated.dll"));
			}
			if (intPtr == IntPtr.Zero)
			{
				Plugin.L.LogWarning((object)"[combat] path limit: Burst library not found");
				return;
			}
			int size;
			byte* ptr = TextSection(intPtr, out size);
			List<IntPtr> list = new List<IntPtr>();
			int i = 0;
			for (int num = size - Signature.Length; i <= num; i++)
			{
				if (ptr[i] == Signature[0])
				{
					int j;
					for (j = 1; j < Signature.Length && ptr[i + j] == Signature[j]; j++)
					{
					}
					if (j == Signature.Length)
					{
						list.Add((IntPtr)(ptr + i + 1));
					}
				}
			}
			if (list.Count != 2)
			{
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(83, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[combat] path limit: found ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(list.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" places instead of 2, game version changed? (not raised)");
				}
				l.LogWarning(val);
			}
			else
			{
				_sites = new byte*[list.Count];
				for (int k = 0; k < list.Count; k++)
				{
					_sites[k] = (byte*)(void*)list[k];
				}
			}
		}

		private unsafe static byte* TextSection(IntPtr module, out int size)
		{
			byte* ptr = (byte*)(void*)module;
			int num = ((int*)ptr)[15];
			int num2 = ((ushort*)(ptr + num))[3];
			int num3 = ((ushort*)(ptr + num))[10];
			byte* ptr2 = ptr + num + 24 + num3;
			int num4 = 0;
			while (num4 < num2)
			{
				if (*ptr2 == 46 && ptr2[1] == 116 && ptr2[2] == 101 && ptr2[3] == 120 && ptr2[4] == 116)
				{
					size = ((int*)ptr2)[2];
					return ptr + ((int*)ptr2)[3];
				}
				num4++;
				ptr2 += 40;
			}
			throw new InvalidOperationException("no .text section");
		}

		[DllImport("kernel32", CharSet = CharSet.Unicode)]
		private static extern IntPtr GetModuleHandleW(string name);

		[DllImport("kernel32", CharSet = CharSet.Unicode)]
		private static extern IntPtr LoadLibraryW(string path);

		[DllImport("kernel32")]
		private static extern bool VirtualProtect(IntPtr address, UIntPtr size, uint protect, out uint old);

		[DllImport("kernel32")]
		private static extern IntPtr GetCurrentProcess();

		[DllImport("kernel32")]
		private static extern bool FlushInstructionCache(IntPtr process, IntPtr address, UIntPtr size);
	}
	internal static class GameValues
	{
		internal static readonly string[] UnitStats = new string[7] { "AttackPeriod", "AttackDelay", "AggroDistance", "Range", "Parry", "BlockArrow", "MissChance" };

		internal static readonly string[] Percent = new string[3] { "Parry", "BlockArrow", "MissChance" };

		internal static readonly string[] Resources = new string[8] { "Food", "Wood", "Stone", "Gold", "Hammer", "Culture", "Military", "Disaster" };

		private static LobbyRule<string> _rule;

		private static UnitStatsMod _units;

		private static BalanceMod _balance;

		private static readonly SortedDictionary<string, int> Values = new SortedDictionary<string, int>(StringComparer.Ordinal);

		internal static bool Editable => _rule.Editable;

		internal static int Count => Values.Count;

		internal static event Action Changed;

		internal static void Install()
		{
			_units = Units.Register("lobbyrules.units", "Edited unit values", 0, "The unit values the host set in the Game values window.");
			_balance = Balance.Register("lobbyrules.balance", "Edited building values", 0, "The building and technology values the host set in the Game values window.");
			_rule = Rules.Text("lobbyrules.values", "Game values", "", (string)null, (Func<bool>)(() => false), true);
			_rule.Changed += delegate
			{
				Load();
			};
			Load();
		}

		internal static int? Get(string key)
		{
			if (!Values.TryGetValue(key, out var value))
			{
				return null;
			}
			return value;
		}

		internal static bool Set(string key, int? value)
		{
			if (!Editable)
			{
				return false;
			}
			SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>(Values, StringComparer.Ordinal);
			if (!value.HasValue)
			{
				sortedDictionary.Remove(key);
			}
			else
			{
				sortedDictionary[key] = value.Value;
			}
			return _rule.TrySet(Encode(sortedDictionary));
		}

		internal static bool ResetAll()
		{
			if (Editable)
			{
				return _rule.TrySet("");
			}
			return false;
		}

		private static string Encode(SortedDictionary<string, int> values)
		{
			return string.Join(";", values.Select((KeyValuePair<string, int> kv) => kv.Key + "=" + kv.Value));
		}

		private static void Load()
		{
			Values.Clear();
			string[] array = (_rule.Value ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries);
			foreach (string text in array)
			{
				int num = text.IndexOf('=');
				if (num > 0 && int.TryParse(text.Substring(num + 1), out var result))
				{
					Values[text.Substring(0, num)] = result;
				}
			}
			try
			{
				Apply();
			}
			catch (Exception ex)
			{
				Plugin.L.LogError((object)("game values: " + ex));
			}
			GameValues.Changed?.Invoke();
		}

		private static void Apply()
		{
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			//IL_0127: Expected O, but got Unknown
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Expected O, but got Unknown
			//IL_01fc: 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_00c7: Expected O, but got Unknown
			//IL_00cc: Expected O, but got Unknown
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Expected O, but got Unknown
			//IL_01ad: Expected O, but got Unknown
			_units.ClearAll();
			_balance.ClearAll();
			Dictionary<(int, int), UnitStatChange> dictionary = new Dictionary<(int, int), UnitStatChange>();
			Dictionary<int, BuildingChange> dictionary2 = new Dictionary<int, BuildingChange>();
			Dictionary<int, ResourceChange> dictionary3 = new Dictionary<int, ResourceChange>();
			int key2;
			BuildingChange value3;
			ResourceChange value4;
			foreach (KeyValuePair<string, int> value7 in Values)
			{
				value7.Deconstruct(out var key, out key2);
				string text = key;
				int num = key2;
				string[] array = text.Split('.');
				int result3;
				int result4;
				if (array[0] == "u" && array.Length == 4 && int.TryParse(array[1], out var result) && int.TryParse(array[2], out var result2))
				{
					if (result < 0 || (result = Civilizations.FromLobbyNumber(result)) >= 0)
					{
						if (!dictionary.TryGetValue((result, result2), out var value))
						{
							(int, int) key3 = (result, result2);
							UnitStatChange val = new UnitStatChange();
							value = val;
							dictionary[key3] = val;
						}
						SetUnit(value, array[3], num);
					}
				}
				else if (array[0] == "b" && array.Length == 3 && int.TryParse(array[1], out result3))
				{
					if (!dictionary2.TryGetValue(result3, out var value2))
					{
						int key4 = result3;
						BuildingChange val2 = new BuildingChange();
						value2 = val2;
						dictionary2[key4] = val2;
					}
					key = array[2];
					switch (key)
					{
					case "Health":
						value2.Health = num;
						continue;
					case "TowerRange":
						value2.TowerRange = num;
						continue;
					case "TowerPeriod":
						value2.TowerPeriod = num;
						continue;
					}
					value3 = value2;
					ResourceChange obj = value3.Cost;
					if (obj == null)
					{
						BuildingChange obj2 = value3;
						ResourceChange val3 = new ResourceChange();
						value4 = val3;
						obj2.Cost = val3;
						obj = value4;
					}
					SetResource(obj, array[2], num);
				}
				else if (array[0] == "t" && array.Length == 3 && int.TryParse(array[1], out result4))
				{
					if (!dictionary3.TryGetValue(result4, out var value5))
					{
						int key5 = result4;
						ResourceChange val4 = new ResourceChange();
						value5 = val4;
						dictionary3[key5] = val4;
					}
					SetResource(value5, array[2], num);
				}
			}
			foreach (KeyValuePair<(int, int), UnitStatChange> item3 in dictionary)
			{
				item3.Deconstruct(out var key6, out var value6);
				(int, int) tuple = key6;
				int item = tuple.Item1;
				int item2 = tuple.Item2;
				UnitStatChange val5 = value6;
				if (item < 0)
				{
					_units.Set((Type)item2, val5);
				}
				else
				{
					_units.Set(item, (Type)item2, val5);
				}
			}
			foreach (KeyValuePair<int, BuildingChange> item4 in dictionary2)
			{
				item4.Deconstruct(out key2, out value3);
				int num2 = key2;
				BuildingChange val6 = value3;
				_balance.Set((BuildingTypeName)num2, val6);
			}
			foreach (KeyValuePair<int, ResourceChange> item5 in dictionary3)
			{
				item5.Deconstruct(out key2, out value4);
				int num3 = key2;
				ResourceChange val7 = value4;
				_balance.SetCost((TechnologyName)num3, val7);
			}
		}

		private static void SetUnit(UnitStatChange c, string stat, int v)
		{
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: 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)
			if (stat == null)
			{
				return;
			}
			switch (stat.Length)
			{
			case 5:
				switch (stat[0])
				{
				case 'R':
					if (stat == "Range")
					{
						c.Range = v;
					}
					break;
				case 'P':
					if (stat == "Parry")
					{
						c.Parry = new Chance(v, 100);
					}
					break;
				}
				break;
			case 10:
				switch (stat[0])
				{
				case 'B':
					if (stat == "BlockArrow")
					{
						c.BlockArrow = new Chance(v, 100);
					}
					break;
				case 'M':
					if (stat == "MissChance")
					{
						c.MissChance = new Chance(v, 100);
					}
					break;
				}
				break;
			case 12:
				if (stat == "AttackPeriod")
				{
					c.AttackPeriod = v;
				}
				break;
			case 11:
				if (stat == "AttackDelay")
				{
					c.AttackDelay = v;
				}
				break;
			case 13:
				if (stat == "AggroDistance")
				{
					c.AggroDistance = v;
				}
				break;
			case 6:
			case 7:
			case 8:
			case 9:
				break;
			}
		}

		private static void SetResource(ResourceChange c, string name, int v)
		{
			if (name == null)
			{
				return;
			}
			switch (name.Length)
			{
			case 4:
				switch (name[0])
				{
				case 'F':
					if (name == "Food")
					{
						c.Food = v;
					}
					break;
				case 'W':
					if (name == "Wood")
					{
						c.Wood = v;
					}
					break;
				case 'G':
					if (name == "Gold")
					{
						c.Gold = v;
					}
					break;
				}
				break;
			case 8:
				switch (name[0])
				{
				case 'M':
					if (name == "Military")
					{
						c.Military = v;
					}
					break;
				case 'D':
					if (name == "Disaster")
					{
						c.Disaster = v;
					}
					break;
				}
				break;
			case 5:
				if (name == "Stone")
				{
					c.Stone = v;
				}
				break;
			case 6:
				if (name == "Hammer")
				{
					c.Hammer = v;
				}
				break;
			case 7:
				if (name == "Culture")
				{
					c.Culture = v;
				}
				break;
			}
		}

		internal static int Percentage(Chance c)
		{
			if (((Chance)(ref c)).Denominator != 0)
			{
				return (int)Math.Round(100.0 * (double)((Chance)(ref c)).Numerator / (double)((Chance)(ref c)).Denominator);
			}
			return 0;
		}

		internal static int UnitBase(int civ, int unit, string stat)
		{
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			UnitStatValues val = Units.Default((Type)unit);
			UnitStatChange val2 = ((civ >= 0) ? Units.CivilizationDefaults(civ, (Type)unit) : null);
			return stat switch
			{
				"AttackPeriod" => val2?.AttackPeriod ?? val.AttackPeriod, 
				"AttackDelay" => val2?.AttackDelay ?? val.AttackDelay, 
				"AggroDistance" => val2?.AggroDistance ?? val.AggroDistance, 
				"Range" => val2?.Range ?? val.Range, 
				"Parry" => Percentage((Chance)(((??)val2?.Parry) ?? val.Parry)), 
				"BlockArrow" => Percentage((Chance)(((??)val2?.BlockArrow) ?? val.BlockArrow)), 
				"MissChance" => Percentage((Chance)(((??)val2?.MissChance) ?? val.MissChance)), 
				_ => 0, 
			};
		}

		internal static bool IsRanged(int unit)
		{
			return Units.Default((Type)unit).IsRanged;
		}

		internal static int Resource(ResourceValues r, string name)
		{
			return name switch
			{
				"Food" => r.Food, 
				"Wood" => r.Wood, 
				"Stone" => r.Stone, 
				"Gold" => r.Gold, 
				"Hammer" => r.Hammer, 
				"Culture" => r.Culture, 
				"Military" => r.Military, 
				"Disaster" => r.Disaster, 
				_ => 0, 
			};
		}
	}
	internal static class IslandSize
	{
		private const int MaxGrid = 201;

		private const int NormalMax = 119;

		private const int NatureLayerOffset = 296;

		private const int FishTile = 5;

		private static PatchSwitch _fishPatch;

		private static int _fishTarget;

		private static UiScope _scope;

		private static bool _extendedOk;

		private static bool _asking;

		private static LobbyRule<int> _grid;

		private static LobbyRule<int> _land;

		private static int2 _gameSize;

		private static Parameters _game;

		private static int _gameRadius;

		private static IslandGrid _prefab;

		private static int _side;

		private static float _normalFocus;

		private static CameraMovement _camera;

		private static float _gameBound;

		private static float _gameMinHeight;

		private static bool _inPosition;

		private static PatchSwitch _positionPatch;

		private static ConfigEntry<bool> _capCamera;

		private static ConfigEntry<bool> _widenSea;

		private static readonly List<(Transform t, Vector3 scale)> _sea = new List<(Transform, Vector3)>();

		private static readonly List<(Canvas c, RenderMode mode, Camera camera, float distance)> _ui = new List<(Canvas, RenderMode, Camera, float)>();

		private static float _mapLo;

		private static float _mapHi;

		private static float _mapNear;

		private static PatchSwitch _dicePatch;

		private static readonly Dictionary<IntPtr, Vector3> _diceScale = new Dictionary<IntPtr, Vector3>();

		private static float Scale
		{
			get
			{
				if (_side <= 0 || _gameSize.x <= 0)
				{
					return 1f;
				}
				return (float)_side / (float)_gameSize.x;
			}
		}

		internal static void Bind(ConfigFile config)
		{
			_capCamera = config.Bind<bool>("Big islands", "NormalCameraDistance", true, "On islands bigger than the game's, the start view and focus views keep a normal island's distance. Read at the start of a match.");
			_widenSea = config.Bind<bool>("Big islands", "WidenSea", true, "On islands bigger than the game's, the sea plane is widened so the outer islands do not lie past its edge. Read at the start of a match.");
		}

		internal static void Install(Patcher patcher, UiScope ui)
		{
			_scope = ui;
			LobbyGroup val = Groups.Get("lobbyrules.islands", "Islands", 500);
			_grid = Rules.Number("lobbyrules.islandGrid", "Island grid size", 49, 49, 201, 2, $"Tiles per side of every island. 49 = the game's islands. The land, its hills, forests, rocks and fish, and the space between islands grow with it. Up to {119} plays normally; {121} .. {201} is experimental and asks first.", (Func<bool>)null, true).InGroup(val);
			_grid.Changed += OnGridChanged;
			_land = Rules.Number("lobbyrules.landSize", "Land size %", 100, 70, 110, 5, "How much of the island grid is land. 100 = like the game's islands.", (Func<bool>)null, true).InGroup(val);
			patcher.Patch(typeof(GameState), "SpawnIslands", typeof(IslandSize), "SpawnPrefix", "SpawnPostfix");
			_fishPatch = patcher.Switch(typeof(IslandGrid), "UpdateNatureVisuals", typeof(IslandSize), "ThinFishPrefix", (string)null);
			patcher.Patch(typeof(IslandGrid), "Awake", typeof(IslandSize), "AwakePrefix", "AwakePostfix");
			_positionPatch = patcher.Switch(typeof(CameraMovement), "Position", typeof(IslandSize), (string)null, "PositionPostfix");
			_dicePatch = patcher.Switch(typeof(HarvestInterface), "CreateDices", typeof(IslandSize), (string)null, "DicePostfix");
			Match.Started += WidenCamera;
			Match.Rejoined += WidenCamera;
			Match.Reset += Restore;
			Match.Ended += Restore;
		}

		private static void OnGridChanged(int value)
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			if (value <= 119 || _extendedOk || _asking || !_grid.Editable)
			{
				return;
			}
			string text = Tx.T("islands.experimental", value, 121, 201) ?? "";
			_asking = true;
			if (_scope == null || !_scope.Native.Dialogs.Confirm(text, (Action)delegate
			{
				_asking = false;
				_extendedOk = true;
			}, (Action)delegate
			{
				_asking = false;
				_grid.TrySet(119);
			}, "uikit:warning", (string)null))
			{
				_asking = false;
				_grid.TrySet(119);
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(77, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[island] grid ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(value);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" needs the warning dialog, which is not available here: set to ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(119);
				}
				l.LogInfo(val);
			}
		}

		internal static void SpawnPrefix(GameState __instance)
		{
			try
			{
				object obj;
				if (__instance == null)
				{
					obj = null;
				}
				else
				{
					Island islandPrefab = __instance.islandPrefab;
					obj = ((islandPrefab != null) ? islandPrefab.grid : null);
				}
				IslandGrid val = (IslandGrid)obj;
				if (!((Object)(object)val == (Object)null))
				{
					_prefab = val;
					Remember(val);
					Apply(val, "island prefab");
					if (_fishTarget > 0)
					{
						_fishPatch.On = true;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[island] spawn: " + ex.Message));
			}
		}

		internal static void SpawnPostfix()
		{
			_fishPatch.On = false;
		}

		internal unsafe static void ThinFishPrefix(IslandGrid __instance)
		{
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Expected O, but got Unknown
			try
			{
				if (_fishTarget <= 0 || (Object)(object)__instance == (Object)null)
				{
					return;
				}
				IntPtr intPtr = *(IntPtr*)((byte*)(void*)((Il2CppObjectBase)__instance).Pointer + 296);
				if (intPtr == IntPtr.Zero)
				{
					return;
				}
				IntPtr intPtr2 = *(IntPtr*)((byte*)(void*)intPtr + 16);
				if (intPtr2 == IntPtr.Zero)
				{
					return;
				}
				int num = ((int*)(void*)intPtr2)[6];
				byte* ptr = (byte*)(void*)intPtr2 + 32;
				List<int> list = new List<int>();
				for (int i = 0; i < num; i++)
				{
					if (ptr[i * 8] != 0 && ((int*)(ptr + i * 8))[1] == 5)
					{
						list.Add(i);
					}
				}
				if (list.Count > _fishTarget)
				{
					Random random = new Random(num * 31 + list.Count);
					for (int j = 0; j < _fishTarget; j++)
					{
						int num2 = random.Next(j, list.Count);
						List<int> list2 = list;
						int index = j;
						int index2 = num2;
						int value = list[num2];
						int value2 = list[j];
						list2[index] = value;
						list[index2] = value2;
					}
					for (int k = _fishTarget; k < list.Count; k++)
					{
						*(long*)(ptr + list[k] * 8) = 0L;
					}
					((sbyte*)(void*)intPtr)[32] = 1;
					ManualLogSource l = Plugin.L;
					bool flag = default(bool);
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(33, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[island] fish spread evenly: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_fishTarget);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" of ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(list.Count);
					}
					l.LogInfo(val);
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[island] fish: " + ex.Message));
			}
		}

		internal static void AwakePrefix(IslandGrid __instance)
		{
			try
			{
				if (Rules.Fixed)
				{
					Remember(__instance);
					Apply(__instance, "island");
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[island] awake: " + ex.Message));
			}
		}

		internal static void AwakePostfix(IslandGrid __instance)
		{
			//IL_0036: 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)
			try
			{
				if (!(_normalFocus > 0f) && !(Scale <= 1f) && Rules.Fixed && _capCamera.Value)
				{
					Focus val = new Focus(__instance, 0f, false);
					_normalFocus = ((Focus)(ref val)).Radius / Scale;
					if (_positionPatch != null)
					{
						_positionPatch.On = true;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[island] focus size: " + ex.Message));
			}
		}

		private static void Remember(IslandGrid grid)
		{
			//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_0014: 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)
			if (_gameRadius == 0)
			{
				_game = grid.generationParameters;
				_gameSize = grid.size;
				_gameRadius = _game.hardLimit.radius;
			}
		}

		private static void Apply(IslandGrid grid, string what)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: 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_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: 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)
			//IL_0297: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Expected O, but got Unknown
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_034a: Unknown result type (might be due to invalid IL or missing references)
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0351: Unknown result type (might be due to invalid IL or missing references)
			//IL_037a: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b4: Unknown result type (might be due to invalid IL or missing references)
			if (_gameRadius <= 0 || _gameSize.x <= 0)
			{
				return;
			}
			bool flag = Plugin.On && Rules.Fixed;
			int num = (flag ? Odd(Math.Clamp(_grid.Value, _gameSize.x, 201)) : _gameSize.x);
			int num2 = (flag ? _land.Value : 100);
			int2 val = (int2)((num == _gameSize.x) ? _gameSize : new int2(num, num));
			int num3 = Math.Clamp((int)Math.Round((float)_gameRadius * (float)num / (float)_gameSize.x * (float)num2 / 100f), 1, num / 2);
			_side = (flag ? num : 0);
			CombatPathLimit.Set(num, _gameSize.x);
			float num4 = (float)num3 / (float)_gameRadius;
			float num5 = num4 * num4;
			Parameters game = _game;
			game.hardLimit.radius = num3;
			game.altitude.distanceVerticalScale = _game.altitude.distanceVerticalScale * 100f / (float)num2;
			game.innerCliffs.numberMains = Times(_game.innerCliffs.numberMains, num5);
			game.nature.trees.count = Times(_game.nature.trees.count, num5);
			game.nature.rocks.count = Times(_game.nature.rocks.count, num5);
			game.nature.fish.maximumDistance = ((num4 > 1f) ? (_game.nature.fish.maximumDistance * num4 * 1.15f) : _game.nature.fish.maximumDistance);
			game.nature.fish.maxCount = ((num4 > 1f) ? 1000000 : _game.nature.fish.maxCount);
			_fishTarget = ((flag && num4 > 1f) ? ((int)Math.Round((float)_game.nature.fish.maxCount * num5)) : 0);
			bool num6 = grid.size.x != val.x || grid.size.y != val.y || grid.generationParameters.hardLimit.radius != num3;
			grid.generationParameters = game;
			grid.size = val;
			if (num6 && flag)
			{
				ManualLogSource l = Plugin.L;
				bool flag2 = default(bool);
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(80, 9, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[island] ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(what);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": grid ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(val.x);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("x");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(val.y);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", land radius ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num3);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", hill groups ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(game.innerCliffs.numberMains.x);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("-");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(game.innerCliffs.numberMains.y);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("forests ~");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(game.nature.trees.count.average, "0.#");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", rock fields ~");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(game.nature.rocks.count.average, "0.#");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", fish ~");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(_fishTarget);
				}
				l.LogInfo(val2);
			}
		}

		private static int2 Times(int2 range, float factor)
		{
			//IL_0000: 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_0020: Unknown result type (might be due to invalid IL or missing references)
			return new int2((int)Math.Round((float)range.x * factor), (int)Math.Round((float)range.y * factor));
		}

		private static Gaussian Times(Gaussian count, float factor)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			return new Gaussian
			{
				average = count.average * factor,
				deviation = count.deviation * MathF.Sqrt(factor)
			};
		}

		private static int Odd(int n)
		{
			if (n % 2 != 0)
			{
				return n;
			}
			return n + 1;
		}

		private static void WidenCamera()
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			try
			{
				float scale = Scale;
				if (scale <= 1f)
				{
					return;
				}
				if ((Object)(object)_camera == (Object)null)
				{
					_camera = Object.FindObjectOfType<CameraMovement>();
				}
				if (!((Object)(object)_camera == (Object)null))
				{
					if (_gameBound == 0f)
					{
						_gameBound = _camera.baseHorizontalBound;
					}
					_camera.baseHorizontalBound = _gameBound * scale;
					ManualLogSource l = Plugin.L;
					bool flag = default(bool);
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(30, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[island] camera panning area x");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(scale, "0.##");
					}
					l.LogInfo(val);
					if (_widenSea.Value)
					{
						WidenSea(scale);
					}
					float num = PushUi(scale);
					if (_gameMinHeight == 0f)
					{
						_gameMinHeight = _camera.minHeight;
					}
					_camera.minHeight = Math.Max(_gameMinHeight, _gameMinHeight + num * 1.5f);
					ManualLogSource l2 = Plugin.L;
					val = new BepInExInfoLogInterpolatedStringHandler(38, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[island] lowest camera height ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(_camera.minHeight, "0.0");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (game ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(_gameMinHeight, "0.0");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")");
					}
					l2.LogInfo(val);
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[island] camera: " + ex.Message));
			}
		}

		private static void WidenSea(float scale)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			if (_sea.Count > 0)
			{
				return;
			}
			Il2CppArrayBase<MeshRenderer> obj = Object.FindObjectsOfType<MeshRenderer>();
			List<(MeshRenderer, float)> list = new List<(MeshRenderer, float)>();
			foreach (MeshRenderer item3 in obj)
			{
				if (!((Object)(object)item3 == (Object)null))
				{
					Bounds bounds = ((Renderer)item3).bounds;
					float num = Math.Max(((Bounds)(ref bounds)).size.x, ((Bounds)(ref bounds)).size.z);
					if (num >= 100f)
					{
						list.Add((item3, num));
					}
				}
			}
			list.Sort(((MeshRenderer r, float size) a, (MeshRenderer r, float size) b) => b.size.CompareTo(a.size));
			foreach (var item4 in list)
			{
				MeshRenderer item = item4.Item1;
				float item2 = item4.Item2;
				string text = (((Object)(object)((Renderer)item).sharedMaterial != (Object)null) ? ((Object)((Renderer)item).sharedMaterial).name : "");
				bool flag = text.IndexOf("water", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("ocean", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("sea", StringComparison.OrdinalIgnoreCase) >= 0;
				Plugin.L.LogInfo((object)($"[island] large object '{((Object)((Component)item).gameObject).name}' material '{text}' size {item2:0}" + (flag ? " -> sea, widened" : "")));
				if (flag)
				{
					Transform transform = ((Component)item).transform;
					_sea.Add((transform, transform.localScale));
					transform.localScale = new Vector3(transform.localScale.x * scale, transform.localScale.y, transform.localScale.z * scale);
				}
			}
		}

		private static float PushUi(float scale)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Invalid comparison between Unknown and I4
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Expected O, but got Unknown
			RestoreUi();
			List<Canvas> list = new List<Canvas>();
			List<Canvas> list2 = new List<Canvas>();
			foreach (Canvas item in Resources.FindObjectsOfTypeAll<Canvas>())
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				Scene scene = ((Component)item).gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && (int)item.renderMode == 1)
				{
					Transform parent = ((Component)item).transform.parent;
					if (!((Object)(object)parent != (Object)null) || !((Object)(object)((Component)parent).GetComponentInParent<Canvas>(true) != (Object)null))
					{
						_ui.Add((item, item.renderMode, item.worldCamera, item.planeDistance));
						((item.planeDistance >= 2f) ? list2 : list).Add(item);
					}
				}
			}
			float num = float.MaxValue;
			float num2 = 0f;
			foreach (Canvas item2 in list)
			{
				num = Math.Min(num, item2.planeDistance);
				num2 = Math.Max(num2, item2.planeDistance);
			}
			float num3 = Math.Max(0.11f, (num == float.MaxValue) ? 0.11f : num) * 6f * scale;
			float num4 = num3;
			_mapLo = ((num == float.MaxValue) ? 0.11f : num);
			_mapHi = ((num2 > _mapLo) ? num2 : (_mapLo + 1f));
			_mapNear = num3;
			foreach (Canvas item3 in list)
			{
				float num5 = ((num2 > num) ? ((item3.planeDistance - num) / (num2 - num)) : 0f);
				item3.planeDistance = num3 * (1f + 0.3f * num5);
				num4 = Math.Max(num4, item3.planeDistance);
			}
			foreach (Canvas item4 in list2)
			{
				item4.planeDistance = Math.Max(item4.planeDistance, num4 * 1.25f);
			}
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(74, 3, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[island] ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_ui.Count);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" camera-space UI canvases moved away from the camera (");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num3, "0.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" .. ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num4, "0.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" units)");
			}
			l.LogInfo(val);
			if (_dicePatch != null)
			{
				_dicePatch.On = list.Count > 0;
			}
			return num4;
		}

		private static float MapDistance(float d)
		{
			return _mapNear * (1f + 0.3f * (d - _mapLo) / (_mapHi - _mapLo));
		}

		internal static void DicePostfix(HarvestInterface __instance)
		{
			//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)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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_0093: 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)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Transform val = (((Object)(object)__instance != (Object)null) ? __instance.dicesHolder : null);
				if (!((Object)(object)val == (Object)null) && !(_mapNear <= 0f))
				{
					if (!_diceScale.TryGetValue(((Il2CppObjectBase)val).Pointer, out var value))
					{
						value = (_diceScale[((Il2CppObjectBase)val).Pointer] = val.localScale);
					}
					Vector3 localPosition = val.localPosition;
					if (!(localPosition.z <= 0f))
					{
						float num = MapDistance(localPosition.z) / localPosition.z;
						val.localPosition = new Vector3(localPosition.x * num, localPosition.y * num, localPosition.z * num);
						val.localScale = new Vector3(value.x * num, value.y * num, value.z * num);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[island] dice depth: " + ex.Message));
			}
		}

		private static void RestoreUi()
		{
			//IL_001c: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			foreach (var (val, renderMode, worldCamera, planeDistance) in _ui)
			{
				if (!((Object)(object)val == (Object)null))
				{
					val.renderMode = renderMode;
					val.worldCamera = worldCamera;
					val.planeDistance = planeDistance;
				}
			}
			_ui.Clear();
		}

		private static void RestoreSea()
		{
			//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_002b: Unknown result type (might be due to invalid IL or missing references)
			foreach (var (val, localScale) in _sea)
			{
				if ((Object)(object)val != (Object)null)
				{
					val.localScale = localScale;
				}
			}
			_sea.Clear();
		}

		internal static void PositionPostfix(CameraMovement __instance, Focus focus, ref float3 __result)
		{
			//IL_002d: 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_004a: 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)
			if (_inPosition || _normalFocus <= 0f || ((Focus)(ref focus)).Radius <= _normalFocus)
			{
				return;
			}
			try
			{
				_inPosition = true;
				__result = __instance.Position(new Focus(((Focus)(ref focus)).Position, _normalFocus, ((Focus)(ref focus)).EndTime, ((Focus)(ref focus)).StopAfterEnd));
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[island] camera focus: " + ex.Message));
			}
			finally
			{
				_inPosition = false;
			}
		}

		private static void Restore()
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)_prefab != (Object)null)
				{
					Apply(_prefab, "island prefab restored");
				}
				_side = 0;
				CombatPathLimit.Reset();
				_normalFocus = 0f;
				_asking = false;
				if (_positionPatch != null)
				{
					_positionPatch.On = false;
				}
				if (_dicePatch != null)
				{
					_dicePatch.On = false;
				}
				_mapNear = 0f;
				foreach (HarvestInterface item in Resources.FindObjectsOfTypeAll<HarvestInterface>())
				{
					if ((Object)(object)item != (Object)null && (Object)(object)item.dicesHolder != (Object)null && _diceScale.TryGetValue(((Il2CppObjectBase)item.dicesHolder).Pointer, out var value))
					{
						item.dicesHolder.localScale = value;
					}
				}
				_diceScale.Clear();
				if (_fishPatch != null)
				{
					_fishPatch.On = false;
				}
				if ((Object)(object)_camera != (Object)null && _gameBound != 0f)
				{
					_camera.baseHorizontalBound = _gameBound;
				}
				if ((Object)(object)_camera != (Object)null && _gameMinHeight != 0f)
				{
					_camera.minHeight = _gameMinHeight;
				}
				RestoreSea();
				RestoreUi();
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[island] restore: " + ex.Message));
			}
		}
	}
	[BepInPlugin("org.dicemodders.dicekingdoms.lobbyrules", "DiceKingdoms Lobby Rules", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("Dice-Kingdoms.exe")]
	public sealed class Plugin : BasePlugin
	{
		public const string Guid = "org.dicemodders.dicekingdoms.lobbyrules";

		public const string Name = "DiceKingdoms Lobby Rules";

		public const string Version = "1.0.0";

		internal static ManualLogSource L;

		internal static bool On;

		public override void Load()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			Tx.Load();
			L = ((BasePlugin)this).Log;
			Patcher val = new Patcher("org.dicemodders.dicekingdoms.lobbyrules", ((BasePlugin)this).Log);
			UiScope ui = UiKit.CreateScope("org.dicemodders.dicekingdoms.lobbyrules");
			IslandSize.Bind(((BasePlugin)this).Config);
			IslandSize.Install(val, ui);
			val.Summary();
			GameValues.Install();
			ValuesWindow.Install(ui);
			Mods.Switch(((BasePlugin)this).Config, true, false, "Turns every rule of this mod on or off.").WhenOn((Action)delegate
			{
				On = true;
			}, (Action)delegate
			{
				On = false;
			});
		}
	}
	internal static class Tx
	{
		internal static TextSet Set;

		internal static void Load()
		{
			Set = Texts.Load("texts.json", (string)null);
		}

		internal static string T(string key)
		{
			TextSet set = Set;
			return ((set != null) ? set.Get(key) : null) ?? key;
		}

		internal static string T(string key, params object[] values)
		{
			TextSet set = Set;
			return ((set != null) ? set.Get(key, values) : null) ?? key;
		}

		internal static SettingsBlockHandle Block(UiScope ui, Func<SettingsBlockSpec> spec)
		{
			if (ui == null)
			{
				return null;
			}
			SettingsBlockHandle handle = ui.Native.Settings.AddBlock(spec());
			Texts.LanguageChanged += delegate
			{
				SettingsBlockHandle obj = handle;
				if (obj != null)
				{
					((NativeHandle)obj).Dispose();
				}
				handle = ui.Native.Settings.AddBlock(spec());
			};
			return handle;
		}
	}
	internal static class ValuesWindow
	{
		private static readonly Color Changed = new Color(1f, 0.82f, 0.45f, 1f);

		private static readonly Color Normal = new Color(0.97f, 0.94f, 0.89f, 1f);

		private static UiScope _ui;

		private static UiWindow _win;

		private static UiScroll _scroll;

		private static UiText _status;

		private static readonly List<UiButton> Tabs = new List<UiButton>();

		private static readonly List<Action> Refreshers = new List<Action>();

		private static readonly List<UiButton> EditButtons = new List<UiButton>();

		private static int _tab;

		private static string _open;

		private static string[] BuiltInCivs => new string[5]
		{
			Texts.Game("civilization.EUROPE.name", Tx.T("civ.0")),
			Texts.Game("civilization.MIDDLE_EAST.name", Tx.T("civ.1")),
			Texts.Game("civilization.VIKING.name", Tx.T("civ.2")),
			Texts.Game("civilization.ANCIENT.name", Tx.T("civ.3")),
			Texts.Game("civilization.MAYA.name", Tx.T("civ.4"))
		};

		private static string[] TabNames => new string[3]
		{
			Tx.T("values.tab.units"),
			Tx.T("values.tab.buildings"),
			Tx.T("values.tab.technologies")
		};

		internal static void Install(UiScope ui)
		{
			_ui = ui;
			GameValues.Changed += Refresh;
			Lobby.Changed += Refresh;
			Tx.Block(ui, delegate
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0005: 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_0017: 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_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Expected O, but got Unknown
				SettingsBlockSpec val = new SettingsBlockSpec();
				val.set_Id("org.dicemodders.dicekingdoms.lobbyrules.lobby");
				val.set_Page((SettingsPage)4);
				val.set_Title(Tx.T("values.block"));
				val.set_Order(30);
				val.set_Build((Action<SettingsBlockHandle>)delegate(SettingsBlockHandle block)
				{
					block.AddButton(Tx.T("values.title"), Tx.T("common.open"), (Action)Toggle);
				});
				return val;
			});
		}

		internal static void Toggle()
		{
			if (_win != null)
			{
				_win.Close();
			}
			else
			{
				Open();
			}
		}

		private static void Open()
		{
			UiScope ui = _ui;
			_win = ((ui != null) ? ui.Custom.Window((Action<UiWindow>)delegate(UiWindow w)
			{
				w.Title(Tx.T("values.title")).Size(760f, 800f).Position(80f, 40f)
					.Draggable(true)
					.Closable(true)
					.Fullscreenable(true)
					.FullscreenButton(true);
				w.OnClose((Action)delegate
				{
					_win = null;
					_scroll = null;
					_status = null;
					Tabs.Clear();
					Refreshers.Clear();
					EditButtons.Clear();
				});
				w.Body.Spacing(6f);
				UiContainer obj = w.Body.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					for (int i = 0; i < TabNames.Length; i++)
					{
						int tab = i;
						UiButton obj3 = r.Button(TabNames[i], (Action)delegate
						{
							_tab = tab;
							_open = null;
							Rebuild();
						});
						UiButton val = ((obj3 != null) ? UiLayout.FillWidth<UiButton>(obj3) : null);
						if (val != null)
						{
							Tabs.Add(val);
						}
					}
					UiButton obj4 = r.Button(Tx.T("values.resetAll"), (Action)delegate
					{
						GameValues.ResetAll();
					});
					UiButton val2 = ((obj4 != null) ? UiLayout.FillWidth<UiButton>(obj4) : null);
					if (val2 != null)
					{
						EditButtons.Add(val2);
					}
				});
				if (obj != null)
				{
					UiLayout.Height<UiContainer>(obj, 36f);
				}
				_status = w.Body.Text("");
				UiScroll obj2 = w.Body.Scroll((Action<UiContainer>)delegate
				{
				});
				_scroll = ((obj2 != null) ? UiLayout.FillHeight<UiScroll>(UiLayout.FillWidth<UiScroll>(obj2)) : null);
			}) : null);
			Rebuild();
		}

		private static void Rebuild()
		{
			if (_win == null || _scroll == null)
			{
				return;
			}
			for (int i = 0; i < Tabs.Count; i++)
			{
				Tabs[i].Selected(i == _tab);
			}
			UiButton val = ((EditButtons.Count > 0) ? EditButtons[0] : null);
			EditButtons.Clear();
			if (val != null)
			{
				EditButtons.Add(val);
			}
			Refreshers.Clear();
			UiContainer content = _scroll.Content;
			content.Clear();
			content.Spacing(4f);
			try
			{
				if (_tab == 0)
				{
					BuildUnits(content);
				}
				else if (_tab == 1)
				{
					BuildBuildings(content);
				}
				else
				{
					BuildTechnologies(content);
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogError((object)("game values window: " + ex));
			}
			Refresh();
			_scroll.ToTop();
		}

		private static void BuildUnits(UiContainer c)
		{
			List<(int, string)> list = new List<(int, string)> { (-1, Tx.T("values.everyCiv")) };
			for (int i = 0; i < BuiltInCivs.Length; i++)
			{
				list.Add((i, BuiltInCivs[i]));
			}
			foreach (ModCivilization item in Civilizations.All)
			{
				list.Add((item.Id, item.DisplayName));
			}
			foreach (var item2 in list)
			{
				var (civ, title) = item2;
				Section(c, "civ:" + civ, title, delegate(UiContainer s)
				{
					//IL_0027: 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_0072: Unknown result type (might be due to invalid IL or missing references)
					for (int j = 0; j < 10; j++)
					{
						int u = j;
						UiText obj = s.Text(Texts.Game("unit." + ((object)(Type)u/*cast due to .constrained prefix*/).ToString() + ".name", Nice(((object)(Type)u/*cast due to .constrained prefix*/).ToString())));
						if (obj != null)
						{
							obj.Size(20f).Color(Changed);
						}
						string[] unitStats = GameValues.UnitStats;
						foreach (string stat in unitStats)
						{
							string all;
							if ((!(stat == "Range") && !(stat == "MissChance")) || GameValues.IsRanged(u))
							{
								bool flag = Array.IndexOf(GameValues.Percent, stat) >= 0;
								int num = ((civ >= 0) ? Civilizations.ToLobbyNumber(civ) : civ);
								string key = $"u.{((num == -1 && civ >= 0) ? civ : num)}.{u}.{stat}";
								all = $"u.-1.{u}.{stat}";
								Stepper(s, Tx.T("stat." + stat) + (flag ? " %" : ""), key, Base, (!flag) ? 1 : 5, 0, flag ? 100 : 99);
							}
							int Base()
							{
								if (civ < 0)
								{
									return GameValues.UnitBase(-1, u, stat);
								}
								return GameValues.Get(all) ?? GameValues.UnitBase(civ, u, stat);
							}
						}
					}
				});
			}
		}

		private static void BuildBuildings(UiContainer c)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: 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)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected I4, but got Unknown
			foreach (BuildingTypeName value in Enum.GetValues(typeof(BuildingTypeName)))
			{
				BuildingTypeName building = value;
				Section(c, "b:" + (int)value, Texts.Game("building." + ((object)value/*cast due to .constrained prefix*/).ToString() + ".name", Nice(((object)value/*cast due to .constrained prefix*/).ToString())), delegate(UiContainer s)
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					//IL_003d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0043: Expected I4, but got Unknown
					BuildingValues d = Balance.DefaultBuilding(building);
					if (d == (BuildingValues)null)
					{
						s.Text(Tx.T("values.buildingNotLoaded"));
					}
					else
					{
						string text = "b." + (int)building + ".";
						Stepper(s, Tx.T("values.health"), text + "Health", () => d.Health, 1, 1, 999);
						if (d.IsTower)
						{
							Stepper(s, Tx.T("values.towerRange"), text + "TowerRange", () => d.TowerRange, 1, 1, 99);
							Stepper(s, Tx.T("values.towerPeriod"), text + "TowerPeriod", () => d.TowerPeriod, 1, 1, 999);
						}
						string[] resources = GameValues.Resources;
						foreach (string text2 in resources)
						{
							string res = text2;
							Stepper(s, Tx.T("values.cost", Tx.T("res." + res)), text + res, () => GameValues.Resource(d.Cost, res), 1, 0, 99);
						}
					}
				});
			}
		}

		private static void BuildTechnologies(UiContainer c)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: 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)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected I4, but got Unknown
			foreach (TechnologyName value in Enum.GetValues(typeof(TechnologyName)))
			{
				TechnologyName tech = value;
				Section(c, "t:" + (int)value, Texts.Game("technology." + ((object)value/*cast due to .constrained prefix*/).ToString() + ".name", Nice(((object)value/*cast due to .constrained prefix*/).ToString())), delegate(UiContainer s)
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					//IL_008f: Unknown result type (might be due to invalid IL or missing references)
					//IL_0096: Expected I4, but got Unknown
					ResourceValues d = Balance.DefaultTechnologyCost(tech);
					if (d == (ResourceValues)null)
					{
						s.Text(Tx.T("values.techNotLoaded"));
					}
					else
					{
						string[] resources = GameValues.Resources;
						foreach (string text in resources)
						{
							string res = text;
							Stepper(s, Tx.T("values.cost", Tx.T("res." + res)), "t." + (int)tech + "." + res, () => GameValues.Resource(d, res), 1, 0, 99);
						}
					}
				});
			}
		}

		private static void Section(UiContainer c, string key, string title, Action<UiContainer> build)
		{
			bool open = _open == key;
			UiButton obj = c.Button((open ? "- " : "+ ") + title, (Action)delegate
			{
				_open = (open ? null : key);
				Rebuild();
			});
			if (obj != null)
			{
				UiLayout.Height<UiButton>(UiLayout.FillWidth<UiButton>(obj), 34f);
			}
			if (open)
			{
				UiContainer obj2 = c.Column((Action<UiContainer>)delegate(UiContainer s)
				{
					s.Spacing(2f);
					s.Padding(16f, 4f);
					build(s);
				});
				if (obj2 != null)
				{
					UiLayout.FillWidth<UiContainer>(obj2);
				}
			}
		}

		private static void Stepper(UiContainer c, string label, string key, Func<int> baseValue, int step, int min, int max)
		{
			UiText value = null;
			UiContainer obj = c.Row((Action<UiContainer>)delegate(UiContainer r)
			{
				r.Spacing(4f);
				UiText obj2 = r.Text(label);
				if (obj2 != null)
				{
					UiLayout.FillWidth<UiText>(obj2);
				}
				UiButton obj3 = r.Button("-", (Action)delegate
				{
					Step(key, baseValue, -step, min, max);
				});
				UiButton val = ((obj3 != null) ? UiLayout.FixedW<UiButton>(obj3, 36f) : null);
				UiText obj4 = r.Text("");
				value = ((obj4 != null) ? UiLayout.FixedW<UiText>(obj4, 140f) : null);
				UiButton obj5 = r.Button("+", (Action)delegate
				{
					Step(key, baseValue, step, min, max);
				});
				UiButton val2 = ((obj5 != null) ? UiLayout.FixedW<UiButton>(obj5, 36f) : null);
				UiButton obj6 = r.Button(Tx.T("values.game"), (Action)delegate
				{
					GameValues.Set(key, null);
				});
				UiButton val3 = ((obj6 != null) ? UiLayout.FixedW<UiButton>(obj6, 70f) : null);
				UiButton[] array = (UiButton[])(object)new UiButton[3] { val, val2, val3 };
				foreach (UiButton val4 in array)
				{
					if (val4 != null)
					{
						EditButtons.Add(val4);
					}
				}
			});
			if (obj != null)
			{
				UiLayout.Height<UiContainer>(obj, 30f);
			}
			Refreshers.Add(delegate
			{
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				//IL_007a: Unknown result type (might be due to invalid IL or missing references)
				if (value != null)
				{
					int num = baseValue();
					int? num2 = GameValues.Get(key);
					value.Value = ((!num2.HasValue) ? num.ToString(CultureInfo.InvariantCulture) : Tx.T("values.was", num2.Value, num));
					value.Color((!num2.HasValue) ? Normal : Changed);
				}
			});
		}

		private static void Step(string key, Func<int> baseValue, int delta, int min, int max)
		{
			int num = baseValue();
			int num2 = Math.Clamp((GameValues.Get(key) ?? num) + delta, min, max);
			if (!GameValues.Set(key, (num2 == num) ? ((int?)null) : new int?(num2)))
			{
				Status(Tx.T("values.hostOnly"));
			}
		}

		private static void Refresh()
		{
			if (_win == null)
			{
				return;
			}
			foreach (Action refresher in Refreshers)
			{
				refresher();
			}
			bool editable = GameValues.Editable;
			foreach (UiButton editButton in EditButtons)
			{
				if (editButton != null)
				{
					editButton.Interactable(editable);
				}
			}
			Status((editable ? Tx.T("values.host") : Tx.T("values.readonly")) + " " + ((GameValues.Count == 0) ? Tx.T("values.none") : Tx.T("values.changed", GameValues.Count)) + " " + Tx.T("values.onlyAll"));
		}

		private static void Status(string text)
		{
			if (_status != null)
			{
				_status.Value = text;
			}
		}

		private static string Nice(string name)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < name.Length; i++)
			{
				char c = name[i];
				if (c == '_')
				{
					stringBuilder.Append(' ');
					continue;
				}
				if (i > 0 && char.IsUpper(c) && char.IsLower(name[i - 1]))
				{
					stringBuilder.Append(' ');
				}
				stringBuilder.Append((stringBuilder.Length == 0) ? char.ToUpperInvariant(c) : char.ToLowerInvariant(c));
			}
			return stringBuilder.ToString();
		}
	}
}