using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("FastBlueprintPaste")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("FastBlueprintPaste")]
[assembly: AssemblyTitle("FastBlueprintPaste")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
internal sealed class RefSafetyRulesAttribute : Attribute
{
public readonly int Version;
public RefSafetyRulesAttribute(int P_0)
{
Version = P_0;
}
}
}
namespace FastBlueprintPaste
{
[BepInPlugin("com.github.jiesiluo.fastblueprintpaste", "Fast Blueprint Paste", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
public const string Guid = "com.github.jiesiluo.fastblueprintpaste";
public const string Name = "Fast Blueprint Paste";
public const string Version = "1.0.0";
internal static ManualLogSource Log;
internal static ConfigEntry<bool> EnabledEntry;
internal static ConfigEntry<bool> FastLookupEntry;
internal static ConfigEntry<bool> LogTimingEntry;
internal static bool Enabled;
internal static bool FastLookup;
internal static bool LogTiming;
private void Awake()
{
//IL_0118: Unknown result type (might be due to invalid IL or missing references)
//IL_011d: Unknown result type (might be due to invalid IL or missing references)
Log = ((BaseUnityPlugin)this).Logger;
EnabledEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Skip unbuilt buildings that cannot matter when a pasted blueprint is checked. 粘贴蓝图做检查时跳过无关的待建建筑。\nOff = the game's own loops again from the next paste.");
FastLookupEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "FastColliderLookup", true, "Find a collider's id with one dictionary lookup instead of walking every active collider. 用字典查碰撞体编号,不再逐个比对所有激活的碰撞体。");
LogTimingEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogTiming", false, "Write the duration of every blueprint paste check and of the prebuild creation to the BepInEx log. 把每次粘贴检查和放下待建建筑的耗时写进日志。");
Enabled = EnabledEntry.Value;
LogTiming = LogTimingEntry.Value;
FastLookup = FastLookupEntry.Value;
FastLookupEntry.SettingChanged += delegate
{
FastLookup = FastLookupEntry.Value;
};
EnabledEntry.SettingChanged += delegate
{
Enabled = EnabledEntry.Value;
};
LogTimingEntry.SettingChanged += delegate
{
LogTiming = LogTimingEntry.Value;
};
Harmony val = new Harmony("com.github.jiesiluo.fastblueprintpaste");
val.PatchAll(typeof(Patches));
val.PatchAll(typeof(ColliderLookup));
Log.LogInfo((object)((Patches.LoopsPatched == 8) ? $"{Patches.LoopsPatched} prebuild loops of the blueprint paste check now skip irrelevant prebuilds" : $"NOT ACTIVE: found {Patches.LoopsPatched} prebuild loops instead of {8} (game updated?); the game's own code runs unchanged"));
}
}
public static class PrebuildSkip
{
private static int[] next = new int[1024];
private static int len;
private static sbyte[] byProto;
private static sbyte[] byModel;
public static int relevantCount;
public static long calls;
public static int Next(int i, int one)
{
if ((uint)i < (uint)len)
{
return next[i];
}
return i + one;
}
private static bool Flags(PrefabDesc d)
{
if (d != null)
{
if (!d.isMarker && !d.isFieldGenerator && !d.isPowerNode && !d.isBattleBase && !d.isStation && !d.isEjector && !d.geothermal)
{
return d.isTurret;
}
return true;
}
return false;
}
private static bool RelevantProto(int protoId)
{
if (protoId < 0)
{
return true;
}
if (byProto == null)
{
byProto = new sbyte[65536];
}
if (protoId >= byProto.Length)
{
return true;
}
sbyte b = byProto[protoId];
if (b == 0)
{
ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(protoId);
bool flag = protoId == 3004 || protoId == 3010 || (val != null && Flags(val.prefabDesc));
b = (byProto[protoId] = (sbyte)(flag ? 1 : 2));
}
return b == 1;
}
private static bool RelevantModel(int modelIndex)
{
PrefabDesc[] prefabDescByModelIndex = PlanetFactory.PrefabDescByModelIndex;
if (prefabDescByModelIndex == null || modelIndex < 0 || modelIndex >= prefabDescByModelIndex.Length)
{
return true;
}
if (byModel == null || byModel.Length != prefabDescByModelIndex.Length)
{
byModel = new sbyte[prefabDescByModelIndex.Length];
}
sbyte b = byModel[modelIndex];
if (b == 0)
{
b = (byModel[modelIndex] = (sbyte)(Flags(prefabDescByModelIndex[modelIndex]) ? 1 : 2));
}
return b == 1;
}
public static bool Relevant(ref PrebuildData p)
{
if (!RelevantProto(p.protoId))
{
return RelevantModel(p.modelIndex);
}
return true;
}
public static void Prepare(PlanetFactory f)
{
len = 0;
calls = 0L;
relevantCount = 0;
if (f == null || f.prebuildPool == null)
{
return;
}
PrebuildData[] prebuildPool = f.prebuildPool;
int prebuildCursor = f.prebuildCursor;
if (prebuildCursor <= 1 || prebuildCursor > prebuildPool.Length)
{
return;
}
if (next.Length < prebuildCursor)
{
int num;
for (num = next.Length; num < prebuildCursor; num *= 2)
{
}
next = new int[num];
}
int num2 = prebuildCursor;
int num3 = 0;
for (int num4 = prebuildCursor - 1; num4 >= 0; num4--)
{
next[num4] = num2;
if (num4 > 0 && prebuildPool[num4].id == num4 && Relevant(ref prebuildPool[num4]))
{
num2 = num4;
num3++;
}
}
relevantCount = num3;
len = prebuildCursor;
}
public static void Clear()
{
len = 0;
}
}
public static class ColliderLookup
{
private static readonly Dictionary<int, ColliderObject> byCollider = new Dictionary<int, ColliderObject>();
private static readonly FieldRef<NearColliderLogic, Dictionary<int, ColliderObject>> tableOf = AccessTools.FieldRefAccess<NearColliderLogic, Dictionary<int, ColliderObject>>("colliderObjs");
public static long fastHits;
public static long fastMisses;
public static long fallbacks;
[HarmonyPostfix]
[HarmonyPatch(/*Could not decode attribute arguments.*/)]
private static void Registered(ColliderObject __instance)
{
Collider collider = __instance.collider;
if (collider != null)
{
byCollider[((Object)collider).GetInstanceID()] = __instance;
}
}
[HarmonyPrefix]
[HarmonyPatch(typeof(NearColliderLogic), "FindColliderId")]
private static bool Find(NearColliderLogic __instance, Collider cc, ref int __result)
{
if (!Plugin.Enabled || !Plugin.FastLookup || (Object)(object)cc == (Object)null)
{
fallbacks++;
return true;
}
Dictionary<int, ColliderObject> dictionary = tableOf.Invoke(__instance);
if (dictionary == null)
{
fallbacks++;
return true;
}
if (byCollider.TryGetValue(((Object)cc).GetInstanceID(), out var value) && value.collider == cc && dictionary.TryGetValue(value.id, out var value2) && value2 == value)
{
fastHits++;
__result = value.id;
}
else
{
fastMisses++;
__result = 0;
}
return false;
}
public static int Slow(NearColliderLogic logic, Collider cc)
{
Dictionary<int, ColliderObject> dictionary = tableOf.Invoke(logic);
if (dictionary == null)
{
return 0;
}
foreach (KeyValuePair<int, ColliderObject> item in dictionary)
{
if ((Object)(object)item.Value.collider == (Object)(object)cc)
{
return item.Value.id;
}
}
return 0;
}
public static int ActiveCount(NearColliderLogic logic)
{
return tableOf.Invoke(logic)?.Count ?? 0;
}
}
internal static class Patches
{
internal const int ExpectedLoops = 8;
internal static int LoopsPatched;
internal static double LastCheckMs;
internal static double LastCreateMs;
[ThreadStatic]
private static Stopwatch checkWatch;
[ThreadStatic]
private static Stopwatch createWatch;
[HarmonyPrefix]
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), "CheckBuildConditions")]
private static void CheckPrefix(BuildTool_BlueprintPaste __instance)
{
if (Plugin.Enabled && LoopsPatched == 8)
{
PrebuildSkip.Prepare(((BuildTool)__instance).factory);
}
else
{
PrebuildSkip.Clear();
}
(checkWatch ?? (checkWatch = new Stopwatch())).Restart();
}
[HarmonyFinalizer]
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), "CheckBuildConditions")]
private static void CheckFinalizer(BuildTool_BlueprintPaste __instance)
{
PrebuildSkip.Clear();
if (checkWatch != null)
{
LastCheckMs = checkWatch.Elapsed.TotalMilliseconds;
if (Plugin.LogTiming)
{
ManualLogSource log = Plugin.Log;
object arg = LastCheckMs;
object arg2 = __instance.bpCursor;
PlanetFactory factory = ((BuildTool)__instance).factory;
log.LogInfo((object)($"paste check: {arg:F0} ms, {arg2} blueprint buildings, {((factory != null) ? new int?(factory.prebuildCount) : ((int?)null))} unbuilt on the planet" + string.Format(" ({0} relevant), skipping {1}", PrebuildSkip.relevantCount, Plugin.Enabled ? "on" : "off")));
}
}
}
[HarmonyPrefix]
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), "CreatePrebuilds")]
private static void CreatePrefix()
{
(createWatch ?? (createWatch = new Stopwatch())).Restart();
}
[HarmonyFinalizer]
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), "CreatePrebuilds")]
private static void CreateFinalizer(BuildTool_BlueprintPaste __instance)
{
if (createWatch != null)
{
LastCreateMs = createWatch.Elapsed.TotalMilliseconds;
if (Plugin.LogTiming)
{
ManualLogSource log = Plugin.Log;
object arg = LastCreateMs;
object arg2 = __instance.bpCursor;
PlanetFactory factory = ((BuildTool)__instance).factory;
log.LogInfo((object)$"paste create prebuilds: {arg:F0} ms, {arg2} blueprint buildings, {((factory != null) ? new int?(factory.prebuildCount) : ((int?)null))} unbuilt on the planet now");
}
}
}
[HarmonyTranspiler]
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), "CheckBuildConditions")]
private static IEnumerable<CodeInstruction> CheckTranspiler(IEnumerable<CodeInstruction> instructions)
{
List<CodeInstruction> list = new List<CodeInstruction>(instructions);
FieldInfo fieldInfo = AccessTools.Field(typeof(PlanetFactory), "prebuildCursor");
MethodInfo operand = AccessTools.Method(typeof(PrebuildSkip), "Next", (Type[])null, (Type[])null);
int num = -1;
for (int i = 0; i + 1 < list.Count; i++)
{
if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo, false) && LocalOf(list[i + 1], store: true) is int num2)
{
if (num >= 0 && num != num2)
{
num = -2;
break;
}
num = num2;
}
}
List<int> list2 = new List<int>();
if (num >= 0)
{
for (int j = 0; j < list.Count; j++)
{
if (LocalOf(list[j], store: false) is int num3 && num3 == num)
{
int num4 = NextReal(list, j, 1);
int num5 = NextReal(list, j, -1);
if (num4 < 0 || num5 < 0 || (!(list[num4].opcode == OpCodes.Blt) && !(list[num4].opcode == OpCodes.Blt_S)))
{
list2.Clear();
break;
}
if (!(LocalOf(list[num5], store: false) is int num6))
{
list2.Clear();
break;
}
int num7 = NextReal(list, num5, -1);
int num8 = NextReal(list, num7, -1);
int num9 = NextReal(list, num8, -1);
int num10 = NextReal(list, num9, -1);
if (num10 < 0 || !(LocalOf(list[num7], store: true) is int num11) || num11 != num6 || list[num8].opcode != OpCodes.Add || list[num9].opcode != OpCodes.Ldc_I4_1 || !(LocalOf(list[num10], store: false) is int num12) || num12 != num6)
{
list2.Clear();
break;
}
list2.Add(num8);
}
}
}
LoopsPatched = list2.Count;
if (list2.Count == 8)
{
foreach (int item in list2)
{
list[item].opcode = OpCodes.Call;
list[item].operand = operand;
}
}
return list;
}
private static int NextReal(List<CodeInstruction> code, int i, int step)
{
if (i < 0)
{
return -1;
}
i += step;
while (i >= 0 && i < code.Count)
{
if (code[i].opcode != OpCodes.Nop)
{
return i;
}
i += step;
}
return -1;
}
private static object LocalOf(CodeInstruction c, bool store)
{
OpCode opcode = c.opcode;
if (store)
{
if (opcode == OpCodes.Stloc_0)
{
return 0;
}
if (opcode == OpCodes.Stloc_1)
{
return 1;
}
if (opcode == OpCodes.Stloc_2)
{
return 2;
}
if (opcode == OpCodes.Stloc_3)
{
return 3;
}
if (opcode != OpCodes.Stloc && opcode != OpCodes.Stloc_S)
{
return null;
}
}
else
{
if (opcode == OpCodes.Ldloc_0)
{
return 0;
}
if (opcode == OpCodes.Ldloc_1)
{
return 1;
}
if (opcode == OpCodes.Ldloc_2)
{
return 2;
}
if (opcode == OpCodes.Ldloc_3)
{
return 3;
}
if (opcode != OpCodes.Ldloc && opcode != OpCodes.Ldloc_S)
{
return null;
}
}
if (c.operand is LocalBuilder localBuilder)
{
return localBuilder.LocalIndex;
}
if (c.operand is int num)
{
return num;
}
if (c.operand is short num2)
{
return (int)num2;
}
if (c.operand is byte b)
{
return (int)b;
}
return null;
}
}
}