1
0
mirror of https://github.com/soarqin/DSP_Mods.git synced 2025-12-08 21:33:28 +08:00

20 Commits

Author SHA1 Message Date
f237789fa0 minor fixes 2025-12-06 22:41:23 +09:00
b2c04c1dff work in progress 2025-12-02 00:10:02 +08:00
29ee32b11b work in progress 2025-11-30 18:08:13 +08:00
3f7c384284 fix description 2025-11-19 01:23:21 +08:00
556493b2b6 some fixes 2025-11-15 22:48:35 +08:00
269cc3b801 minor fixes 2025-11-15 01:02:33 +08:00
cacbfd6d5f fix recreate planet 2025-11-14 22:08:46 +08:00
45445f82a1 UXAssist v1.4.5 2025-11-14 15:59:48 +08:00
1a242af84e work in progress 2025-11-14 15:42:24 +08:00
1467a6010d work in progress 2025-11-13 22:16:28 +08:00
6f5b779d58 work in progress 2025-11-12 02:43:26 +08:00
d8fa46d495 priority fix 2025-11-11 23:18:26 +08:00
af3b46be11 minor check 2025-11-11 01:41:06 +08:00
96f160926c work in progress 2025-11-10 22:39:58 +08:00
ee812bbc79 work in progress 2025-11-10 01:41:55 +08:00
052c23d3b7 ready for UXAssist 1.4.4 release 2025-11-06 00:45:40 +08:00
be9de43492 fix issue 2025-10-29 20:22:23 +08:00
2dbf017a5e update LogisticMiner to be compatible with latest game update 2025-10-29 15:27:53 +08:00
3c7744047c update Game dll 2025-10-29 15:27:23 +08:00
a9959a2f07 try to fix a strange issue 2025-10-29 15:27:13 +08:00
29 changed files with 1021 additions and 128 deletions

Binary file not shown.

Binary file not shown.

View File

@@ -1,6 +1,7 @@
using Random = UnityEngine.Random;
namespace CheatEnabler.Functions;
public static class PlanetFunctions
{
public static void BuryAllVeins(bool bury)

View File

@@ -134,12 +134,12 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
{
UpdateSailLifeTime();
UpdateSailsCacheForThisGame();
GameLogicProc.OnGameBegin += GameMain_Begin_Postfix;
GameLogicProc.OnGameBegin += OnGameBegin;
}
protected override void OnDisable()
{
GameLogicProc.OnGameBegin -= GameMain_Begin_Postfix;
GameLogicProc.OnGameBegin -= OnGameBegin;
}
private static void UpdateSailLifeTime()
@@ -172,7 +172,7 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
_sailsCacheCapacity[index] = capacity;
}
private static void GameMain_Begin_Postfix()
private static void OnGameBegin()
{
UpdateSailsCacheForThisGame();
UpdateSailLifeTime();

View File

@@ -94,14 +94,14 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
ControlPanelRemoteLogistics.Enable(ControlPanelRemoteLogisticsEnabled.Value);
Enable(true);
CargoTrafficPatch.Enable(true);
GameLogicProc.OnGameBegin += GameMain_Begin_Postfix_For_ImmBuild;
GameLogicProc.OnGameBegin += OnGameBegin_For_ImmBuild;
GameLogicProc.OnDataLoaded += OnDataLoaded;
}
public static void Uninit()
{
GameLogicProc.OnDataLoaded -= OnDataLoaded;
GameLogicProc.OnGameBegin -= GameMain_Begin_Postfix_For_ImmBuild;
GameLogicProc.OnGameBegin -= OnGameBegin_For_ImmBuild;
CargoTrafficPatch.Enable(false);
Enable(false);
ImmediateBuild.Enable(false);
@@ -292,7 +292,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
}
}
private static void GameMain_Begin_Postfix_For_ImmBuild()
private static void OnGameBegin_For_ImmBuild()
{
if (DSPGame.IsMenuDemo) return;
var factory = GameMain.mainPlayer?.factory;
@@ -629,12 +629,12 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
protected override void OnEnable()
{
InitSignalBelts();
GameLogicProc.OnGameBegin += GameMain_Begin_Postfix;
GameLogicProc.OnGameBegin += OnGameBegin;
}
protected override void OnDisable()
{
GameLogicProc.OnGameBegin -= GameMain_Begin_Postfix;
GameLogicProc.OnGameBegin -= OnGameBegin;
_initialized = false;
_signalBelts = null;
_signalBeltsCapacity = 0;
@@ -675,11 +675,12 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
private static void InitSignalBelts()
{
if (!GameMain.isRunning) return;
if (DSPGame.IsMenuDemo) return;
InitItemSources();
_signalBelts = new Dictionary<int, BeltSignal>[64];
_signalBeltsCapacity = 64;
_portalFrom = new Dictionary<long, int>();
_portalTo = new Dictionary<int, HashSet<long>>();
_portalFrom = [];
_portalTo = [];
var factories = GameMain.data?.factories;
if (factories == null) return;
@@ -735,7 +736,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
if (obj != null) return obj;
}
obj = new Dictionary<int, BeltSignal>();
obj = [];
_signalBelts[index] = obj;
return obj;
}
@@ -865,11 +866,10 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
set.Remove(v);
}
private static void GameMain_Begin_Postfix()
private static void OnGameBegin()
{
if (DSPGame.IsMenuDemo) return;
if (BeltSignalGeneratorEnabled.Value) InitSignalBelts();
InitItemSources();
}
[HarmonyPostfix]
@@ -1171,7 +1171,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
for (var i = 0; i < len; i++)
{
if (ItemSources.ContainsKey(res[i])) continue;
var rs = new ItemSource { Count = rescnt[i], From = new Dictionary<int, float>() };
var rs = new ItemSource { Count = rescnt[i], From = [] };
var it = recipe.Items;
var itcnt = recipe.ItemCounts;
var len2 = it.Length;
@@ -1182,7 +1182,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
if (len > 1)
{
rs.Extra = new Dictionary<int, float>();
rs.Extra = [];
for (var k = 0; k < len; k++)
{
if (i != k)
@@ -1258,7 +1258,38 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
if (itemSource.From == null) return;
foreach (var p in itemSource.From)
{
CalculateAllProductions(result, extra, p.Key, times * p.Value);
var value = p.Value * times;
if (extra.TryGetValue(p.Key, out var rcount))
{
if (value <= rcount)
{
if (value == rcount)
{
extra.Remove(p.Key);
}
else
{
extra[p.Key] = rcount - value;
}
continue;
}
extra.Remove(p.Key);
value -= rcount;
}
if (result.TryGetValue(p.Key, out rcount))
{
rcount -= value;
if (rcount <= 0)
{
result.Remove(p.Key);
}
else
{
result[p.Key] = rcount;
}
continue;
}
CalculateAllProductions(result, extra, p.Key, value);
}
}
/* END: Item sources calculation */

View File

@@ -48,7 +48,7 @@ public static class GamePatch
p.Value.OnUnregEvent();
}
abnormalLogic.determinators = new Dictionary<int, AbnormalityDeterminator>();
abnormalLogic.determinators = [];
}
protected override void OnDisable()
@@ -81,7 +81,7 @@ public static class GamePatch
{
_savedDeterminators = __instance.determinators;
if (!AbnormalDisablerEnabled.Value) return;
__instance.determinators = new Dictionary<int, AbnormalityDeterminator>();
__instance.determinators = [];
foreach (var p in _savedDeterminators)
{
p.Value.OnUnregEvent();
@@ -140,7 +140,7 @@ public static class GamePatch
var pos = matcher.Pos;
/* Remove Shift+F4 part of the method */
matcher.Start().RemoveInstructions(pos).MatchForward(false,
new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(GameMain), "get_sandboxToolsEnabled")),
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(GameMain), nameof(GameMain.sandboxToolsEnabled))),
new CodeMatch(OpCodes.Ldc_I4_0),
new CodeMatch(OpCodes.Ceq)
);
@@ -297,7 +297,7 @@ public static class GamePatch
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UITechNode), nameof(UITechNode.tree))),
new CodeMatch(OpCodes.Callvirt, AccessTools.Method(typeof(UITechTree), "get_selected"))
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(UITechTree), nameof(UITechTree.selected)))
);
var labels = matcher.Labels;
matcher.Labels = null;

View File

@@ -6,6 +6,7 @@ using HarmonyLib;
using UXAssist.Common;
namespace CheatEnabler.Patches;
public static class PlanetPatch
{
public static ConfigEntry<bool> WaterPumpAnywhereEnabled;
@@ -53,6 +54,92 @@ public static class PlanetPatch
private class TerraformAnyway : PatchImpl<TerraformAnyway>
{
[HarmonyTranspiler]
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.DetermineReforms))]
private static IEnumerable<CodeInstruction> BuildTool_BlueprintPaste_DetermineReforms_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(BuildTool), nameof(BuildTool.player))),
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.sandCount))),
new CodeMatch(ci => ci.IsStloc())
).Advance(4).MatchForward(false,
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(OpCodes.Conv_I8),
new CodeMatch(ci => ci.opcode == OpCodes.Bge || ci.opcode == OpCodes.Bge_S)
);
var labels = matcher.Labels;
matcher.Labels = null;
matcher.RemoveInstructions(3);
matcher.Labels.AddRange(labels);
matcher.Opcode = OpCodes.Br;
return matcher.InstructionEnumeration();
}
[HarmonyTranspiler]
[HarmonyPatch(typeof(BuildTool_Reform), nameof(BuildTool_Reform.RemoveBasePit))]
private static IEnumerable<CodeInstruction> BuildTool_Reform_RemoveBasePit_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(BuildTool_Reform), nameof(BuildTool_Reform.circlePointCount))),
new CodeMatch(ci => ci.opcode == OpCodes.Blt || ci.opcode == OpCodes.Blt_S)
).RemoveInstructions(2).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldc_I4_0)
).MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(BuildTool), nameof(BuildTool.player))),
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.sandCount))),
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(OpCodes.Conv_I8),
new CodeMatch(OpCodes.Sub)
).Advance(6).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldc_I8, 0L),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Math), nameof(Math.Max), [typeof(long), typeof(long)]))
);
return matcher.InstructionEnumeration();
}
[HarmonyTranspiler]
[HarmonyPatch(typeof(UIRemoveBasePitButton), nameof(UIRemoveBasePitButton.OnRemoveButtonClick))]
[HarmonyPatch(typeof(UIRemoveBasePitButton), nameof(UIRemoveBasePitButton._OnUpdate))]
private static IEnumerable<CodeInstruction> UIRemoveBasePitButton_OnRemoveButtonClick_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIRemoveBasePitButton), nameof(UIRemoveBasePitButton.pointCount))),
new CodeMatch(OpCodes.Sub),
new CodeMatch(OpCodes.Ldc_I4_0),
new CodeMatch(OpCodes.Clt)
);
if (matcher.IsValid)
{
matcher.RemoveInstructions(2).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldc_I4_0)
);
}
else
{
matcher.Start();
}
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIRemoveBasePitButton), nameof(UIRemoveBasePitButton.player))),
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.sandCount))),
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(OpCodes.Conv_I8),
new CodeMatch(OpCodes.Sub)
).Advance(6).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldc_I8, 0L),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Math), nameof(Math.Max), [typeof(long), typeof(long)]))
);
return matcher.InstructionEnumeration();
}
[HarmonyTranspiler]
[HarmonyPatch(typeof(BuildTool_Reform), nameof(BuildTool_Reform.ReformAction))]
private static IEnumerable<CodeInstruction> BuildTool_Reform_ReformAction_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
@@ -65,13 +152,13 @@ public static class PlanetPatch
).RemoveInstructions(2).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldc_I4_0)
).MatchForward(false,
new CodeMatch(OpCodes.Callvirt, AccessTools.Method(typeof(Player), "get_sandCount"))
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.sandCount)))
).Advance(1).MatchForward(false,
new CodeMatch(OpCodes.Conv_I8),
new CodeMatch(OpCodes.Sub)
new CodeMatch(OpCodes.Conv_I8),
new CodeMatch(OpCodes.Sub)
).Advance(2).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldc_I8, 0L),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Math), "Max", [typeof(long), typeof(long)]))
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Math), nameof(Math.Max), [typeof(long), typeof(long)]))
);
return matcher.InstructionEnumeration();
}

View File

@@ -68,7 +68,7 @@ public static class UIConfigWindow
I18N.Add("Overclock Silos", "Overclock Silos (10x)", "高速发射井(10倍射速)");
I18N.Add("Unlock Dyson Sphere max orbit radius", "Unlock Dyson Sphere max orbit radius", "解锁戴森球最大轨道半径");
I18N.Add("Complete Dyson Sphere shells instantly", "Complete Dyson Sphere shells instantly", "立即完成戴森壳建造");
I18N.Add("Generate illegal dyson shell", "Generate an illegal dyson shell (!!All shells will be removed first!!)", "生成单层仙术戴森壳(!!会先删除全部的壳!!)");
I18N.Add("Generate illegal dyson shell", "Generate an illegal dyson shell (!!1st shell layer will be replaced!!)", "生成单层仙术戴森壳(!!会先删除第一层戴森壳!!)");
I18N.Add("Keep max production shells and remove others", "Keep max production shells and remove others", "保留发电量最高的戴森壳并移除其他戴森壳");
I18N.Add("Duplicate shells from that with highest production", "Duplicate shells from that with highest production", "从发电量最高的壳复制戴森壳");
I18N.Add("Generate illegal dyson shell quickly", "Generate illegal dyson shell quickly", "快速生成仙术戴森壳");
@@ -327,7 +327,7 @@ public static class UIConfigWindow
y = originalY;
var btn4 = wnd.AddButton(x, y, 300f, tab4, "Generate illegal dyson shell quickly", 16, "button-generate-illegal-dyson-shells-quickly", () =>
{
UIMessageBox.Show("Generate illegal dyson shell".Translate(), "WARNING: This operation can be very slow, continue?".Translate(), "取消".Translate(), "确定".Translate(), UIMessageBox.WARNING, null,
UIMessageBox.Show("Generate illegal dyson shell quickly".Translate(), "WARNING: This operation can be very slow, continue?".Translate(), "取消".Translate(), "确定".Translate(), UIMessageBox.WARNING, null,
() => { DysonSphereFunctions.CreateIllegalDysonShellQuickly(DysonSphereFunctions.ShellsCountForFunctions.Value); });
});
y += 30f;

View File

@@ -15,11 +15,11 @@ public class LogisticMiner : BaseUnityPlugin
private static long _oreEnergyConsume = 2000000;
private static long _oilEnergyConsume = 3600000;
private static long _waterEnergyConsume = 20000000;
private static int _waterSpeed = 100;
private static long _waterEnergyConsume = 2000000;
private static int _waterSpeed = 10;
private static int _miningScale;
private static int _fuelIlsSlot = 3;
private static int _fuelPlsSlot = 2;
private static int _fuelPlsSlot = 3;
private static float _frame;
private static float _miningCostRateByTech;
@@ -31,8 +31,8 @@ public class LogisticMiner : BaseUnityPlugin
private static uint _miningCostBarrierOil;
private static uint _seed = (uint)Random.Range(int.MinValue, int.MaxValue);
private static readonly Dictionary<int, VeinCacheData> PlanetVeinCacheData = new();
private static readonly Dictionary<int, (long, bool)> Fuels = new();
private static readonly Dictionary<int, VeinCacheData> PlanetVeinCacheData = [];
private static readonly Dictionary<int, (long, bool)> Fuels = [];
private bool _cfgEnabled = true;
@@ -52,11 +52,11 @@ public class LogisticMiner : BaseUnityPlugin
.Value;
_fuelIlsSlot = Config.Bind("General", "ILSFuelSlot", _fuelIlsSlot + 1,
new ConfigDescription("Fuel slot for ILS, set to 0 to disable",
new AcceptableValueRange<int>(0, 5), Array.Empty<object>()))
new AcceptableValueRange<int>(0, 5), []))
.Value - 1;
_fuelPlsSlot = Config.Bind("General", "PLSFuelSlot", _fuelPlsSlot + 1,
new ConfigDescription("Fuel slot for PLS, set to 0 to disable",
new AcceptableValueRange<int>(0, 4), Array.Empty<object>()))
new AcceptableValueRange<int>(0, 4), []))
.Value - 1;
if (!_cfgEnabled) return;
@@ -98,8 +98,8 @@ public class LogisticMiner : BaseUnityPlugin
}
[HarmonyPostfix]
[HarmonyPatch(typeof(DSPGame), "StartGame", typeof(GameDesc))]
[HarmonyPatch(typeof(DSPGame), "StartGame", typeof(string))]
[HarmonyPatch(typeof(DSPGame), nameof(DSPGame.StartGame), typeof(GameDesc))]
[HarmonyPatch(typeof(DSPGame), nameof(DSPGame.StartGame), typeof(string))]
private static void OnGameStart()
{
Logger.LogInfo("Game Start");
@@ -119,7 +119,7 @@ public class LogisticMiner : BaseUnityPlugin
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameMain), "Start")]
[HarmonyPatch(typeof(GameMain), nameof(GameMain.Start))]
private static void OnGameLoaded()
{
_frame = 0f;
@@ -130,7 +130,7 @@ public class LogisticMiner : BaseUnityPlugin
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameHistoryData), "UnlockTechFunction")]
[HarmonyPatch(typeof(GameHistoryData), nameof(GameHistoryData.UnlockTechFunction))]
private static void OnUnlockTech(int func)
{
switch (func)
@@ -145,7 +145,7 @@ public class LogisticMiner : BaseUnityPlugin
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameData), "GameTick")]
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic.OnFactoryFrameBegin))]
private static void FrameTick()
{
var main = GameMain.instance;
@@ -165,7 +165,7 @@ public class LogisticMiner : BaseUnityPlugin
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameHistoryData), "UnlockRecipe")]
[HarmonyPatch(typeof(GameHistoryData), nameof(GameHistoryData.UnlockRecipe))]
private static void OnUnlockRecipe(int recipeId)
{
if (recipeId == 119)
@@ -175,9 +175,9 @@ public class LogisticMiner : BaseUnityPlugin
}
[HarmonyPostfix]
[HarmonyPatch(typeof(PlanetFactory), "Init")]
[HarmonyPatch(typeof(PlanetFactory), "RecalculateVeinGroup")]
[HarmonyPatch(typeof(PlanetFactory), "RecalculateAllVeinGroups")]
[HarmonyPatch(typeof(PlanetFactory), nameof(PlanetFactory.Init))]
[HarmonyPatch(typeof(PlanetFactory), nameof(PlanetFactory.RecalculateVeinGroup))]
[HarmonyPatch(typeof(PlanetFactory), nameof(PlanetFactory.RecalculateAllVeinGroups))]
private static void NeedRecalcVeins(PlanetFactory __instance)
{
RecalcVeins(__instance);
@@ -204,13 +204,12 @@ public class LogisticMiner : BaseUnityPlugin
}
[HarmonyPostfix]
[HarmonyPatch(typeof(FactorySystem), "CheckBeforeGameTick")]
private static void FactorySystemLogisticMiner(FactorySystem __instance)
[HarmonyPatch(typeof(PlanetFactory), nameof(PlanetFactory.BeforeGameTick))]
private static void FactorySystemLogisticMiner(PlanetFactory __instance)
{
if (_miningSpeedScaleLong <= 0)
return;
var factory = __instance.factory;
var planetId = factory.planetId;
var planetId = __instance.planetId;
lock (PlanetVeinCacheData)
{
if (PlanetVeinCacheData.TryGetValue(planetId, out var vcd))
@@ -227,11 +226,11 @@ public class LogisticMiner : BaseUnityPlugin
return;
}
var planetTransport = __instance.planet.factory.transport;
var planetTransport = __instance.transport;
var factoryProductionStat =
GameMain.statistics.production.factoryStatPool[__instance.factory.index];
GameMain.statistics.production.factoryStatPool[__instance.index];
var productRegister = factoryProductionStat?.productRegister;
PerformanceMonitor.BeginSample(ECpuWorkEntry.Miner);
DeepProfiler.BeginSample(DPEntry.Miner);
do
{
for (var j = 1; j < planetTransport.stationCursor; j++)
@@ -271,7 +270,7 @@ public class LogisticMiner : BaseUnityPlugin
if (isVein)
{
(amount, energyConsume) = vcd.Mine(factory, stationStore.itemId, miningScale,
(amount, energyConsume) = vcd.Mine(__instance, stationStore.itemId, miningScale,
_miningSpeedScaleLong,
stationComponent.energy);
if (amount < 0)
@@ -334,7 +333,7 @@ public class LogisticMiner : BaseUnityPlugin
vcd.FrameNext += _miningFrames;
} while (vcd.FrameNext <= _frame);
PerformanceMonitor.EndSample(ECpuWorkEntry.Miner);
DeepProfiler.EndSample(DPEntry.Miner);
}
}
@@ -343,7 +342,7 @@ public class LogisticMiner : BaseUnityPlugin
public float FrameNext;
/* stores list of indices to veinData, with an extra INT which indicates cout of veinGroups at last */
private Dictionary<int, List<int>> _veins = new();
private Dictionary<int, List<int>> _veins = [];
private int _mineIndex = -1;
public bool HasVein(int productId)
@@ -353,9 +352,9 @@ public class LogisticMiner : BaseUnityPlugin
public void GenVeins(PlanetFactory factory)
{
_veins = new Dictionary<int, List<int>>();
_veins = [];
var veinPool = factory.veinPool;
var vg = new Dictionary<int, HashSet<int>>();
Dictionary<int, HashSet<int>> vg = [];
for (var i = 0; i < veinPool.Length; i++)
{
if (veinPool[i].amount <= 0 || veinPool[i].type == EVeinType.None) continue;

View File

@@ -6,7 +6,7 @@
<AssemblyName>LogisticMiner</AssemblyName>
<BepInExPluginGuid>org.soardev.logisticminer</BepInExPluginGuid>
<Description>DSP MOD - LogisticMiner</Description>
<Version>0.1.0</Version>
<Version>0.2.0</Version>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<LangVersion>latest</LangVersion>
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
@@ -15,10 +15,19 @@
<ItemGroup>
<PackageReference Include="BepInEx.Core" Version="5.*" />
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
<PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" />
<!-- <PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" /> -->
<PackageReference Include="UnityEngine.Modules" Version="2018.4.12" IncludeAssets="compile" />
</ItemGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>..\AssemblyFromGame\Assembly-CSharp.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.UI">
<HintPath>..\AssemblyFromGame\UnityEngine.UI.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
</ItemGroup>

View File

@@ -27,7 +27,7 @@
reaches Advanced Mining Machine, otherwise 100.
* 100/s for water by default.
* Energy costs: 1MW/vein-group & 10MW/water-slot & 1.8MW/oil-seep(configurable)
* Fuels burning slot. Default: 4th for ILS, 3rd for PLS. Set to 0 to disable it.
* Fuels burning slot. Default: 4th for ILS, 4th for PLS. Set to 0 to disable it.
## 使用说明
@@ -47,4 +47,4 @@
倍率可以设置为0(默认)此时倍率会随科技解锁而变化默认是100%解锁高级采矿机后变为300%。
* 水的采集速度默认为100/s。
* 能耗:每矿物组 1MW单格水 10MW每油井 1.8MW。
* 燃料格位置。默认星际物流塔第4格行星内物流塔第3格。设为0则关闭燃料补充能量功能。
* 燃料格位置。默认星际物流塔第4格行星内物流塔第4格。设为0则关闭燃料补充能量功能。

View File

@@ -1,6 +1,6 @@
{
"name": "LogisticMiner",
"version_number": "0.1.0",
"version_number": "0.2.0",
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/LogisticMiner",
"description": "Logistic Storages can mine all ores/water on current planet / 物流塔可以采集当前星球的全部矿产(以及水)",
"dependencies": [

View File

@@ -3,6 +3,16 @@
## Changlog
* 1.4.5
* New feature: `Ctrl+Shift+Click to pick items from whole belts`, with 2 suboptions: `Include branches of belts` and `Include connected inserters`
* Patch [BlueprintTweaks](https://thunderstore.io/c/dyson-sphere-program/p/kremnev8/BlueprintTweaks/) temporarily to fix `Drag Remove` functions (And wait for limoka to merge the [Pull Request](https://github.com/limoka/DSP-Mods/pull/133)):
* Ground rendering is correct now.
* Dismantle logic follows offcial's implementation to avoid possible crashes.
* Fixed CommonAPI patch to make shortcut key settings saved as expect now, sorry for wrong implementation in last version.
* 1.4.4
* `Remember window position and size on last exit`: Fix compatiblity for game patch 0.10.33
* `Real-time logistic stations info panel`: Try to fix a display issue.
* Patch [CommonAPI](https://thunderstore.io/c/dyson-sphere-program/p/CommonAPI/CommonAPI/) temporarily to fix a known issue that shortcut key settings are not saved to config, while its [PR](https://github.com/limoka/CommonAPI/pull/14) is not merged yet.
* 1.4.3
* `Build Tesla Tower and Wireless Power Tower alternately`:
* Fix wrong implementation for latest game patch.
@@ -346,6 +356,16 @@
## 更新日志
* 1.4.5
* 新功能:`按住Ctrl+Shift点击从整条传送带抓取物品`,包含两个子选项:`包含传送带分支``包含连接的分拣器`
* 临时修复 [BlueprintTweaks](https://thunderstore.io/c/dyson-sphere-program/p/kremnev8/BlueprintTweaks/) 的 `拖拽拆除` 功能(等待 limoka 合并 [Pull Request](https://github.com/limoka/DSP-Mods/pull/133)
* 地面绘制现在已正确
* 拆除逻辑遵循官方实现,避免潜在崩溃可能
* 修正了 CommonAPI 的补丁,现在快捷键设置可以如预期保存了,不好意思上一版本实现有误
* 1.4.4
* `记住上次退出时的窗口位置和大小`修复对游戏补丁0.10.33的兼容性
* `物流站实时信息面板`:尝试修复一个显示问题
* 对[CommonAPI](https://thunderstore.io/c/dyson-sphere-program/p/CommonAPI/CommonAPI/)临时打补丁,修复快捷键设置未能保存到配置文件的已知问题(其[PR](https://github.com/limoka/CommonAPI/pull/14)仍未合并)
* 1.4.3
* `交替建造电力感应塔和无线输电塔`:
* 修复了在最新游戏补丁中的错误实现

View File

@@ -24,6 +24,13 @@ public static class FactoryFunctions
cargoTraffic.AlterBeltConnections(beltId, 0, i0, i1, i2);
}
public static bool ObjectIsBeltOrInserter(PlanetFactory factory, int objId)
{
if (objId == 0) return false;
ItemProto proto = LDB.items.Select(objId > 0 ? factory.entityPool[objId].protoId : factory.prebuildPool[-objId].protoId);
return proto != null && (proto.prefabDesc.isBelt || proto.prefabDesc.isInserter);
}
public static void DismantleBlueprintSelectedBuildings()
{
var player = GameMain.mainPlayer;
@@ -50,7 +57,7 @@ public static class FactoryFunctions
for (var j = 0; j < 2; j++)
{
factory.ReadObjectConn(objId, j, out _, out var connObjId, out _);
if (connObjId == 0 || factory.ObjectIsBelt(connObjId) || blueprintCopyTool.ObjectIsInserter(connObjId)) continue;
if (connObjId == 0 || ObjectIsBeltOrInserter(factory, connObjId)) continue;
needCheck = true;
break;
}
@@ -59,7 +66,7 @@ public static class FactoryFunctions
for (var k = 0; k < 16; k++)
{
factory.ReadObjectConn(objId, k, out _, out var connObjId, out _);
if (connObjId != 0 && (index = buildPreviewsToRemove.BinarySearch(connObjId)) < 0 && (factory.ObjectIsBelt(connObjId) || blueprintCopyTool.ObjectIsInserter(connObjId)))
if (connObjId != 0 && (index = buildPreviewsToRemove.BinarySearch(connObjId)) < 0 && ObjectIsBeltOrInserter(factory, connObjId))
buildPreviewsToRemove.Insert(~index, connObjId);
}
}
@@ -70,7 +77,7 @@ public static class FactoryFunctions
for (var j = 0; j < 2; j++)
{
factory.ReadObjectConn(connObjId, j, out _, out var connObjId2, out _);
if (connObjId2 == 0 || (index = buildPreviewsToRemove.BinarySearch(connObjId2)) >= 0 || factory.ObjectIsBelt(connObjId2) || blueprintCopyTool.ObjectIsInserter(connObjId2)) continue;
if (connObjId2 == 0 || (index = buildPreviewsToRemove.BinarySearch(connObjId2)) >= 0 || ObjectIsBeltOrInserter(factory, connObjId2)) continue;
buildPreviewsToRemove.Insert(~index, connObjId);
break;
}
@@ -81,7 +88,7 @@ public static class FactoryFunctions
for (var j = 0; j < 16; j++)
{
factory.ReadObjectConn(objId, j, out _, out var connObjId, out _);
if (connObjId != 0 && (index = buildPreviewsToRemove.BinarySearch(connObjId)) < 0 && (factory.ObjectIsBelt(connObjId) || blueprintCopyTool.ObjectIsInserter(connObjId)))
if (connObjId != 0 && (index = buildPreviewsToRemove.BinarySearch(connObjId)) < 0 && ObjectIsBeltOrInserter(factory, connObjId))
buildPreviewsToRemove.Insert(~index, connObjId);
}
}

View File

@@ -59,6 +59,7 @@ public static class PlanetFunctions
uiGame.ShutAllFullScreens();
}
player.controller.actionBuild.Close();
var groundCombatModule = player.mecha.groundCombatModule;
for (var i = 0; i < groundCombatModule.moduleFleets.Length; i++)
{
@@ -67,6 +68,42 @@ public static class PlanetFunctions
entry.fleetEnabled = false;
groundCombatModule.RemoveFleetDirectly(i);
}
var constructionSystem = factory.constructionSystem;
var constructionModule = player.mecha.constructionModule;
for (var i = 0; i < constructionSystem.drones.cursor; i++)
{
ref var drone = ref constructionSystem.drones.buffer[i];
if (drone.id <= 0) continue;
var owner = drone.owner;
constructionSystem.ResetDroneTargets(ref drone);
if (owner == 0)
{
factory.RemoveCraftWithComponents(drone.craftId);
constructionModule.droneIdleCount++;
}
else
{
drone.movement = factory.gameData.history.constructionDroneMovement;
factory.craftPool[drone.craftId].pos = constructionSystem.constructionModules[owner].baseEjectPos;
constructionSystem.constructionModules[owner].droneIdleCount++;
}
}
for (var i = 0; i < constructionSystem.constructStats.cursor; i++)
{
ref var constructStat = ref constructionSystem.constructStats.buffer[i];
if (constructStat.id <= 0) continue;
constructionSystem.RemoveConstructStat(constructStat.id);
}
constructionModule.autoReconstructTargetTotalCount = 0;
constructionModule.buildTargetTotalCount = 0;
constructionModule.repairTargetTotalCount = 0;
constructionModule.autoReconstructTargets = null;
constructionModule.buildTargets = null;
constructionModule.repairTargets = null;
constructionModule.tmpTargets = null;
constructionModule.tmpTargetsHash = null;
constructionModule.checkItemCursor = 0;
//planet.data = new PlanetRawData(planet.precision);
//planet.data.CalcVerts();
for (var id = factory.entityCursor - 1; id > 0; id--)
@@ -93,6 +130,20 @@ public static class PlanetFunctions
planet.audio?.RemoveAudioData(ed.audioId);
}
for (var id = factory.prebuildCursor - 1; id > 0; id--)
{
ref var pb = ref factory.prebuildPool[id];
if (pb.id != id) continue;
if (pb.colliderId != 0)
{
planet.physics.RemoveLinkedColliderData(pb.colliderId);
}
if (pb.modelId != 0)
{
GameMain.gpuiManager.RemovePrebuildModel(pb.modelIndex, pb.modelId);
}
}
var hives = GameMain.spaceSector?.dfHives;
if (hives != null)
{
@@ -115,18 +166,18 @@ public static class PlanetFunctions
}
}
if (planet.factory.enemyPool != null)
if (factory.enemyPool != null)
{
for (var i = planet.factory.enemyCursor - 1; i > 0; i--)
for (var i = factory.enemyCursor - 1; i > 0; i--)
{
ref var enemyData = ref planet.factory.enemyPool[i];
ref var enemyData = ref factory.enemyPool[i];
if (enemyData.id != i) continue;
var combatStatId = enemyData.combatStatId;
planet.factory.skillSystem.OnRemovingSkillTarget(combatStatId, planet.factory.skillSystem.combatStats.buffer[combatStatId].originAstroId, ETargetType.CombatStat);
planet.factory.skillSystem.combatStats.Remove(combatStatId);
planet.factory.KillEnemyFinally(i, ref CombatStat.empty);
factory.skillSystem.OnRemovingSkillTarget(combatStatId, factory.skillSystem.combatStats.buffer[combatStatId].originAstroId, ETargetType.CombatStat);
factory.skillSystem.combatStats.Remove(combatStatId);
factory.KillEnemyFinally(i, ref CombatStat.empty);
}
planet.factory.enemySystem.Free();
factory.enemySystem.Free();
UIRoot.instance.uiGame.dfAssaultTip.ClearAllSpots();
}
@@ -165,7 +216,7 @@ public static class PlanetFunctions
factory.PlanetReformRevert();
}
planet.UnloadFactory();
GameMain.data.LeavePlanet();
var index = factory.index;
var warningSystem = GameMain.data.warningSystem;
var warningPool = warningSystem.warningPool;
@@ -238,12 +289,7 @@ public static class PlanetFunctions
factory.digitalSystem = new DigitalSystem(planet);
//GameMain.data.statistics.production.CreateFactoryStat(index);
planet.LoadFactory();
while (!planet.factoryLoaded)
{
PlanetModelingManager.Update();
Thread.Sleep(0);
}
GameMain.data.ArrivePlanet(planet);
}
public static void BuildOrbitalCollectors()

View File

@@ -1,11 +1,13 @@
using CommonAPI.Systems;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Linq;
using System.Collections.Generic;
using UXAssist.UI;
using CommonAPI.Systems;
using UXAssist.Common;
using UXAssist.UI;
using GameLogicProc = UXAssist.Common.GameLogic;
namespace UXAssist.Functions;
@@ -719,4 +721,158 @@ public static class UIFunctions
}
}
#endregion
#region MilkyWayClusterUploadResult
const int ClusterUploadResultKeepCount = 100;
private static readonly ClusterUploadResult[] _clusterUploadResults = new ClusterUploadResult[ClusterUploadResultKeepCount];
private static readonly object _clusterUploadResultsLock = new();
private static int _clusterUploadResultsHead = 0;
private static int _clusterUploadResultsCount = 0;
private struct ClusterUploadResult
{
public DateTime UploadTime;
public int Result;
public float RequestTime;
}
public static void AddClusterUploadResult(int result, float requestTime)
{
lock (_clusterUploadResultsLock)
{
if (_clusterUploadResultsCount >= ClusterUploadResultKeepCount)
{
_clusterUploadResults[_clusterUploadResultsHead] = new ClusterUploadResult { UploadTime = DateTime.Now, Result = result, RequestTime = requestTime };
_clusterUploadResultsHead = (_clusterUploadResultsHead + 1) % ClusterUploadResultKeepCount;
}
else
{
_clusterUploadResults[(_clusterUploadResultsHead + _clusterUploadResultsCount) % ClusterUploadResultKeepCount] = new ClusterUploadResult { UploadTime = DateTime.Now, Result = result, RequestTime = requestTime };
_clusterUploadResultsCount++;
}
}
}
public static void ExportClusterUploadResults(BinaryWriter w)
{
lock (_clusterUploadResultsLock)
{
w.Write(_clusterUploadResultsCount);
w.Write(_clusterUploadResultsHead);
for (var i = 0; i < _clusterUploadResultsCount; i++)
{
ref var result = ref _clusterUploadResults[(i + _clusterUploadResultsHead) % ClusterUploadResultKeepCount];
w.Write(result.UploadTime.ToBinary());
w.Write(result.Result);
w.Write(result.RequestTime);
}
}
}
public static void ImportClusterUploadResults(BinaryReader r)
{
lock (_clusterUploadResultsLock)
{
_clusterUploadResultsCount = r.ReadInt32();
_clusterUploadResultsHead = r.ReadInt32();
for (var i = 0; i < _clusterUploadResultsCount; i++)
{
ref var result = ref _clusterUploadResults[(i + _clusterUploadResultsHead) % ClusterUploadResultKeepCount];
result.UploadTime = DateTime.FromBinary(r.ReadInt64());
result.Result = r.ReadInt32();
result.RequestTime = r.ReadSingle();
}
}
}
#endregion
#region MilkyWayTopTenPlayers
private static ClusterPlayerData[] _topTenPlayerData = null;
private static readonly StringBuilder _sb = new(" ", 12);
public static UI.MyCheckButton MilkyWayTopTenPlayersToggler;
public static void SetTopPlayerCount(int count)
{
_topTenPlayerData = new ClusterPlayerData[count];
}
public static void SetTopPlayerData(int index, ref ClusterPlayerData playerData)
{
if (index < 0 || index >= _topTenPlayerData.Length) return;
_topTenPlayerData[index] = playerData;
}
public static void InitMilkyWayTopTenPlayers()
{
var uiRoot = UIRoot.instance;
if (!uiRoot) return;
var rect = uiRoot.uiMilkyWay.transform as RectTransform;
var panel = new GameObject("uxassist-milkyway-top-ten-players-panel");
var rtrans = panel.AddComponent<RectTransform>();
panel.transform.SetParent(rect);
rtrans.sizeDelta = new Vector2(0f, 0f);
rtrans.localScale = new Vector3(1f, 1f, 1f);
rtrans.anchorMax = new Vector2(1f, 1f);
rtrans.anchorMin = new Vector2(0f, 0f);
rtrans.pivot = new Vector2(0f, 1f);
rtrans.anchoredPosition3D = new Vector3(0, 0, 0f);
MyFlatButton[] buttons = [];
MilkyWayTopTenPlayersToggler = UI.MyCheckButton.CreateCheckButton(0, 0, rtrans, false, "Show top players".Translate()).WithSize(100f, 24f);
MilkyWayTopTenPlayersToggler.OnChecked += UpdateButtons;
MilkyWayTopTenPlayersToggler.Checked = false;
UpdateButtons();
void UpdateButtons()
{
var chk = MilkyWayTopTenPlayersToggler.Checked;
if (_topTenPlayerData == null)
{
MilkyWayTopTenPlayersToggler.gameObject.SetActive(false);
return;
}
var count = _topTenPlayerData.Length;
MilkyWayTopTenPlayersToggler.gameObject.SetActive(count > 0);
if (count != buttons.Length)
{
for (var i = count; i < buttons.Length; i++)
{
UnityEngine.Object.Destroy(buttons[i].gameObject);
}
Array.Resize(ref buttons, count);
}
for (var i = 0; i < count; i++)
{
var button = buttons[i];
if (chk)
{
if (button == null)
{
button = MyFlatButton.CreateFlatButton(0f, 20f * i + 24f, rtrans, "").WithSize(20f, 18f);
button.labelText.alignment = TextAnchor.MiddleLeft;
buttons[i] = button;
}
button.SetLabelText(String.Format(">> {0:00}. {1} {2}W", i + 1, _topTenPlayerData[i].name, ToKMG(_topTenPlayerData[i].genCap * 60L)));
button.gameObject.SetActive(true);
}
else
{
button.gameObject.SetActive(false);
}
}
MilkyWayTopTenPlayersToggler.SetLabelText(chk ? "Hide top players".Translate() : "Show top players".Translate());
string ToKMG(long value)
{
StringBuilderUtility.WriteKMG(_sb, 8, value, true);
return _sb.ToString();
}
}
}
#endregion
}

View File

@@ -0,0 +1,156 @@
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using UnityEngine;
using UXAssist.Functions;
namespace UXAssist.ModsCompat;
class BlueprintTweaks
{
public const string BlueprintTweaksGuid = "org.kremnev8.plugin.BlueprintTweaks";
private static FieldInfo selectObjIdsField;
private static Type classTypeBlueprintTweaksPlugin;
private static Type classTypeUIBuildingGridPatch2;
public static bool Run(Harmony harmony)
{
if (!BepInEx.Bootstrap.Chainloader.PluginInfos.TryGetValue(BlueprintTweaksGuid, out var pluginInfo)) return false;
var assembly = pluginInfo.Instance.GetType().Assembly;
var classTypeDragRemoveBuildTool = assembly.GetType("BlueprintTweaks.DragRemoveBuildTool");
if (classTypeDragRemoveBuildTool == null) return false;
if (AccessTools.Method(classTypeDragRemoveBuildTool, "DetermineMorePreviews") != null) return true;
classTypeBlueprintTweaksPlugin = assembly.GetType("BlueprintTweaks.BlueprintTweaksPlugin");
classTypeUIBuildingGridPatch2 = assembly.GetType("BlueprintTweaks.UIBuildingGridPatch2");
var UIBuildingGrid_Update = AccessTools.Method(typeof(UIBuildingGrid), nameof(UIBuildingGrid.Update));
harmony.Patch(AccessTools.Method(classTypeUIBuildingGridPatch2, "UpdateGrid"), null, null, new HarmonyMethod(AccessTools.Method(typeof(BlueprintTweaks), nameof(PatchUpdateGrid))));
selectObjIdsField = AccessTools.Field(classTypeDragRemoveBuildTool, "selectObjIds");
harmony.Patch(AccessTools.Method(classTypeDragRemoveBuildTool, "DeterminePreviews"),
new HarmonyMethod(AccessTools.Method(typeof(BlueprintTweaks), nameof(PatchDeterminePreviews))));
return true;
}
private static readonly int zMin = Shader.PropertyToID("_ZMin");
private static readonly int reformMode = Shader.PropertyToID("_ReformMode");
private static IEnumerable<CodeInstruction> PatchUpdateGrid(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(classTypeBlueprintTweaksPlugin, "tool")),
new CodeMatch(OpCodes.Ldfld),
new CodeMatch(ci => ci.opcode == OpCodes.Brfalse || ci.opcode == OpCodes.Brfalse_S)
);
var label1 = generator.DefineLabel();
matcher.Advance(2).Operand = label1;
matcher.Advance(1);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIBuildingGrid), nameof(UIBuildingGrid.blueprintMaterial))),
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(classTypeUIBuildingGridPatch2, "tintColor")),
new CodeMatch(OpCodes.Call),
new CodeMatch(OpCodes.Callvirt)
).RemoveInstructions(5);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIBuildingGrid), nameof(UIBuildingGrid.blueprintMaterial))),
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(classTypeUIBuildingGridPatch2, "cursorGratBox")),
new CodeMatch(OpCodes.Ldsfld),
new CodeMatch(OpCodes.Ldfld),
new CodeMatch(OpCodes.Call),
new CodeMatch(OpCodes.Callvirt)
).Advance(1).Operand = AccessTools.Field(typeof(UIBuildingGrid), nameof(UIBuildingGrid.material));
matcher.Advance(6);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIBuildingGrid), nameof(UIBuildingGrid.blueprintMaterial))),
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(classTypeUIBuildingGridPatch2, "selectColor")),
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld),
new CodeMatch(OpCodes.Call),
new CodeMatch(OpCodes.Callvirt)
).Advance(1).Operand = AccessTools.Field(typeof(UIBuildingGrid), nameof(UIBuildingGrid.material));
matcher.Advance(1).Operand = AccessTools.Field(classTypeUIBuildingGridPatch2, "tintColor");
matcher.Advance(5);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIBuildingGrid), nameof(UIBuildingGrid.blueprintMaterial))),
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(classTypeUIBuildingGridPatch2, "showDivideLine")),
new CodeMatch(OpCodes.Ldc_R4, 0f),
new CodeMatch(OpCodes.Callvirt)
).RemoveInstructions(5);
matcher.InsertAndAdvance(new CodeInstruction(OpCodes.Ldarg_0),
Transpilers.EmitDelegate((UIBuildingGrid grid) =>
{
grid.material.SetFloat(reformMode, 0f);
grid.material.SetFloat(zMin, -0.5f);
})
);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIBuildingGrid), nameof(UIBuildingGrid.blueprintGridRnd))),
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(OpCodes.Callvirt),
new CodeMatch(ci => ci.opcode == OpCodes.Br || ci.opcode == OpCodes.Br_S)
).RemoveInstructions(4).Set(OpCodes.Ret, null).Labels.Add(label1);
return matcher.InstructionEnumeration();
}
private static void PatchDeterminePreviews(object __instance)
{
var selectObjIds = (HashSet<int>)selectObjIdsField.GetValue(__instance);
var buildTool = (BuildTool)__instance;
var factory = buildTool.factory;
HashSet<int> extraObjIds = [];
foreach (var objId in selectObjIds)
{
var desc = buildTool.GetPrefabDesc(objId);
var isBelt = desc.isBelt;
var isInserter = desc.isInserter;
if (isInserter) continue;
if (isBelt)
{
var needCheck = false;
for (var j = 0; j < 2; j++)
{
factory.ReadObjectConn(objId, j, out _, out var connObjId, out _);
if (connObjId == 0 || FactoryFunctions.ObjectIsBeltOrInserter(factory, connObjId)) continue;
needCheck = true;
break;
}
if (needCheck)
{
for (var k = 0; k < 16; k++)
{
factory.ReadObjectConn(objId, k, out _, out var connObjId, out _);
if (connObjId != 0 && !selectObjIds.Contains(connObjId) && !extraObjIds.Contains(connObjId) && FactoryFunctions.ObjectIsBeltOrInserter(factory, connObjId))
extraObjIds.Add(connObjId);
}
}
for (var m = 0; m < 4; m++)
{
factory.ReadObjectConn(objId, m, out _, out var connObjId, out _);
if (connObjId == 0 || !factory.ObjectIsBelt(connObjId) || selectObjIds.Contains(connObjId) || extraObjIds.Contains(connObjId)) continue;
for (var j = 0; j < 2; j++)
{
factory.ReadObjectConn(connObjId, j, out _, out var connObjId2, out _);
if (connObjId2 == 0 || selectObjIds.Contains(connObjId2) || extraObjIds.Contains(connObjId2) || FactoryFunctions.ObjectIsBeltOrInserter(factory, connObjId2)) continue;
extraObjIds.Add(connObjId);
break;
}
}
continue;
}
if (desc.addonType == EAddonType.Belt) continue;
for (var j = 0; j < 16; j++)
{
factory.ReadObjectConn(objId, j, out _, out var connObjId, out _);
if (connObjId != 0 && !selectObjIds.Contains(connObjId) && !extraObjIds.Contains(connObjId) && FactoryFunctions.ObjectIsBeltOrInserter(factory, connObjId))
extraObjIds.Add(connObjId);
}
}
selectObjIds.UnionWith(extraObjIds);
}
}

View File

@@ -0,0 +1,20 @@
using BepInEx.Bootstrap;
using CommonAPI;
using HarmonyLib;
namespace UXAssist.ModsCompat;
public static class CommonAPIWrapper
{
public static void Run(Harmony harmony)
{
if (!Chainloader.PluginInfos.TryGetValue(CommonAPIPlugin.GUID, out var commonAPIPlugin) ||
commonAPIPlugin.Metadata.Version > new System.Version(1, 6, 7, 0)) return;
harmony.Patch(AccessTools.Method(typeof(GameOption), nameof(GameOption.InitKeys)), new HarmonyMethod(AccessTools.Method(typeof(CommonAPIWrapper), nameof(PatchInitKeys)), Priority.First));
}
public static bool PatchInitKeys(GameOption __instance)
{
return __instance.overrideKeys == null;
}
}

View File

@@ -269,14 +269,14 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
protected override void OnEnable()
{
InitNodeForAbsorb();
GameLogicProc.OnGameBegin += GameMain_Begin_Postfix;
GameLogicProc.OnGameEnd += GameMain_End_Postfix;
GameLogicProc.OnGameBegin += OnGameBegin;
GameLogicProc.OnGameEnd += OnGameEnd;
}
protected override void OnDisable()
{
GameLogicProc.OnGameEnd -= GameMain_End_Postfix;
GameLogicProc.OnGameBegin -= GameMain_Begin_Postfix;
GameLogicProc.OnGameEnd -= OnGameEnd;
GameLogicProc.OnGameBegin -= OnGameBegin;
_initialized = false;
_nodeForAbsorb = null;
}
@@ -347,12 +347,12 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
return comp is { Count: > 0 };
}
private static void GameMain_Begin_Postfix()
private static void OnGameBegin()
{
InitNodeForAbsorb();
}
private static void GameMain_End_Postfix()
private static void OnGameEnd()
{
_initialized = false;
_nodeForAbsorb = null;

View File

@@ -4,6 +4,7 @@ using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using CommonAPI.Systems;
using HarmonyLib;
@@ -45,6 +46,9 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
public static ConfigEntry<int> EjectorBufferCount;
public static ConfigEntry<int> SiloBufferCount;
public static ConfigEntry<bool> ShortcutKeysForBlueprintCopyEnabled;
public static ConfigEntry<bool> PressShiftToTakeWholeBeltItemsEnabled;
public static ConfigEntry<bool> PressShiftToTakeWholeBeltItemsIncludeBranches;
public static ConfigEntry<bool> PressShiftToTakeWholeBeltItemsIncludeInserters;
private static PressKeyBind _doNotRenderEntitiesKey;
private static PressKeyBind _offgridfForPathsKey;
@@ -131,6 +135,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
ReceiverBufferCount.SettingChanged += (_, _) => TweakBuildingBuffer.RefreshReceiverBufferCount();
EjectorBufferCount.SettingChanged += (_, _) => TweakBuildingBuffer.RefreshEjectorBufferCount();
SiloBufferCount.SettingChanged += (_, _) => TweakBuildingBuffer.RefreshSiloBufferCount();
PressShiftToTakeWholeBeltItemsEnabled.SettingChanged += (_, _) => PressShiftToTakeWholeBeltItems.Enable(PressShiftToTakeWholeBeltItemsEnabled.Value);
}
public static void Start()
@@ -150,6 +155,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
BeltSignalsForBuyOut.Enable(BeltSignalsForBuyOutEnabled.Value);
TankFastFillInAndTakeOut.Enable(TankFastFillInAndTakeOutEnabled.Value);
TweakBuildingBuffer.Enable(TweakBuildingBufferEnabled.Value);
PressShiftToTakeWholeBeltItems.Enable(PressShiftToTakeWholeBeltItemsEnabled.Value);
Enable(true);
UpdateTankFastFillInAndTakeOutMultiplierRealValue();
@@ -159,6 +165,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
{
Enable(false);
PressShiftToTakeWholeBeltItems.Enable(false);
TweakBuildingBuffer.Enable(false);
TankFastFillInAndTakeOut.Enable(false);
BeltSignalsForBuyOut.Enable(false);
@@ -276,12 +283,12 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
protected override void OnEnable()
{
GameLogicProc.OnGameEnd += GameMain_End_Postfix;
GameLogicProc.OnGameEnd += OnGameEnd;
}
protected override void OnDisable()
{
GameLogicProc.OnGameEnd -= GameMain_End_Postfix;
GameLogicProc.OnGameEnd -= OnGameEnd;
if (_sunlight)
{
_sunlight.transform.localEulerAngles = new Vector3(0f, 180f);
@@ -292,7 +299,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
_nightlightInitialized = false;
}
private static void GameMain_End_Postfix()
private static void OnGameEnd()
{
if (_sunlight)
{
@@ -304,25 +311,13 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
_nightlightInitialized = false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void UpdateSunlightAngle()
{
if (!_sunlight) return;
_sunlight.transform.rotation = Quaternion.LookRotation(-GameMain.mainPlayer.transform.up + GameMain.mainPlayer.transform.forward * NightLightAngleX.Value / 10f +
GameMain.mainPlayer.transform.right * NightLightAngleY.Value / 10f);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameData), nameof(GameData.ArriveStar))]
public static void GameData_ArriveStar_Postfix()
{
_sunlight = GameMain.universeSimulator?.LocalStarSimulator()?.sunLight;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(GameData), nameof(GameData.LeaveStar))]
public static void GameData_LeaveStar_Prefix()
{
_sunlight = null;
_sunlight.transform.rotation =
Quaternion.LookRotation(-GameMain.mainPlayer.transform.up + GameMain.mainPlayer.transform.forward * NightLightAngleX.Value / 10f +
GameMain.mainPlayer.transform.right * NightLightAngleY.Value / 10f);
}
[HarmonyPostfix]
@@ -335,7 +330,6 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
{
if (!GameMain.mainPlayer.controller.model.gameObject.activeInHierarchy) return;
if (_sail == null) _sail = GameMain.mainPlayer.animator.sails[GameMain.mainPlayer.animator.sailAnimIndex];
_sunlight = GameMain.universeSimulator?.LocalStarSimulator()?.sunLight;
_nightlightInitialized = true;
}
@@ -356,6 +350,10 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
if (sailing) return;
_mechaOnEarth = true;
if (_sunlight == null)
{
_sunlight = GameMain.universeSimulator?.LocalStarSimulator()?.sunLight;
}
}
[HarmonyTranspiler]
@@ -1405,16 +1403,16 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
protected override void OnEnable()
{
GameLogicProc.OnGameBegin += GameMain_Begin_Postfix;
GameLogicProc.OnGameEnd += GameMain_End_Postfix;
GameLogicProc.OnGameBegin += OnGameBegin;
GameLogicProc.OnGameEnd += OnGameEnd;
FixProto();
}
protected override void OnDisable()
{
UnfixProto();
GameLogicProc.OnGameEnd -= GameMain_End_Postfix;
GameLogicProc.OnGameBegin -= GameMain_Begin_Postfix;
GameLogicProc.OnGameEnd -= OnGameEnd;
GameLogicProc.OnGameBegin -= OnGameBegin;
}
public static void AlternatelyChanged()
@@ -1465,12 +1463,12 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
OldDragBuildDist.Clear();
}
private static void GameMain_Begin_Postfix()
private static void OnGameBegin()
{
FixProto();
}
private static void GameMain_End_Postfix()
private static void OnGameEnd()
{
UnfixProto();
}
@@ -1749,7 +1747,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
if (obj != null) return obj;
}
obj = new Dictionary<int, uint>();
obj = [];
_signalBelts[index] = obj;
return obj;
}
@@ -1782,12 +1780,12 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
{
AddBeltSignalProtos();
GameLogicProc.OnDataLoaded += VFPreload_InvokeOnLoadWorkEnded_Postfix;
GameLogicProc.OnGameBegin += GameMain_Begin_Postfix;
GameLogicProc.OnGameBegin += OnGameBegin;
}
protected override void OnDisable()
{
GameLogicProc.OnGameBegin -= GameMain_Begin_Postfix;
GameLogicProc.OnGameBegin -= OnGameBegin;
GameLogicProc.OnDataLoaded -= VFPreload_InvokeOnLoadWorkEnded_Postfix;
}
@@ -1809,7 +1807,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
RemovePlanetSignalBelts(factory.index);
}
private static void GameMain_Begin_Postfix()
private static void OnGameBegin()
{
_clusterSeedKey = GameMain.data.GetClusterSeedKey();
InitSignalBelts();
@@ -2233,4 +2231,237 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
return matcher.InstructionEnumeration();
}
}
private class PressShiftToTakeWholeBeltItems : PatchImpl<PressShiftToTakeWholeBeltItems>
{
private static long nextTimei = 0;
protected override void OnEnable()
{
GameLogicProc.OnGameBegin += OnGameBegin;
}
protected override void OnDisable()
{
GameLogicProc.OnGameBegin -= OnGameBegin;
}
private static void OnGameBegin()
{
nextTimei = 0;
}
[HarmonyTranspiler]
[HarmonyPatch(typeof(VFInput), nameof(VFInput._fastTransferWithEntityDown), MethodType.Getter)]
[HarmonyPatch(typeof(VFInput), nameof(VFInput._fastTransferWithEntityPress), MethodType.Getter)]
private static IEnumerable<CodeInstruction> VFInput_fastTransferWithEntityDown_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(typeof(VFInput), nameof(VFInput.shift))),
new CodeMatch(ci => ci.opcode == OpCodes.Brtrue || ci.opcode == OpCodes.Brtrue_S)
);
var lables = matcher.Labels;
matcher.RemoveInstructions(2);
matcher.Labels.AddRange(lables);
return matcher.InstructionEnumeration();
}
[HarmonyTranspiler]
[HarmonyPatch(typeof(PlayerAction_Inspect), nameof(PlayerAction_Inspect.GameTick))]
private static IEnumerable<CodeInstruction> PlayerAction_Inspect_GameTick_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(PlayerAction_Inspect), nameof(PlayerAction_Inspect.fastFillIn)))
);
matcher.SetAndAdvance(OpCodes.Ldsfld, AccessTools.Field(typeof(VFInput), nameof(VFInput.shift))).Insert(
new CodeInstruction(OpCodes.Ldc_I4_0),
new CodeInstruction(OpCodes.Ceq)
);
var label0 = generator.DefineLabel();
var label1 = generator.DefineLabel();
matcher.Start().MatchForward(false,
new CodeMatch(ci => ci.IsStloc()),
new CodeMatch(OpCodes.Ldc_I4_0),
new CodeMatch(ci => ci.IsStloc()),
new CodeMatch(OpCodes.Ldloc_0),
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(ci => ci.IsLdloc()),
new CodeMatch(OpCodes.Callvirt, AccessTools.Method(typeof(PlanetFactory), nameof(PlanetFactory.EntityFastTakeOut)))
).Advance(8).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(VFInput), nameof(VFInput.shift))),
new CodeInstruction(OpCodes.Brfalse_S, label0),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(PressShiftToTakeWholeBeltItems), nameof(EntityFastTakeOutAlt))),
new CodeInstruction(OpCodes.Br, label1)
).Labels.Add(label0);
matcher.Advance(1).Labels.Add(label1);
return matcher.InstructionEnumeration();
}
private static void EntityFastTakeOutAlt(PlanetFactory factory, int entityId, bool toPackage, out ItemBundle itemBundle, out bool full)
{
if (factory._tmp_items == null)
{
factory._tmp_items = new ItemBundle();
}
else
{
factory._tmp_items.Clear();
}
itemBundle = factory._tmp_items;
full = false;
if (entityId == 0 || factory.entityPool[entityId].id != entityId)
{
return;
}
if (GameMain.instance.timei < nextTimei) return;
nextTimei = GameMain.instance.timei + 12;
ref var entityData = ref factory.entityPool[entityId];
if (entityData.beltId <= 0) return;
var cargoTraffic = factory.cargoTraffic;
ref var belt = ref cargoTraffic.beltPool[entityData.beltId];
if (belt.id != entityData.beltId) return;
HashSet<int> pathIds = [belt.segPathId];
HashSet<int> inserterIds = [];
var includeBranches = PressShiftToTakeWholeBeltItemsIncludeBranches.Value;
var includeInserters = PressShiftToTakeWholeBeltItemsIncludeInserters.Value;
List<int> pendingPathIds = [belt.segPathId];
Dictionary<int, long> takeOutItems = [];
var factorySystem = factory.factorySystem;
while (pendingPathIds.Count > 0)
{
var lastIndex = pendingPathIds.Count - 1;
var thisPathId = pendingPathIds[lastIndex];
pendingPathIds.RemoveAt(lastIndex);
var path = cargoTraffic.GetCargoPath(thisPathId);
if (path == null) continue;
if (includeInserters)
{
foreach (var beltId in path.belts)
{
ref var b = ref cargoTraffic.beltPool[beltId];
if (b.id != beltId) return;
// From WriteObjectConn: Only slot 4 to 11 is used for belt <-> inserter connections (method argument slot/otherSlot is -1 there)
for (int cidx = 4; cidx < 12; cidx++)
{
factory.ReadObjectConn(b.entityId, cidx, out var isOutput, out var otherObjId, out var otherSlot);
if (otherObjId <= 0) continue;
var inserterId = factory.entityPool[otherObjId].inserterId;
if (inserterId <= 0) continue;
ref var inserter = ref factorySystem.inserterPool[inserterId];
if (inserter.id != inserterId) continue;
inserterIds.Add(inserterId);
if (includeBranches)
{
var pickTargetId = inserter.pickTarget;
if (pickTargetId > 0)
{
ref var pickTarget = ref factory.entityPool[pickTargetId];
if (pickTarget.id == pickTargetId && pickTarget.beltId > 0)
{
ref var pickTargetBelt = ref cargoTraffic.beltPool[pickTarget.beltId];
if (pickTargetBelt.id == pickTarget.beltId && !pathIds.Contains(pickTargetBelt.segPathId))
{
pathIds.Add(pickTargetBelt.segPathId);
pendingPathIds.Add(pickTargetBelt.segPathId);
}
}
}
var insertTargetId = inserter.insertTarget;
if (insertTargetId > 0)
{
ref var insertTarget = ref factory.entityPool[insertTargetId];
if (insertTarget.id == insertTargetId && insertTarget.beltId > 0)
{
ref var insertTargetBelt = ref cargoTraffic.beltPool[insertTarget.beltId];
if (insertTargetBelt.id == insertTarget.beltId && !pathIds.Contains(insertTargetBelt.segPathId))
{
pathIds.Add(insertTargetBelt.segPathId);
pendingPathIds.Add(insertTargetBelt.segPathId);
}
}
}
}
}
}
}
if (!includeBranches) continue;
foreach (var inputPathId in path.inputPaths)
{
if (pathIds.Contains(inputPathId)) continue;
pathIds.Add(inputPathId);
pendingPathIds.Add(inputPathId);
}
if (path.outputPath == null) continue;
var outputPathId = path.outputPath.id;
if (pathIds.Contains(outputPathId)) continue;
pathIds.Add(outputPathId);
pendingPathIds.Add(outputPathId);
}
var mainPlayer = factory.gameData.mainPlayer;
foreach (var pathId in pathIds)
{
var cargoPath = cargoTraffic.GetCargoPath(pathId);
if (cargoPath == null) continue;
var end = cargoPath.bufferLength - 5;
var buffer = cargoPath.buffer;
for (var i = 0; i <= end;)
{
if (buffer[i] >= 246)
{
i += 250 - buffer[i];
var index = buffer[i + 1] - 1 + (buffer[i + 2] - 1) * 100 + (buffer[i + 3] - 1) * 10000 + (buffer[i + 4] - 1) * 1000000;
ref var cargo = ref cargoPath.cargoContainer.cargoPool[index];
var item = cargo.item;
var stack = cargo.stack;
var inc = cargo.inc;
takeOutItems[item] = (takeOutItems.TryGetValue(item, out var value) ? value : 0)
+ ((long)stack | ((long)inc << 32));
Array.Clear(buffer, i - 4, 10);
i += 6;
if (cargoPath.updateLen < i) cargoPath.updateLen = i;
i += 4;
cargoPath.cargoContainer.RemoveCargo(index);
}
else
{
i += 5;
if (i > end && i < end + 5)
{
i = end;
}
}
}
}
foreach (var inserterId in inserterIds)
{
ref var inserter = ref factorySystem.inserterPool[inserterId];
if (inserter.itemId > 0 && inserter.stackCount > 0)
{
takeOutItems[inserter.itemId] = (takeOutItems.TryGetValue(inserter.itemId, out var value) ? value : 0)
+ ((long)inserter.itemCount | ((long)inserter.itemInc << 32));
inserter.itemId = 0;
inserter.stackCount = 0;
inserter.itemCount = 0;
inserter.itemInc = 0;
}
}
foreach (var kvp in takeOutItems)
{
var added = mainPlayer.TryAddItemToPackage(kvp.Key, (int)(kvp.Value & 0xFFFFFFFF), (int)(kvp.Value >> 32), true, entityId);
if (added > 0)
{
UIItemup.Up(kvp.Key, added);
}
}
}
}
}

View File

@@ -1069,10 +1069,10 @@ public static class LogisticsPatch
var localPlanet = GameMain.data?.localPlanet;
if (localPlanet == null || !localPlanet.factoryLoaded)
{
_stationTipsRoot.SetActive(false);
if (_lastPlanetId == 0) return;
RecycleStationTips();
_lastPlanetId = 0;
_stationTipsRoot.SetActive(false);
return;
}
@@ -1222,7 +1222,7 @@ public static class LogisticsPatch
private float _pixelPerItem;
private StorageItemData[] _storageItems;
private static readonly Dictionary<int, Sprite> ItemSprites = new();
private static readonly Dictionary<int, Sprite> ItemSprites = [];
private static readonly Color[] StateColor = [Color.gray, SupplyColor, DemandColor];
private struct StorageItemData

View File

@@ -1,7 +1,9 @@
using System.Collections.Generic;
using System.IO;
using System.Reflection.Emit;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Networking;
using UXAssist.Common;
namespace UXAssist.Patches;
@@ -169,4 +171,95 @@ public class PersistPatch : PatchImpl<PersistPatch>
{
return false;
}
#region Cluster Upload Result
[HarmonyPostfix]
[HarmonyPatch(typeof(MilkyWayWebClient), nameof(MilkyWayWebClient.OnUploadLoginErrored))]
private static void MilkyWayWebClient_OnUploadLoginErrored_Postfix(MilkyWayWebClient __instance, DSPWeb.HTTP_ERROR_TYPE errorType, string errorInfo, int errorCode)
{
switch (errorType)
{
case DSPWeb.HTTP_ERROR_TYPE.NETWORK_ERROR:
Functions.UIFunctions.AddClusterUploadResult(-10001, (float)__instance.uploadRequest.reqTime);
break;
case DSPWeb.HTTP_ERROR_TYPE.HTTP_ERROR:
Functions.UIFunctions.AddClusterUploadResult(-10010 - errorCode, (float)__instance.uploadRequest.reqTime);
break;
case DSPWeb.HTTP_ERROR_TYPE.USER_ABORT:
Functions.UIFunctions.AddClusterUploadResult(-10003, (float)__instance.uploadRequest.reqTime);
break;
case DSPWeb.HTTP_ERROR_TYPE.UNEXPECTED_ERROR:
Functions.UIFunctions.AddClusterUploadResult(-10004, (float)__instance.uploadRequest.reqTime);
break;
}
}
[HarmonyPostfix]
[HarmonyPatch(typeof(MilkyWayWebClient), nameof(MilkyWayWebClient.OnUploadErrored))]
private static void MilkyWayWebClient_OnUploadErrored_Postfix(MilkyWayWebClient __instance, DSPWeb.HTTP_ERROR_TYPE errorType, string errorInfo, int errorCode)
{
switch (errorType)
{
case DSPWeb.HTTP_ERROR_TYPE.NETWORK_ERROR:
Functions.UIFunctions.AddClusterUploadResult(-101, (float)__instance.uploadRequest.reqTime);
break;
case DSPWeb.HTTP_ERROR_TYPE.HTTP_ERROR:
Functions.UIFunctions.AddClusterUploadResult(-110 - errorCode, (float)__instance.uploadRequest.reqTime);
break;
case DSPWeb.HTTP_ERROR_TYPE.USER_ABORT:
Functions.UIFunctions.AddClusterUploadResult(-103, (float)__instance.uploadRequest.reqTime);
break;
case DSPWeb.HTTP_ERROR_TYPE.UNEXPECTED_ERROR:
Functions.UIFunctions.AddClusterUploadResult(-104, (float)__instance.uploadRequest.reqTime);
break;
}
}
[HarmonyPostfix]
[HarmonyPatch(typeof(MilkyWayWebClient), nameof(MilkyWayWebClient.OnUploadSucceed))]
private static void MilkyWayWebClient_OnUploadSucceed_Postfix(MilkyWayWebClient __instance, DownloadHandler handler)
{
if (!int.TryParse(handler.text, out var rcode))
rcode = -1;
Functions.UIFunctions.AddClusterUploadResult(rcode, (float)__instance.uploadRequest.reqTime);
}
[HarmonyTranspiler]
[HarmonyPatch(typeof(MilkyWayCache), nameof(MilkyWayCache.LoadTopTenPlayerData))]
private static IEnumerable<CodeInstruction> MilkyWayCache_LoadTopTenPlayerData_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_1),
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(BinaryReader), nameof(BinaryReader.ReadInt32))),
new CodeMatch(ci => ci.IsStloc())
).Advance(2).InsertAndAdvance(
new CodeInstruction(OpCodes.Dup),
Transpilers.EmitDelegate(Functions.UIFunctions.SetTopPlayerCount)
);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldloca_S),
new CodeMatch(OpCodes.Ldarg_1),
new CodeMatch(OpCodes.Callvirt),
new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(ClusterPlayerData), nameof(ClusterPlayerData.isAnon)))
);
var objloc = matcher.Operand;
matcher.Advance(4);
var iinstr = matcher.Instruction.Clone();
matcher.InsertAndAdvance(
iinstr,
new CodeInstruction(OpCodes.Ldloca_S, objloc),
Transpilers.EmitDelegate((int index, ref ClusterPlayerData playerData) =>
{
Functions.UIFunctions.SetTopPlayerData(index, ref playerData);
})
);
return matcher.InstructionEnumeration();
}
#endregion
}

View File

@@ -5,6 +5,7 @@ using HarmonyLib;
using UXAssist.Common;
namespace UXAssist.Patches;
public static class PlanetPatch
{
public static ConfigEntry<bool> PlayerActionsInGlobeViewEnabled;

View File

@@ -24,6 +24,7 @@ public class UIPatch : PatchImpl<UIPatch>
GameLogicProc.OnGameBegin += PlanetVeinUtilization.OnGameBegin;
Enable(true);
Functions.UIFunctions.InitMenuButtons();
Functions.UIFunctions.InitMilkyWayTopTenPlayers();
PlanetVeinUtilization.Enable(PlanetVeinUtilizationEnabled.Value);
}

View File

@@ -71,6 +71,9 @@ public static class UIConfigWindow
I18N.Add("Drag building power poles in maximum connection range", "Drag building power poles in maximum connection range", "拖动建造电线杆时自动使用最大连接距离间隔");
I18N.Add("Build Tesla Tower and Wireless Power Tower alternately", "Build Tesla Tower and Wireless Power Tower alternately", "交替建造电力感应塔和无线输电塔");
I18N.Add("Belt signals for buy out dark fog items automatically", "Belt signals for buy out dark fog items automatically", "用于自动购买黑雾物品的传送带信号");
I18N.Add("Ctrl+Shift+Click to pick items from whole belts", "Ctrl+Shift+Click to pick items from whole belts", "按住Ctrl+Shift点击从整条传送带抓取物品");
I18N.Add("Include branches of belts", "Include branches of belts", "包含传送带分支");
I18N.Add("Include connected inserters", "Include connected inserters (and their connected belts if above is checked)", "包含连接的分拣器(若勾选上面的选项则包含分拣器连接的传送带)");
I18N.Add("Auto-config logistic stations", "Auto-config logistic stations", "自动配置物流设施");
I18N.Add("Limit auto-replenish count to values below", "Limit auto-replenish count to values below", "限制自动补充数量为下面配置的值");
I18N.Add("Dispenser", "Logistics Distributor", "物流配送器");
@@ -404,6 +407,24 @@ public static class UIConfigWindow
}
}
{
y += 36f;
wnd.AddCheckBox(x, y, tab2, FactoryPatch.PressShiftToTakeWholeBeltItemsEnabled, "Ctrl+Shift+Click to pick items from whole belts");
y += 27f;
var includeBranches = wnd.AddCheckBox(x + 10, y, tab2, FactoryPatch.PressShiftToTakeWholeBeltItemsIncludeBranches, "Include branches of belts", 13);
y += 27f;
var includeInserters = wnd.AddCheckBox(x + 10, y, tab2, FactoryPatch.PressShiftToTakeWholeBeltItemsIncludeInserters, "Include connected inserters", 13);
FactoryPatch.PressShiftToTakeWholeBeltItemsEnabled.SettingChanged += PressShiftToTakeWholeBeltItemsEnabledChanged;
wnd.OnFree += () => { FactoryPatch.PressShiftToTakeWholeBeltItemsEnabled.SettingChanged -= PressShiftToTakeWholeBeltItemsEnabledChanged; };
PressShiftToTakeWholeBeltItemsEnabledChanged(null, null);
void PressShiftToTakeWholeBeltItemsEnabledChanged(object o, EventArgs e)
{
includeBranches.SetEnable(FactoryPatch.PressShiftToTakeWholeBeltItemsEnabled.Value);
includeInserters.SetEnable(FactoryPatch.PressShiftToTakeWholeBeltItemsEnabled.Value);
}
}
x = 400f;
y = 10f;
wnd.AddButton(x, y, tab2, "Initialize This Planet", 16, "button-init-planet", () =>
@@ -470,7 +491,6 @@ public static class UIConfigWindow
FactoryPatch.TweakBuildingBufferEnabled.SettingChanged += TweakBuildingBufferChanged;
wnd.OnFree += () => { FactoryPatch.TweakBuildingBufferEnabled.SettingChanged -= TweakBuildingBufferChanged; };
TweakBuildingBufferChanged(null, null);
void TweakBuildingBufferChanged(object o, EventArgs e)
{
assemblerBufferTimeMultiplierSlider.SetEnable(FactoryPatch.TweakBuildingBufferEnabled.Value);
@@ -606,7 +626,7 @@ public static class UIConfigWindow
textForMeasureTextWidth = wnd.AddText2(x, y, tab3, "Min. Piler Value", 13, "text-amm-min-piler-value");
maxWidth = Mathf.Max(maxWidth, textForMeasureTextWidth.preferredWidth);
y = oy + 1;
var nx = x + maxWidth + 5f;
var nx = x + maxWidth + 5f + 10f;
wnd.AddSideSlider(nx, y, tab3, LogisticsPatch.AutoConfigDispenserChargePower, new AutoConfigDispenserChargePowerMapper(), "G", 150f, -100f).WithFontSize(13);
y += 18f;
wnd.AddSideSlider(nx, y, tab3, LogisticsPatch.AutoConfigDispenserCourierCount, new MyWindow.RangeValueMapper<int>(0, 10), "G", 150f, -100f).WithFontSize(13);

View File

@@ -33,12 +33,13 @@ public class UXAssist : BaseUnityPlugin, IModCanSave
private readonly Harmony _harmony = new(PluginInfo.PLUGIN_GUID);
#region IModCanSave
private const ushort ModSaveVersion = 1;
private const ushort ModSaveVersion = 2;
public void Export(BinaryWriter w)
{
w.Write(ModSaveVersion);
FactoryPatch.Export(w);
UIFunctions.ExportClusterUploadResults(w);
}
public void Import(BinaryReader r)
@@ -46,6 +47,10 @@ public class UXAssist : BaseUnityPlugin, IModCanSave
var version = r.ReadUInt16();
if (version <= 0) return;
FactoryPatch.Import(r);
if (version > 1)
{
UIFunctions.ImportClusterUploadResults(r);
}
}
public void IntoOtherSave()
@@ -56,6 +61,8 @@ public class UXAssist : BaseUnityPlugin, IModCanSave
UXAssist()
{
ModsCompat.PlanetVeinUtilization.Run(_harmony);
ModsCompat.BlueprintTweaks.Run(_harmony);
ModsCompat.CommonAPIWrapper.Run(_harmony);
}
private void Awake()
@@ -138,6 +145,12 @@ public class UXAssist : BaseUnityPlugin, IModCanSave
FactoryPatch.SiloBufferCount = Config.Bind("Factory", "SiloBufferCount", 1, new ConfigDescription("Silo buffer count", new AcceptableValueRange<int>(1, 40)));
FactoryPatch.ShortcutKeysForBlueprintCopyEnabled = Config.Bind("Factory", "DismantleBlueprintSelection", false,
"Dismantle blueprint selected buildings");
FactoryPatch.PressShiftToTakeWholeBeltItemsEnabled = Config.Bind("Factory", "PressShiftToTakeWholeBeltItems", false,
"Ctrl+Shift+Click to pick items from whole belts");
FactoryPatch.PressShiftToTakeWholeBeltItemsIncludeBranches = Config.Bind("Factory", "PressShiftToTakeWholeBeltItemsIncludeBranches", false,
"Include branches of belts");
FactoryPatch.PressShiftToTakeWholeBeltItemsIncludeInserters = Config.Bind("Factory", "PressShiftToTakeWholeBeltItemsIncludeInserters", false,
"Include connected inserters");
LogisticsPatch.AutoConfigLogisticsEnabled = Config.Bind("Factory", "AutoConfigLogistics", false,
"Auto-config logistic stations");
LogisticsPatch.AutoConfigLimitAutoReplenishCount = Config.Bind("Factory", "AutoConfigLimitAutoReplenishCount", false,
@@ -217,7 +230,8 @@ public class UXAssist : BaseUnityPlugin, IModCanSave
t => string.Equals(t.Namespace, "UXAssist.Patches", StringComparison.Ordinal) || string.Equals(t.Namespace, "UXAssist.Functions", StringComparison.Ordinal));
_patches?.Do(type => type.GetMethod("Init")?.Invoke(null, null));
_compats = Util.GetTypesInNamespace(Assembly.GetExecutingAssembly(), "UXAssist.ModsCompat");
_compats?.Do(type => type.GetMethod("Init")?.Invoke(null, null));
object[] parameters = [_harmony];
_compats?.Do(type => type.GetMethod("Init")?.Invoke(null, parameters));
I18N.Apply();
}

View File

@@ -4,7 +4,7 @@
<TargetFramework>net472</TargetFramework>
<BepInExPluginGuid>org.soardev.uxassist</BepInExPluginGuid>
<Description>DSP MOD - UXAssist</Description>
<Version>1.4.3</Version>
<Version>1.4.5</Version>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<LangVersion>latest</LangVersion>
<PackageId>UXAssist</PackageId>
@@ -17,7 +17,7 @@
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
<PackageReference Include="UnityEngine.Modules" Version="2022.3.53" IncludeAssets="compile" />
<!-- <PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" /> -->
<PackageReference Include="DysonSphereProgram.Modding.CommonAPI" Version="1.6.5" />
<PackageReference Include="DysonSphereProgram.Modding.CommonAPI" Version="1.*" />
<PackageReference Include="DysonSphereProgram.Modding.DSPModSave" Version="1.*" />
</ItemGroup>

View File

@@ -1,6 +1,6 @@
{
"name": "UXAssist",
"version_number": "1.4.3",
"version_number": "1.4.5",
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/UXAssist",
"description": "Some functions and patches for better user experience / 一些提升用户体验的功能和补丁",
"dependencies": [

View File

@@ -4,6 +4,7 @@ using HarmonyLib;
using GameLogicProc = UXAssist.Common.GameLogic;
namespace UniverseGenTweaks;
public static class BirthPlanetPatch
{
public static ConfigEntry<bool> SitiVeinsOnBirthPlanet;