fix(uxassist): exclude protected veins from mining displays

Use productive veins for mining-rate estimates, resource analysis and hover counts without mutating miners or reserves. Keep zero-cost mining productive, including CheatEnabler infinite resources.

Refs #95
This commit is contained in:
soarqin committed 2026-10-11 03:48:04 +08:00
1 parent 47ba29447c
commit 06a8445907
6 files changed
+203 -4

No files matched your search

+3 -2
View File
@@ -35,9 +35,10 @@ public static class ResourcePatch
{
static private readonly float InfiniteResourceRate = 0f;
// Harmony transpiler: Transpiler
// Target: FactorySystem.GameTick, GameLogic._miner_parallel, PlanetTransport.GameTick, UIChartAstroResource.CalculateMaxAmount, UIChartVeinGroup.CalculateMaxAmount, UIControlPanelAdvancedMinerEntry._OnUpdate, UIControlPanelVeinCollectorPanel._OnUpdate, UIMinerWindow._OnUpdate, UIMiningUpgradeLabel.Update, UIVeinCollectorPanel._OnUpdate
// Target: FactorySystem.GameTick, GameLogic._miner_parallel, PlanetTransport.GameTick, FactoryPatch.GetMiningCostRate (UXAssist), UIChartAstroResource.CalculateMaxAmount, UIChartVeinGroup.CalculateMaxAmount, UIControlPanelAdvancedMinerEntry._OnUpdate, UIControlPanelVeinCollectorPanel._OnUpdate, UIMinerWindow._OnUpdate, UIMiningUpgradeLabel.Update, UIVeinCollectorPanel._OnUpdate
// Fallback: None — patch will fail loudly if the target method body changes.
[HarmonyTranspiler]
[HarmonyPatch(typeof(UXAssist.Patches.Factory.FactoryPatch), nameof(UXAssist.Patches.Factory.FactoryPatch.GetMiningCostRate))]
[HarmonyPatch(typeof(FactorySystem), nameof(FactorySystem.GameTick), typeof(long), typeof(bool))]
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic._miner_parallel))]
[HarmonyPatch(typeof(PlanetTransport), nameof(PlanetTransport.GameTick))]
@@ -128,4 +129,4 @@ public static class ResourcePatch
return matcher.InstructionEnumeration();
}
}
}
}
+2
View File
@@ -4,6 +4,7 @@
## Changlog
* 1.6.2 - Unrelease
* `Protect veins from exhaustion`: Exclude protected veins from mining-rate estimates, mining resource counts, and miner hover counts while retaining their remaining reserves.
* `Dismantle blueprint selected buildings`: Respect sandbox instant-dismantle settings when discarding logistics station contents, and return them normally outside instant dismantling.
* `Treat stack items as single in monitor components`: Fix the option taking effect at game startup when disabled, until toggled on and off.
* `Building options`: Honor saved toggle states at startup for off-grid construction, power-pole dragging, fast tank transfers, and Ctrl+Shift belt pickup.
@@ -430,6 +431,7 @@
## 更新日志
* 1.6.2 - Unreleased
* `保护矿脉不会枯竭`:开采速度估算、开采中资源数量和采矿机悬浮信息不再把受保护的矿脉计入开采;仍保留剩余储量显示。
* `拆除蓝图选中的建筑`:按沙盒模式的瞬间拆除设置销毁物流站库存;常规拆除时仍正常返还库存。
* `在流速计中将堆叠物品视为单个物品`:修复未勾选时仍在启动游戏后生效、必须切换一次才能关闭的问题。
* `建造选项`:修复不对齐网格建造、拖建电线杆、储液罐快速存取和 Ctrl+Shift 拾取整段传送带物品在启动时忽略已保存开关的问题。
+5
View File
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using CommonAPI.Systems;
using UnityEngine;
@@ -12,6 +13,10 @@ namespace UXAssist.Patches.Factory;
[ModFeature("Factory", Order = 10)]
public static class FactoryPatch
{
/// <summary>Returns the mining cost rate shared by vein-protection display calculations.</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static float GetMiningCostRate(GameHistoryData history) => history.miningCostRate;
public static ConfigEntry<bool> UnlimitInteractiveEnabled;
public static ConfigEntry<bool> RemoveSomeConditionEnabled;
public static ConfigEntry<bool> NightLightEnabled;
@@ -8,7 +8,7 @@ using GameLogicProc = UXAssist.Common.GameLogic;
namespace UXAssist.Patches.Factory;
[ModFeature("VeinProtection")]
internal static class VeinProtectionPatch
internal static partial class VeinProtectionPatch
{
public static void Enable(bool enable)
{
@@ -30,7 +30,7 @@ internal static class VeinProtectionPatch
GameLogicProc.OnGameEnd -= ProtectVeinsFromExhaustion.ResetState;
}
internal class ProtectVeinsFromExhaustion : PatchImpl<ProtectVeinsFromExhaustion>
internal partial class ProtectVeinsFromExhaustion : PatchImpl<ProtectVeinsFromExhaustion>
{
public static int KeepVeinAmount = 100;
public static float KeepOilSpeed = 1f;
@@ -0,0 +1,189 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using UXAssist.Common.Patching;
namespace UXAssist.Patches.Factory;
internal static partial class VeinProtectionPatch
{
internal partial class ProtectVeinsFromExhaustion
{
private static bool IsProtectedVein(ref VeinData vein, float miningRate)
{
if (miningRate <= 0f || vein.id <= 0 || vein.amount <= 0) return false;
return vein.type == EVeinType.Oil
? _keepOilAmount > 2500 && vein.amount <= _keepOilAmount
: vein.amount <= KeepVeinAmount;
}
private static int GetMiningVeinCount(ref MinerComponent miner, PlanetFactory factory)
{
var miningRate = FactoryPatch.GetMiningCostRate(factory.gameData.history);
var count = 0;
for (var i = 0; i < miner.veinCount; i++)
{
ref var vein = ref factory.veinPool[miner.veins[i]];
if (vein.id > 0 && vein.amount > 0 && !IsProtectedVein(ref vein, miningRate)) count++;
}
return count;
}
private static int GetMiningVeinAmount(ref VeinData vein, PlanetFactory factory)
{
return IsProtectedVein(ref vein, FactoryPatch.GetMiningCostRate(factory.gameData.history)) ? 0 : vein.amount;
}
// Harmony transpiler: MiningSpeed_Transpiler
// Target: ProductionExtraInfoCalculator.CalculateFactory, UIReferenceSpeedTip.AddEntryDataWithFactory, UIMinerWindow._OnUpdate
// Fallback: Return the original instructions if the native mining-speed multiplications cannot be found.
[HarmonyTranspiler]
[HarmonyPatch(typeof(ProductionExtraInfoCalculator), nameof(ProductionExtraInfoCalculator.CalculateFactory))]
[HarmonyPatch(typeof(UIReferenceSpeedTip), nameof(UIReferenceSpeedTip.AddEntryDataWithFactory))]
[HarmonyPatch(typeof(UIMinerWindow), nameof(UIMinerWindow._OnUpdate))]
private static IEnumerable<CodeInstruction> MiningSpeed_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase __originalMethod)
{
var original = instructions.ToList();
var matcher = new CodeMatcher(original, generator);
var factoryParameter = __originalMethod.GetParameters().Select((p, i) => (p, i)).FirstOrDefault(v => v.p.ParameterType == typeof(PlanetFactory));
var factoryLoad = factoryParameter.p != null
? new[] { new CodeInstruction(OpCodes.Ldarg, factoryParameter.i + (__originalMethod.IsStatic ? 0 : 1)) }
: new[] { new CodeInstruction(OpCodes.Ldarg_0), new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(UIMinerWindow), nameof(UIMinerWindow.factory))) };
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(MinerComponent), nameof(MinerComponent.veinCount))),
new CodeMatch(ci => ci.opcode == OpCodes.Conv_R8 || ci.opcode == OpCodes.Conv_R4));
if (matcher.IsInvalid) return matcher.Finish(original, UXAssist.Logger, nameof(MiningSpeed_Transpiler));
matcher.Repeat(m => ReplaceRead(m, factoryLoad, nameof(GetMiningVeinCount)));
matcher.Start().MatchForward(false,
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(VeinData), nameof(VeinData.amount))),
new CodeMatch(OpCodes.Conv_R8),
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(typeof(VeinData), nameof(VeinData.oilSpeedMultiplier))));
var oilMatched = matcher.IsValid;
if (oilMatched) matcher.Repeat(m => ReplaceRead(m, factoryLoad, nameof(GetMiningVeinAmount)));
matcher.Start().MatchForward(false,
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(VeinData), nameof(VeinData.amount))),
new CodeMatch(OpCodes.Conv_R8),
new CodeMatch(OpCodes.Mul),
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(typeof(VeinData), nameof(VeinData.oilSpeedMultiplier))));
if (matcher.IsValid)
{
oilMatched = true;
matcher.Repeat(m => ReplaceRead(m, factoryLoad, nameof(GetMiningVeinAmount)));
}
if (!oilMatched) return matcher.Finish(original, UXAssist.Logger, nameof(MiningSpeed_Transpiler));
return matcher.InstructionEnumeration();
}
private static void ReplaceRead(CodeMatcher matcher, CodeInstruction[] factoryLoad, string helper)
{
var labels = matcher.Labels.ToArray();
var blocks = matcher.Instruction.blocks.ToArray();
matcher.RemoveInstruction();
var replacement = factoryLoad.Select(ci => ci.Clone()).Append(new CodeInstruction(OpCodes.Call,
AccessTools.Method(typeof(ProtectVeinsFromExhaustion), helper))).ToArray();
replacement[0].labels.AddRange(labels);
replacement[0].blocks.AddRange(blocks);
matcher.InsertAndAdvance(replacement);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(EntityBriefInfo), nameof(EntityBriefInfo.SetBriefInfo))]
private static void EntityBriefInfo_SetBriefInfo_Postfix(EntityBriefInfo __instance, PlanetFactory _factory, int _entityId)
{
if (_factory == null || _entityId <= 0) return;
var minerId = _factory.entityPool[_entityId].minerId;
if (minerId <= 0) return;
ref var miner = ref _factory.factorySystem.minerPool[minerId];
if (miner.type == EMinerType.Water) return;
var miningRate = FactoryPatch.GetMiningCostRate(_factory.gameData.history);
for (var i = 0; i < miner.veinCount; i++)
{
ref var vein = ref _factory.veinPool[miner.veins[i]];
if (IsProtectedVein(ref vein, miningRate)) __instance.equipment.Add((int)vein.type, -1, 0);
}
}
[HarmonyPostfix]
[HarmonyPatch(typeof(AstroResourceStatPlan), nameof(AstroResourceStatPlan.AddPlanetResources))]
private static void AstroResourceStatPlan_AddPlanetResources_Postfix(AstroResourceStatPlan __instance, PlanetData planet, int veinAmountDisplayFilter)
{
var factory = planet?.factory;
if (factory == null || planet.type == EPlanetType.Gas || veinAmountDisplayFilter is not (1 or 2)) return;
var miningRate = FactoryPatch.GetMiningCostRate(factory.gameData.history);
if (miningRate <= 0f) return;
var miners = factory.factorySystem.minerPool;
var consumers = factory.powerSystem.consumerPool;
var seen = AstroResourceStatPlan.hashes;
seen.Clear();
var sign = veinAmountDisplayFilter == 1 ? -1 : 1;
for (var i = 1; i < factory.factorySystem.minerCursor; i++)
{
ref var miner = ref miners[i];
if (miner.id != i || miner.type == EMinerType.Water || consumers[miner.pcId].networkId <= 0) continue;
for (var j = 0; j < miner.veinCount; j++)
{
var veinId = miner.veins[j];
ref var vein = ref factory.veinPool[veinId];
if (!IsProtectedVein(ref vein, miningRate) || !seen.Add(veinId)) continue;
var type = vein.type == EVeinType.Oil ? AstroResourceStatPlan.EAstroResourceType.Oil : AstroResourceStatPlan.EAstroResourceType.Vein;
double amount = vein.amount;
if (vein.type == EVeinType.Oil)
{
amount = (float)vein.amount * VeinData.oilSpeedMultiplier;
if (veinAmountDisplayFilter == 1) amount *= __instance.gameData.history.miningSpeedScale;
}
__instance.AddStatData(type, (int)vein.type, sign, sign * amount);
}
}
seen.Clear();
}
[HarmonyPrefix]
[HarmonyPatch(typeof(AstroResourceStatPlan), nameof(AstroResourceStatPlan.AddPlanetDetailedResources))]
private static bool AstroResourceStatPlan_AddPlanetDetailedResources_Prefix(AstroResourceStatPlan __instance, PlanetData planet, int veinAmountDisplayFilter, ref bool __result)
{
var factory = planet?.factory;
if (factory == null || planet.type == EPlanetType.Gas || veinAmountDisplayFilter is not (1 or 2)) return true;
var miningRate = FactoryPatch.GetMiningCostRate(factory.gameData.history);
var veins = planet.runtimeVeinPool;
if (miningRate <= 0f || veins == null) return true;
var seen = AstroResourceStatPlan.hashes;
seen.Clear();
var miners = factory.factorySystem.minerPool;
var consumers = factory.powerSystem.consumerPool;
__result = true;
for (var i = 1; i < factory.factorySystem.minerCursor; i++)
{
ref var miner = ref miners[i];
if (miner.id != i || miner.type != EMinerType.Vein || consumers[miner.pcId].networkId <= 0) continue;
for (var j = 0; j < miner.veinCount; j++)
{
var id = miner.veins[j];
if (id <= 0) continue;
ref var vein = ref veins[id];
if (vein.id != id || vein.type == EVeinType.Oil || IsProtectedVein(ref vein, miningRate) || !seen.Add(id)) continue;
if (veinAmountDisplayFilter == 1 && !__instance.AddDetailedStatData(planet.astroId, (int)vein.type, vein.groupIndex, vein.amount))
{
__result = false;
return false;
}
}
}
if (veinAmountDisplayFilter == 2)
{
for (var i = 1; i < planet.runtimeVeinCursor; i++)
{
ref var vein = ref veins[i];
if (vein.id != i || vein.type == EVeinType.Oil || seen.Contains(i)) continue;
if (__instance.AddDetailedStatData(planet.astroId, (int)vein.type, vein.groupIndex, vein.amount)) continue;
__result = false;
break;
}
}
return false;
}
}
}
+2
View File
@@ -59,6 +59,7 @@
* You can set multiplier for tanks' operation speed
* This affects manually fill in to and/or take out from tanks, as well as transfer from upper to lower level.
* Protect veins from exhaustion
* Mining-rate estimates, mining resource counts, and miner hover counts exclude veins stopped by protection; remaining reserves stay visible.
* Default protection thresholds are 1,000 remaining vein units and an oil extraction rate of 1.0/s; change them in the config file.
* Mining or pumping stops at the configured threshold. Disable protection to resume consuming the remaining resources.
* Vein mining can continue at the threshold when `Veins Utilization` reduces the mining cost rate to zero.
@@ -248,6 +249,7 @@
* 你可以设置储液罐操作速度的倍率
* 影响手动注入和抽取,以及从储液罐上层传输到下层的速度
* 保护矿脉不会耗尽
* 开采速度估算、开采中资源数量和采矿机悬浮信息不计入因保护而停采的矿脉;剩余储量仍正常显示。
* 默认保护阈值为矿脉剩余量 1,000、采油速度 1.0/s,可在配置文件中修改。
* 达到阈值时停止采矿或抽油;关闭保护后可继续消耗剩余资源。
* `矿物利用` 将采矿消耗降到零后,即使达到保护阈值也可继续采矿。