Decompiled source of ForecastRune v0.1.0

plugins\ForecastRune.dll

Decompiled 21 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("Catosaur")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A craftable rune that shows the next weather changes for your biome.")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+8937820f113241d219dede01a61d428f961d2eaf")]
[assembly: AssemblyProduct("ForecastRune")]
[assembly: AssemblyTitle("ForecastRune")]
[assembly: AssemblyVersion("0.1.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 ForecastRune
{
	internal static class ForecastFormatter
	{
		private enum Sky
		{
			Rain,
			Snow,
			Fog,
			Shine,
			Unsettled
		}

		private static readonly string[] DayLabels = new string[3] { "Today", "Tomorrow", "Day after tomorrow" };

		internal static List<string> DailyLines(List<ForecastEntry> entries, double dayLength, double nowSeconds)
		{
			List<string> list = new List<string>();
			if (dayLength <= 0.0)
			{
				return list;
			}
			long num = (long)(nowSeconds / dayLength);
			for (int i = 0; i < DayLabels.Length; i++)
			{
				long day = num + i;
				list.Add(DayLabels[i] + ": " + DaySummary(entries, dayLength, day));
			}
			return list;
		}

		private static string DaySummary(List<ForecastEntry> entries, double dayLength, long day)
		{
			List<Sky> list = new List<Sky>();
			foreach (ForecastEntry entry in entries)
			{
				if ((long)(entry.StartSeconds / dayLength) == day)
				{
					Sky item = Classify(entry);
					if (!list.Contains(item))
					{
						list.Add(item);
					}
				}
			}
			if (list.Count == 0)
			{
				return Word(Sky.Unsettled);
			}
			List<string> list2 = new List<string>();
			foreach (Sky item2 in list)
			{
				list2.Add(Word(item2));
			}
			return string.Join(", then ", list2.ToArray());
		}

		private static Sky Classify(ForecastEntry entry)
		{
			if (string.IsNullOrEmpty(entry.EnvName))
			{
				return Sky.Unsettled;
			}
			if (entry.IsWet)
			{
				return Sky.Rain;
			}
			if (entry.IsFreezing)
			{
				return Sky.Snow;
			}
			string text = entry.EnvName.ToLowerInvariant();
			if (text.Contains("mist") || text.Contains("fog"))
			{
				return Sky.Fog;
			}
			if (text.Contains("clear"))
			{
				return Sky.Shine;
			}
			return Sky.Unsettled;
		}

		private static string Word(Sky sky)
		{
			return sky switch
			{
				Sky.Rain => "rain", 
				Sky.Snow => "snow", 
				Sky.Fog => "fog", 
				Sky.Shine => "shine", 
				_ => "unsettled", 
			};
		}

		internal static string BiomeTitle(string biomeName)
		{
			return biomeName switch
			{
				"BlackForest" => "the Black Forest", 
				"AshLands" => "the Ashlands", 
				"DeepNorth" => "the Deep North", 
				"Meadows" => "the Meadows", 
				"Swamp" => "the Swamp", 
				"Mountain" => "the Mountains", 
				"Plains" => "the Plains", 
				"Mistlands" => "the Mistlands", 
				"Ocean" => "the Ocean", 
				_ => "this land", 
			};
		}
	}
	[BepInPlugin("com.catosaurluna.forecastrune", "ForecastRune", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("valheim.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.catosaurluna.forecastrune";

		public const string PluginName = "ForecastRune";

		public const string PluginVersion = "0.1.0";

		internal static ConfigEntry<bool> ShowOverrideSource;

		internal static ConfigEntry<float> CooldownSeconds;

		internal static ConfigEntry<string> RecipeText;

		internal static ConfigEntry<string> CraftingStation;

		internal static ConfigEntry<int> MinStationLevel;

		private Harmony _harmony;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ShowOverrideSource = ((BaseUnityPlugin)this).Config.Bind<bool>("Forecast", "ShowOverrideSource", false, "Name the raid or zone that hides the sky when the rune refuses.");
			CooldownSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Item", "CooldownSeconds", 10f, new ConfigDescription("Real-time seconds between readings. 0 disables. Clamped to 0-15.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 15f), Array.Empty<object>()));
			RecipeText = ((BaseUnityPlugin)this).Config.Bind<string>("Item", "Recipe", "BoneFragments:6,GreydwarfEye:2,Resin:1", "Recipe as Prefab:Amount pairs, comma separated. Applied on world load.");
			CraftingStation = ((BaseUnityPlugin)this).Config.Bind<string>("Item", "CraftingStation", "piece_workbench", "Crafting station prefab name for the recipe.");
			MinStationLevel = ((BaseUnityPlugin)this).Config.Bind<int>("Item", "MinStationLevel", 1, new ConfigDescription("Minimum crafting station level.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>()));
			PrefabManager.OnVanillaPrefabsAvailable += RuneItem.Register;
			_harmony = new Harmony("com.catosaurluna.forecastrune");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			Log.LogInfo((object)"ForecastRune 0.1.0 loaded.");
		}
	}
	internal static class RuneItem
	{
		internal const string PrefabName = "ForecastRune";

		internal const string NameToken = "$item_forecastrune";

		internal const string DescToken = "$item_forecastrune_desc";

		private const string BasePrefab = "AmberPearl";

		internal static void Register()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Expected O, but got Unknown
			try
			{
				CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
				string text = "English";
				string text2 = "$item_forecastrune";
				localization.AddTranslation(ref text, ref text2, "Forecast Rune");
				text = "English";
				text2 = "$item_forecastrune_desc";
				localization.AddTranslation(ref text, ref text2, "A rune that speaks of the weather to come. Use it to hear the next few changes for the land you stand on.");
				ItemConfig val = new ItemConfig
				{
					Name = "$item_forecastrune",
					Description = "$item_forecastrune_desc",
					StackSize = 1
				};
				Sprite val2 = LoadIcon();
				if ((Object)(object)val2 != (Object)null)
				{
					val.Icons = (Sprite[])(object)new Sprite[1] { val2 };
				}
				CustomItem val3 = new CustomItem("ForecastRune", "AmberPearl", val);
				if (!ItemManager.Instance.AddItem(val3))
				{
					Plugin.Log.LogError((object)"ForecastRune: ItemManager rejected the item. Check that base prefab 'AmberPearl' exists.");
					return;
				}
				RecipeConfig val4 = new RecipeConfig
				{
					Name = "Recipe_ForecastRune",
					Item = "ForecastRune",
					CraftingStation = Plugin.CraftingStation.Value,
					MinStationLevel = Plugin.MinStationLevel.Value
				};
				string[] array = Plugin.RecipeText.Value.Split(new char[1] { ',' });
				foreach (string text3 in array)
				{
					string[] array2 = text3.Trim().Split(new char[1] { ':' });
					if (array2.Length != 2 || string.IsNullOrEmpty(array2[0]) || !int.TryParse(array2[1], out var result) || result <= 0)
					{
						Plugin.Log.LogWarning((object)("ForecastRune: ignoring invalid recipe entry '" + text3 + "'."));
					}
					else
					{
						val4.AddRequirement(array2[0].Trim(), result, 0);
					}
				}
				if (!ItemManager.Instance.AddRecipe(new CustomRecipe(val4)))
				{
					Plugin.Log.LogError((object)"ForecastRune: recipe was not added. Check the Recipe and CraftingStation settings.");
				}
				else
				{
					Plugin.Log.LogInfo((object)"ForecastRune: item and recipe registered.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("ForecastRune: item registration failed: " + ex));
			}
		}

		private static Sprite LoadIcon()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ForecastRune.icon.png");
			if (stream == null)
			{
				Plugin.Log.LogWarning((object)"ForecastRune: embedded icon not found; the item will use the base icon.");
				return null;
			}
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			Texture2D val = AssetUtils.LoadImage(memoryStream.ToArray());
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
		}
	}
	internal static class RuneParticles
	{
		private static readonly Color Teal = new Color(0.2f, 0.9f, 0.84f, 1f);

		private const float RingLifetime = 1.5f;

		private const float BurstDelay = 1.2f;

		private const float DestroyAfter = 4f;

		private static Material s_material;

		private static bool s_materialFailed;

		internal static void Play(Player player)
		{
			//IL_0022: 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_0033: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			try
			{
				Material material = GetMaterial();
				if (!((Object)(object)material == (Object)null) && !((Object)(object)player == (Object)null))
				{
					GameObject val = new GameObject("ForecastRuneFx");
					val.transform.position = ((Component)player).transform.position;
					Build(val.transform, "Ring", Vector3.zero, material, ring: true);
					Build(val.transform, "Burst", new Vector3(0f, 2f, 0f), material, ring: false);
					Object.Destroy((Object)val, 4f);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("ForecastRune: particle effect skipped: " + ex.Message));
			}
		}

		private static void Build(Transform parent, string name, Vector3 localOffset, Material material, bool ring)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: 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_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Expected O, but got Unknown
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: 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_0267: 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)
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			val.transform.localPosition = localOffset;
			ParticleSystem val2 = val.AddComponent<ParticleSystem>();
			val2.Stop(true, (ParticleSystemStopBehavior)0);
			MainModule main = val2.main;
			((MainModule)(ref main)).loop = false;
			((MainModule)(ref main)).playOnAwake = false;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).maxParticles = 300;
			((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(Teal);
			EmissionModule emission = val2.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(0f);
			ShapeModule shape = val2.shape;
			if (ring)
			{
				((MainModule)(ref main)).duration = 1.5f;
				((MainModule)(ref main)).startDelay = MinMaxCurve.op_Implicit(0f);
				((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(1.5f);
				((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0.4f);
				((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(0.16f);
				((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(110f);
				((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)10;
				((ShapeModule)(ref shape)).radius = 1.4f;
				((ShapeModule)(ref shape)).rotation = new Vector3(90f, 0f, 0f);
				VelocityOverLifetimeModule velocityOverLifetime = val2.velocityOverLifetime;
				((VelocityOverLifetimeModule)(ref velocityOverLifetime)).enabled = true;
				((VelocityOverLifetimeModule)(ref velocityOverLifetime)).orbitalY = MinMaxCurve.op_Implicit(2.6f);
				((VelocityOverLifetimeModule)(ref velocityOverLifetime)).y = MinMaxCurve.op_Implicit(1.1f);
			}
			else
			{
				((MainModule)(ref main)).duration = 0.8f;
				((MainModule)(ref main)).startDelay = MinMaxCurve.op_Implicit(1.2f);
				((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(0.9f);
				((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(3.2f);
				((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(0.12f);
				((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(0.3f);
				((EmissionModule)(ref emission)).SetBursts((Burst[])(object)new Burst[1]
				{
					new Burst(0f, (short)70)
				});
				((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)0;
				((ShapeModule)(ref shape)).radius = 0.25f;
			}
			ColorOverLifetimeModule colorOverLifetime = val2.colorOverLifetime;
			((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true;
			Gradient val3 = new Gradient();
			val3.SetKeys((GradientColorKey[])(object)new GradientColorKey[2]
			{
				new GradientColorKey(Teal, 0f),
				new GradientColorKey(Teal, 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[2]
			{
				new GradientAlphaKey(1f, 0f),
				new GradientAlphaKey(0f, 1f)
			});
			((ColorOverLifetimeModule)(ref colorOverLifetime)).color = new MinMaxGradient(val3);
			((Renderer)val.GetComponent<ParticleSystemRenderer>()).material = material;
			val2.Play();
		}

		private static Material GetMaterial()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			if ((Object)(object)s_material != (Object)null || s_materialFailed)
			{
				return s_material;
			}
			Shader val = Shader.Find("Sprites/Default");
			if ((Object)(object)val == (Object)null)
			{
				s_materialFailed = true;
				Plugin.Log.LogWarning((object)"ForecastRune: Sprites/Default shader not found; rune particles disabled.");
				return null;
			}
			s_material = new Material(val);
			s_material.mainTexture = (Texture)(object)CreateSoftDot();
			return s_material;
		}

		private static Texture2D CreateSoftDot()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(32, 32, (TextureFormat)4, false);
			Color[] array = (Color[])(object)new Color[1024];
			float num = 15.5f;
			for (int i = 0; i < 32; i++)
			{
				for (int j = 0; j < 32; j++)
				{
					float num2 = ((float)j - num) / num;
					float num3 = ((float)i - num) / num;
					float num4 = Mathf.Sqrt(num2 * num2 + num3 * num3);
					float num5 = Mathf.Clamp01(1f - num4);
					array[i * 32 + j] = new Color(1f, 1f, 1f, num5 * num5);
				}
			}
			val.SetPixels(array);
			val.Apply(false, true);
			((Texture)val).wrapMode = (TextureWrapMode)1;
			return val;
		}
	}
	internal static class RuneReading
	{
		private const float MaxCooldownSeconds = 15f;

		private const int DaysAhead = 2;

		private static float s_cooldownUntil;

		internal static void Use(Player player)
		{
			EnvMan instance = EnvMan.instance;
			double dayLength = (((Object)(object)instance != (Object)null) ? ((double)instance.m_dayLengthSec) : 1800.0);
			double duration = (((Object)(object)instance != (Object)null) ? ((double)instance.m_environmentDuration) : 666.0);
			double nowSeconds = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTimeSeconds() : 0.0);
			List<ForecastEntry> entries;
			string biomeName;
			string overrideName;
			OracleRefusal oracleRefusal = WeatherOracle.TryForecast(PeriodsUntilEndOfDay(nowSeconds, dayLength, duration, 2), out entries, out biomeName, out overrideName);
			if (oracleRefusal != OracleRefusal.None)
			{
				((Character)player).Message((MessageType)2, RefusalText(oracleRefusal, overrideName), 0, (Sprite)null, false);
				return;
			}
			if (entries.Count == 0)
			{
				((Character)player).Message((MessageType)2, "The sky holds no weather for this land.", 0, (Sprite)null, false);
				return;
			}
			float num = s_cooldownUntil - Time.time;
			if (num > 0f)
			{
				((Character)player).Message((MessageType)2, "The rune is still warm. (" + Mathf.CeilToInt(num) + "s)", 0, (Sprite)null, false);
				return;
			}
			List<string> list = ForecastFormatter.DailyLines(entries, dayLength, nowSeconds);
			string text = "<b>The rune speaks of " + ForecastFormatter.BiomeTitle(biomeName) + "</b>\n" + string.Join("\n", list.ToArray());
			((Character)player).Message((MessageType)2, text, 0, (Sprite)null, false);
			RuneParticles.Play(player);
			float num2 = Mathf.Clamp(Plugin.CooldownSeconds.Value, 0f, 15f);
			s_cooldownUntil = Time.time + num2;
		}

		private static int PeriodsUntilEndOfDay(double nowSeconds, double dayLength, double duration, int daysAhead)
		{
			if (dayLength <= 0.0 || duration <= 0.0)
			{
				return 0;
			}
			long num = (long)(((double)((long)(nowSeconds / dayLength) + daysAhead + 1) * dayLength - 1.0) / duration);
			long num2 = (long)nowSeconds / (long)duration;
			long num3 = num - num2;
			if (num3 >= 0)
			{
				return (int)num3;
			}
			return 0;
		}

		private static string RefusalText(OracleRefusal refusal, string overrideName)
		{
			switch (refusal)
			{
			case OracleRefusal.Interior:
				return "Stone hides the sky from the rune.";
			case OracleRefusal.TimeSkipping:
				return "The rune is silent while you sleep.";
			case OracleRefusal.Override:
				if (!Plugin.ShowOverrideSource.Value)
				{
					return "Something stronger than weather clouds the reading.";
				}
				return "Something stronger than weather clouds the reading (" + overrideName + ").";
			default:
				return "The rune has gone quiet.";
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "UseItem")]
	public static class UseItemPatch
	{
		[HarmonyPrefix]
		public static bool Prefix(Humanoid __instance, Inventory inventory, ItemData item, bool fromInventoryGui)
		{
			if (item == null || item.m_shared == null || item.m_shared.m_name != "$item_forecastrune")
			{
				return true;
			}
			if ((object)__instance != Player.m_localPlayer)
			{
				return true;
			}
			try
			{
				RuneReading.Use(Player.m_localPlayer);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("ForecastRune: reading failed: " + ex));
			}
			return false;
		}
	}
	internal enum OracleRefusal
	{
		None,
		NotReady,
		Interior,
		TimeSkipping,
		Override
	}
	internal struct ForecastEntry
	{
		public long Period;

		public double StartSeconds;

		public string EnvName;

		public bool IsWet;

		public bool IsFreezing;

		public bool IsFreezingAtNight;

		public bool IsCold;

		public bool IsAlwaysDark;
	}
	internal static class WeatherOracle
	{
		private static MethodInfo s_getBiome;

		private static MethodInfo s_getOverride;

		private static MethodInfo s_selectWeighted;

		private static bool s_bound;

		internal static bool IsBound => s_bound;

		internal static bool Bind()
		{
			if (s_bound)
			{
				return true;
			}
			s_getBiome = typeof(EnvMan).GetMethod("GetBiome", BindingFlags.Instance | BindingFlags.NonPublic);
			s_getOverride = typeof(EnvMan).GetMethod("GetEnvironmentOverride", BindingFlags.Instance | BindingFlags.NonPublic);
			s_selectWeighted = typeof(EnvMan).GetMethod("SelectWeightedEnvironment", BindingFlags.Instance | BindingFlags.NonPublic);
			s_bound = s_getBiome != null && s_getOverride != null && s_selectWeighted != null && s_getBiome.ReturnType == typeof(BiomeSector) && s_getOverride.ReturnType == typeof(string) && s_selectWeighted.ReturnType == typeof(EnvSetup);
			return s_bound;
		}

		internal static OracleRefusal TryForecast(int count, out List<ForecastEntry> entries, out string biomeName, out string overrideName)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			entries = new List<ForecastEntry>();
			biomeName = null;
			overrideName = null;
			EnvMan instance = EnvMan.instance;
			ZNet instance2 = ZNet.instance;
			WorldGenerator instance3 = WorldGenerator.instance;
			Player localPlayer = Player.m_localPlayer;
			Camera mainCamera = Utils.GetMainCamera();
			if (!Bind() || (Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || instance3 == null || (Object)(object)localPlayer == (Object)null || (Object)(object)mainCamera == (Object)null)
			{
				return OracleRefusal.NotReady;
			}
			if (((Character)localPlayer).InInterior())
			{
				return OracleRefusal.Interior;
			}
			if (instance.IsTimeSkipping())
			{
				return OracleRefusal.TimeSkipping;
			}
			string text = (string)s_getOverride.Invoke(instance, null);
			if (!string.IsNullOrEmpty(text))
			{
				overrideName = text;
				return OracleRefusal.Override;
			}
			BiomeSector val = (BiomeSector)s_getBiome.Invoke(instance, null);
			biomeName = ((object)Unsafe.As<Biome, Biome>(ref val.Biome)/*cast due to .constrained prefix*/).ToString();
			Vector3 position = ((Component)mainCamera).transform.position;
			bool ash = WorldGenerator.IsAshlands(position.x, position.z);
			bool deep = WorldGenerator.IsDeepnorth(position.x, position.y);
			List<EnvEntry> availableEnvironments = instance.GetAvailableEnvironments(val);
			if (availableEnvironments == null || availableEnvironments.Count == 0)
			{
				return OracleRefusal.None;
			}
			List<EnvEntry> list = new List<EnvEntry>(availableEnvironments);
			long environmentDuration = instance.m_environmentDuration;
			if (environmentDuration <= 0)
			{
				return OracleRefusal.NotReady;
			}
			long num = (long)instance2.GetTimeSeconds() / environmentDuration;
			for (long num2 = num; num2 <= num + count; num2++)
			{
				EnvSetup val2 = RollPeriod(instance, list, num2, ash, deep);
				ForecastEntry item = new ForecastEntry
				{
					Period = num2,
					StartSeconds = (double)num2 * (double)environmentDuration,
					EnvName = val2?.m_name,
					IsWet = (val2?.m_isWet ?? false),
					IsFreezing = (val2?.m_isFreezing ?? false),
					IsFreezingAtNight = (val2?.m_isFreezingAtNight ?? false),
					IsCold = (val2?.m_isCold ?? false),
					IsAlwaysDark = (val2?.m_alwaysDark ?? false)
				};
				entries.Add(item);
			}
			return OracleRefusal.None;
		}

		private static EnvSetup RollPeriod(EnvMan env, List<EnvEntry> list, long period, bool ash, bool deep)
		{
			//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_007a: 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_0028: Expected O, but got Unknown
			State state = Random.state;
			try
			{
				Random.InitState((int)period);
				EnvSetup result = (EnvSetup)s_selectWeighted.Invoke(env, new object[1] { list });
				foreach (EnvEntry item in list)
				{
					if (item.m_ashlandsOverride && ash)
					{
						result = item.m_env;
					}
					if (item.m_deepnorthOverride && deep)
					{
						result = item.m_env;
					}
				}
				return result;
			}
			finally
			{
				Random.state = state;
			}
		}
	}
}