using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using BepInEx;
using BepInEx.Logging;
using DysonSphereMods.Shared;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Valoneu")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © 2026")]
[assembly: AssemblyDescription("PlanetMinerFast")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a20df26b6b4e9b5b08b56dea2d5095efdc61da88")]
[assembly: AssemblyProduct("DysonSphereMods")]
[assembly: AssemblyTitle("PlanetMinerFast")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Microsoft.CodeAnalysis.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 DysonSphereMods.Shared
{
public static class Log
{
private static ManualLogSource _logger;
public static void Init(ManualLogSource logger)
{
_logger = logger;
}
public static void Debug(object data)
{
ManualLogSource logger = _logger;
if (logger != null)
{
logger.LogDebug(data);
}
}
public static void Info(object data)
{
ManualLogSource logger = _logger;
if (logger != null)
{
logger.LogInfo(data);
}
}
public static void Warning(object data)
{
ManualLogSource logger = _logger;
if (logger != null)
{
logger.LogWarning(data);
}
}
public static void Error(object data)
{
ManualLogSource logger = _logger;
if (logger != null)
{
logger.LogError(data);
}
}
public static void Fatal(object data)
{
ManualLogSource logger = _logger;
if (logger != null)
{
logger.LogFatal(data);
}
}
public static void Message(object data)
{
ManualLogSource logger = _logger;
if (logger != null)
{
logger.LogMessage(data);
}
}
public static void LogOnce(string msg, ref bool flag, params object[] args)
{
if (flag)
{
return;
}
flag = true;
try
{
string[] array = ((args == null) ? Array.Empty<string>() : args.Select((object arg) => (arg != null) ? ((!(arg is int) && !(arg is string) && !arg.GetType().IsPrimitive) ? JsonUtility.ToJson(arg) : arg.ToString()) : "null").ToArray());
object[] args2 = array;
Info(string.Format(msg, args2));
}
catch (Exception arg2)
{
Warning($"LogOnce failed to format message: {msg}. Exception: {arg2}");
}
}
}
public static class MultiplierService
{
private static readonly Dictionary<string, float> _multipliers = new Dictionary<string, float>();
private static bool _isDirty;
public static event Action OnMultipliersChanged;
public static void SetMultiplier(string key, float value)
{
if (!_multipliers.TryGetValue(key, out var value2) || Math.Abs(value2 - value) > 0.0001f)
{
_multipliers[key] = value;
_isDirty = true;
}
}
public static float GetMultiplier(string key, float defaultValue = 1f)
{
if (!_multipliers.TryGetValue(key, out var value))
{
return defaultValue;
}
return value;
}
public static void CommitChanges()
{
if (_isDirty)
{
_isDirty = false;
MultiplierService.OnMultipliersChanged?.Invoke();
}
}
}
public static class TickManager
{
private static long _lastSlowTick = -1L;
private static long _lastLazyTick = -1L;
private static bool _patched = false;
public static event Action OnSlowTick;
public static event Action OnLazyTick;
public static void Patch(Harmony harmony)
{
if (!_patched)
{
_patched = true;
harmony.PatchAll(typeof(TickManager));
}
}
[HarmonyPatch(typeof(GameMain), "Begin")]
[HarmonyPostfix]
public static void Init()
{
_lastSlowTick = -1L;
_lastLazyTick = -1L;
}
[HarmonyPatch(typeof(GameLogic), "LogicFrame")]
[HarmonyPostfix]
public static void GameTick()
{
long gameTick = GameMain.gameTick;
if (gameTick / 60 > _lastSlowTick)
{
_lastSlowTick = gameTick / 60;
TickManager.OnSlowTick?.Invoke();
}
if (gameTick / 600 > _lastLazyTick)
{
_lastLazyTick = gameTick / 600;
TickManager.OnLazyTick?.Invoke();
}
}
}
public abstract class WindowBase
{
public Rect WindowRect;
protected Vector2 ScrollPos;
private bool _isResizing;
private Rect _resizeRect = new Rect(0f, 0f, 15f, 15f);
public Vector2 MinSize = new Vector2(300f, 200f);
public int WindowId { get; protected set; }
public string Title { get; set; }
public bool IsVisible { get; set; }
protected WindowBase(int windowId, string title, Rect defaultRect)
{
//IL_0015: Unknown result type (might be due to invalid IL or missing references)
//IL_001a: 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_002f: Unknown result type (might be due to invalid IL or missing references)
//IL_0049: Unknown result type (might be due to invalid IL or missing references)
//IL_004a: Unknown result type (might be due to invalid IL or missing references)
WindowId = windowId;
Title = title;
WindowRect = defaultRect;
}
public virtual void OnGUI()
{
//IL_001d: 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_003b: Unknown result type (might be due to invalid IL or missing references)
//IL_0050: Expected O, but got Unknown
//IL_004b: Unknown result type (might be due to invalid IL or missing references)
//IL_0050: Unknown result type (might be due to invalid IL or missing references)
//IL_0055: Unknown result type (might be due to invalid IL or missing references)
if (IsVisible)
{
GUI.backgroundColor = new Color(0.08f, 0.12f, 0.22f, 0.95f);
WindowRect = GUILayout.Window(WindowId, WindowRect, new WindowFunction(DrawWindowInternal), Title, Array.Empty<GUILayoutOption>());
GUI.backgroundColor = Color.white;
((Rect)(ref WindowRect)).x = Mathf.Clamp(((Rect)(ref WindowRect)).x, 0f - ((Rect)(ref WindowRect)).width + 50f, (float)(Screen.width - 50));
((Rect)(ref WindowRect)).y = Mathf.Clamp(((Rect)(ref WindowRect)).y, -20f, (float)(Screen.height - 50));
}
}
private void DrawWindowInternal(int id)
{
//IL_0008: Unknown result type (might be due to invalid IL or missing references)
//IL_0012: Unknown result type (might be due to invalid IL or missing references)
//IL_0017: 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_009a: Unknown result type (might be due to invalid IL or missing references)
//IL_009f: 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_00af: Unknown result type (might be due to invalid IL or missing references)
//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
//IL_00d8: Expected O, but got Unknown
//IL_00dd: Expected O, but got Unknown
//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
//IL_0115: Unknown result type (might be due to invalid IL or missing references)
//IL_011b: Invalid comparison between Unknown and I4
//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
//IL_012a: Unknown result type (might be due to invalid IL or missing references)
//IL_0130: Invalid comparison between Unknown and I4
//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
//IL_014d: Unknown result type (might be due to invalid IL or missing references)
//IL_016a: Unknown result type (might be due to invalid IL or missing references)
DrawWindowHeader();
ScrollPos = GUILayout.BeginScrollView(ScrollPos, Array.Empty<GUILayoutOption>());
DrawWindowContent();
GUILayout.EndScrollView();
DrawWindowFooter();
((Rect)(ref _resizeRect)).x = ((Rect)(ref WindowRect)).width - 20f;
((Rect)(ref _resizeRect)).y = ((Rect)(ref WindowRect)).height - 20f;
((Rect)(ref _resizeRect)).width = 20f;
((Rect)(ref _resizeRect)).height = 20f;
GUI.Label(_resizeRect, "↘", new GUIStyle(GUI.skin.label)
{
alignment = (TextAnchor)4,
fontSize = 20,
normal = new GUIStyleState
{
textColor = new Color(0.6f, 0.6f, 0.6f, 0.8f)
}
});
Event current = Event.current;
bool flag = false;
if ((int)current.type == 0 && ((Rect)(ref _resizeRect)).Contains(current.mousePosition))
{
_isResizing = true;
flag = true;
current.Use();
}
else if ((int)current.type == 1)
{
_isResizing = false;
}
else if ((int)current.type == 3 && _isResizing)
{
ref Rect windowRect = ref WindowRect;
((Rect)(ref windowRect)).width = ((Rect)(ref windowRect)).width + current.delta.x;
ref Rect windowRect2 = ref WindowRect;
((Rect)(ref windowRect2)).height = ((Rect)(ref windowRect2)).height + current.delta.y;
((Rect)(ref WindowRect)).width = Mathf.Max(MinSize.x, ((Rect)(ref WindowRect)).width);
((Rect)(ref WindowRect)).height = Mathf.Max(MinSize.y, ((Rect)(ref WindowRect)).height);
current.Use();
}
if ((int)current.type == 0 && !flag)
{
GUIUtility.keyboardControl = 0;
}
GUI.DragWindow();
}
protected virtual void DrawWindowHeader()
{
}
protected abstract void DrawWindowContent();
protected virtual void DrawWindowFooter()
{
}
public virtual void Toggle()
{
IsVisible = !IsVisible;
}
}
}
namespace PlanetMinerFast
{
[BepInPlugin("com.Valoneu.PlanetMinerFast", "PlanetMinerFast", "1.0.0")]
public class PlanetMinerFastPlugin : BaseUnityPlugin
{
private class PlanetVeinCache
{
public Dictionary<int, List<int>> ItemToVeinIndices = new Dictionary<int, List<int>>();
public Dictionary<int, float> MinedFractions = new Dictionary<int, float>();
public List<int> ActiveOres = new List<int>();
public int[] PendingProductRegister = new int[12000];
public long LastScanTick = -1L;
public double CostFrac;
public bool IsDirty = true;
}
public const long ENERGY_COST = 20000000L;
private static Harmony _harmony;
private static PlanetVeinCache[] _veinCaches = new PlanetVeinCache[1024];
private static bool _weaverChecked = false;
private static FastInvokeHandler _weaverGetPlanetHandler;
private static FastInvokeHandler _weaverGetStatusHandler;
private static object _weaverRunningEnum;
private void Awake()
{
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_001a: Expected O, but got Unknown
Log.Init(((BaseUnityPlugin)this).Logger);
_harmony = new Harmony("com.Valoneu.PlanetMinerFast");
TickManager.Patch(_harmony);
TickManager.OnSlowTick += OnSlowTick;
_harmony.PatchAll(typeof(PlanetMinerFastPlugin));
Log.Info("PlanetMinerFast 1.0.0 Loaded - Optimized Mining Active");
}
private void OnDestroy()
{
TickManager.OnSlowTick -= OnSlowTick;
Harmony harmony = _harmony;
if (harmony != null)
{
harmony.UnpatchSelf();
}
}
private static PlanetVeinCache GetCache(PlanetFactory factory)
{
if (factory == null || factory.index >= _veinCaches.Length)
{
return new PlanetVeinCache();
}
PlanetVeinCache planetVeinCache = _veinCaches[factory.index];
if (planetVeinCache == null)
{
planetVeinCache = new PlanetVeinCache();
_veinCaches[factory.index] = planetVeinCache;
}
if (planetVeinCache.IsDirty || GameMain.gameTick - planetVeinCache.LastScanTick > 3600)
{
planetVeinCache.ItemToVeinIndices.Clear();
VeinData[] veinPool = factory.veinPool;
int num = 0;
for (int i = 1; i < factory.veinCursor; i++)
{
if (veinPool[i].id == i && veinPool[i].amount > 0 && veinPool[i].productId > 0)
{
int productId = veinPool[i].productId;
if (!planetVeinCache.ItemToVeinIndices.TryGetValue(productId, out var value))
{
value = new List<int>();
planetVeinCache.ItemToVeinIndices[productId] = value;
}
value.Add(i);
num++;
}
}
planetVeinCache.ActiveOres = planetVeinCache.ItemToVeinIndices.Keys.ToList();
planetVeinCache.IsDirty = false;
planetVeinCache.LastScanTick = GameMain.gameTick;
Log.Debug($"Rebuilt vein cache for planet {factory.planetId}: found {num} active veins.");
}
return planetVeinCache;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(PlanetFactory), "RemoveVeinWithComponents")]
private static void PlanetFactory_RemoveVein_Postfix(PlanetFactory __instance)
{
if (__instance != null && __instance.index < _veinCaches.Length && _veinCaches[__instance.index] != null)
{
_veinCaches[__instance.index].IsDirty = true;
}
}
private void OnSlowTick()
{
if (GameMain.data == null || GameMain.data.factories == null)
{
return;
}
PlanetFactory[] factories = GameMain.data.factories;
foreach (PlanetFactory val in factories)
{
if (val != null && !IsWeaverOptimizing(val.planet))
{
ProcessFactory(val);
}
}
}
private void ProcessFactory(PlanetFactory factory)
{
//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
//IL_00c6: Invalid comparison between Unknown and I4
//IL_0180: Unknown result type (might be due to invalid IL or missing references)
//IL_0186: Invalid comparison between Unknown and I4
//IL_0279: Unknown result type (might be due to invalid IL or missing references)
//IL_027e: 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)
//IL_0289: Unknown result type (might be due to invalid IL or missing references)
GameHistoryData history = GameMain.history;
float miningSpeedScale = history.miningSpeedScale;
if (miningSpeedScale <= 0.0001f)
{
return;
}
PlanetVeinCache cache = GetCache(factory);
PlanetTransport transport = factory.transport;
int[] array = GameMain.statistics.production.factoryStatPool[factory.index]?.productRegister;
float miningCostRate = history.miningCostRate;
VeinData[] veinPool = factory.veinPool;
StationComponent[] stationPool = transport.stationPool;
foreach (StationComponent val in stationPool)
{
if (val == null || val.id == 0 || val.storage == null)
{
continue;
}
if ((float)val.energy < (float)val.energyMax * 0.2f)
{
GenerateEnergyFromAnySlot(val);
}
for (int j = 0; j < val.storage.Length; j++)
{
if ((int)val.storage[j].localLogic != 2)
{
continue;
}
int itemId = val.storage[j].itemId;
if (itemId <= 0 || val.storage[j].count >= val.storage[j].max)
{
continue;
}
float num = 0f;
float num2 = 1f;
List<int> value;
if (itemId == factory.planet.waterItemId)
{
if (val.energy >= 20000000)
{
num = 100f * miningSpeedScale * num2;
}
}
else if (cache.ItemToVeinIndices.TryGetValue(itemId, out value) && val.energy >= 20000000)
{
bool flag = (int)LDB.veins.GetVeinTypeByItemId(itemId) == 7;
float num3 = 1f * miningSpeedScale * num2;
foreach (int item in value)
{
if (veinPool[item].id != 0 && veinPool[item].amount > 0)
{
if (flag)
{
num += (float)veinPool[item].amount / 6000f * miningSpeedScale * num2;
}
else if (TryMineVein(veinPool, item, miningCostRate, num3, factory, cache))
{
num += num3;
}
}
}
}
if (!(num > 0.001f))
{
continue;
}
cache.MinedFractions.TryGetValue(itemId, out var value2);
value2 += num;
int num4 = (int)value2;
if (num4 > 0)
{
value2 -= (float)num4;
val.storage[j].count += num4;
if (array != null)
{
EVeinType veinTypeByItemId = LDB.veins.GetVeinTypeByItemId(itemId);
factory.AddMiningFlagUnsafe(veinTypeByItemId);
factory.AddVeinMiningFlagUnsafe(veinTypeByItemId);
if (itemId < cache.PendingProductRegister.Length)
{
Interlocked.Add(ref cache.PendingProductRegister[itemId], num4);
}
}
val.energy -= 20000000;
}
cache.MinedFractions[itemId] = value2;
}
}
}
private static bool TryMineVein(VeinData[] veinPool, int index, float miningRate, float minedAmount, PlanetFactory factory, PlanetVeinCache cache)
{
//IL_0110: Unknown result type (might be due to invalid IL or missing references)
//IL_0116: Expected I4, but got Unknown
//IL_012a: Unknown result type (might be due to invalid IL or missing references)
//IL_012f: Unknown result type (might be due to invalid IL or missing references)
//IL_0144: Unknown result type (might be due to invalid IL or missing references)
if (veinPool[index].id == 0 || veinPool[index].amount <= 0)
{
return false;
}
if (miningRate > 1E-05f)
{
cache.CostFrac += miningRate * minedAmount;
int num = (int)cache.CostFrac;
if (num > 0)
{
cache.CostFrac -= num;
if (num > veinPool[index].amount)
{
num = veinPool[index].amount;
}
veinPool[index].amount -= num;
factory.veinGroups[veinPool[index].groupIndex].amount -= num;
factory.veinAnimPool[index].time = ((veinPool[index].amount >= 20000) ? 0f : ((float)(1.0 - (double)veinPool[index].amount * 4.999999873689376E-05)));
if (veinPool[index].amount <= 0)
{
int num2 = (int)veinPool[index].type;
int groupIndex = veinPool[index].groupIndex;
Vector3 pos = veinPool[index].pos;
factory.RemoveVeinWithComponents(index);
factory.RecalculateVeinGroup(groupIndex);
factory.NotifyVeinExhausted(num2, groupIndex, pos);
}
}
}
return true;
}
private static void GenerateEnergyFromAnySlot(StationComponent sc)
{
//IL_000e: Unknown result type (might be due to invalid IL or missing references)
//IL_0013: 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_0020: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
//IL_0074: Unknown result type (might be due to invalid IL or missing references)
//IL_0088: Unknown result type (might be due to invalid IL or missing references)
//IL_008f: Unknown result type (might be due to invalid IL or missing references)
//IL_007c: Unknown result type (might be due to invalid IL or missing references)
//IL_0117: Unknown result type (might be due to invalid IL or missing references)
//IL_011e: Unknown result type (might be due to invalid IL or missing references)
//IL_0128: Unknown result type (might be due to invalid IL or missing references)
for (int i = 0; i < sc.storage.Length; i++)
{
StationStore val = sc.storage[i];
if (val.itemId <= 0 || val.count <= 0)
{
continue;
}
ItemProto val2 = ((ProtoSet<ItemProto>)(object)LDB.items).Select(val.itemId);
if (val2 != null && val2.HeatValue > 0)
{
int num = Math.Min(10, (int)((sc.energyMax - sc.energy) / val2.HeatValue));
if (num <= 0)
{
num = 1;
}
if (num > val.count)
{
num = val.count;
}
float num2 = 1f + (float)val.inc / (float)val.count * 0.1f;
sc.energy += (long)((float)(num * val2.HeatValue) * num2);
sc.storage[i].count -= num;
if (sc.storage[i].count <= 0)
{
sc.storage[i].itemId = 0;
sc.storage[i].inc = 0;
}
else
{
sc.storage[i].inc = (int)((float)val.inc * (float)(val.count - num) / (float)val.count);
}
if ((float)sc.energy >= (float)sc.energyMax * 0.9f)
{
break;
}
}
}
}
private static bool IsWeaverOptimizing(PlanetData planet)
{
if (planet == null)
{
return false;
}
if (!_weaverChecked)
{
try
{
Type type = Type.GetType("Weaver.Optimizations.IOptimizedPlanet, DSP_Weaver");
if (type != null)
{
MethodInfo methodInfo = Type.GetType("Weaver.Optimizations.OptimizedStarCluster, DSP_Weaver")?.GetMethod("GetOptimizedPlanet", BindingFlags.Static | BindingFlags.Public);
if (methodInfo != null)
{
_weaverGetPlanetHandler = MethodInvoker.GetHandler(methodInfo, false);
}
PropertyInfo property = type.GetProperty("Status");
if (property != null)
{
_weaverGetStatusHandler = MethodInvoker.GetHandler(property.GetGetMethod(), false);
}
Type type2 = Type.GetType("Weaver.Optimizations.OptimizedPlanetStatus, DSP_Weaver");
if (type2 != null)
{
_weaverRunningEnum = Enum.Parse(type2, "Running");
}
}
}
catch
{
}
_weaverChecked = true;
}
if (_weaverGetPlanetHandler == null || _weaverGetStatusHandler == null)
{
return false;
}
try
{
object obj2 = _weaverGetPlanetHandler.Invoke((object)null, new object[1] { planet });
if (obj2 != null)
{
return _weaverGetStatusHandler.Invoke(obj2, Array.Empty<object>()).Equals(_weaverRunningEnum);
}
}
catch
{
}
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(FactoryProductionStat), "PrepareTick")]
private static void FactoryProductionStat_PrepareTick_Postfix(FactoryProductionStat __instance)
{
if (__instance == null || __instance.productRegister == null || GameMain.statistics?.production?.factoryStatPool == null)
{
return;
}
FactoryProductionStat[] factoryStatPool = GameMain.statistics.production.factoryStatPool;
for (int i = 0; i < factoryStatPool.Length; i++)
{
if (factoryStatPool[i] != __instance)
{
continue;
}
if (i >= _veinCaches.Length)
{
break;
}
PlanetVeinCache planetVeinCache = _veinCaches[i];
if (planetVeinCache == null)
{
break;
}
bool flag = false;
for (int j = 0; j < planetVeinCache.ActiveOres.Count; j++)
{
int num = planetVeinCache.ActiveOres[j];
if (num < planetVeinCache.PendingProductRegister.Length && planetVeinCache.PendingProductRegister[num] > 0)
{
flag = true;
break;
}
}
if (!flag)
{
continue;
}
for (int k = 0; k < planetVeinCache.ActiveOres.Count; k++)
{
int num2 = planetVeinCache.ActiveOres[k];
if (num2 < planetVeinCache.PendingProductRegister.Length)
{
int num3 = Interlocked.Exchange(ref planetVeinCache.PendingProductRegister[num2], 0);
if (num3 > 0 && num2 < __instance.productRegister.Length)
{
__instance.productRegister[num2] += num3;
}
}
}
break;
}
}
}
public static class MyPluginInfo
{
public const string PLUGIN_GUID = "com.Valoneu.PlanetMinerFast";
public const string PLUGIN_NAME = "PlanetMinerFast";
public const string PLUGIN_VERSION = "1.0.0";
}
}