Decompiled source of ProjectEden v1.8.2

patchers/ProjectEden.Preloader.dll

Decompiled 8 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ProjectEden.Preloader")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.8.2.0")]
[assembly: AssemblyInformationalVersion("1.8.2+4cb507d33ee1b39fb2d135297296949dd4cb0a0b")]
[assembly: AssemblyProduct("Project Eden Preloader")]
[assembly: AssemblyTitle("ProjectEden.Preloader")]
[assembly: AssemblyVersion("1.8.2.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 ProjectEden.Preloader
{
	internal static class CargoIncWidener
	{
		internal class Report
		{
			internal bool Applied;

			internal readonly List<string> Blockers = new List<string>();

			internal readonly List<string> Notes = new List<string>();

			internal int WidenedParams;

			internal int WidenedLocals;

			internal int FixedIndirect;

			internal int FixedConv;

			internal int CallSites;

			internal readonly List<string> ExtraFields = new List<string>();

			internal readonly List<string> Propagated = new List<string>();
		}

		private const string CargoType = "Cargo";

		private const string IncField = "inc";

		private static readonly string[] Watched = new string[2] { "inc", "stack" };

		private static readonly string[] ExtraParams = new string[3] { "PlanetFactory::InsertInto::remainInc", "ItemPackage::.ctor::_stack", "CargoView::.ctor::_stack" };

		private static readonly string[] ExtraTargets = new string[3] { "InserterComponent::stackInput", "InserterComponent::stackOutput", "ItemPackage::stack" };

		internal static Report Apply(ModuleDefinition module)
		{
			Report report = Run(module, mutate: false);
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			return Run(module, mutate: true);
		}

		private static Report Run(ModuleDefinition module, bool mutate)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Invalid comparison between Unknown and I4
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Invalid comparison between Unknown and I4
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Invalid comparison between Unknown and I4
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Invalid comparison between Unknown and I4
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0461: Unknown result type (might be due to invalid IL or missing references)
			Report report = new Report();
			TypeDefinition type = module.GetType("Cargo");
			if (type == null)
			{
				report.Blockers.Add("找不到 Cargo 类型");
				return report;
			}
			List<FieldDefinition> list = new List<FieldDefinition>();
			string[] watched = Watched;
			foreach (string want in watched)
			{
				FieldDefinition val = ((IEnumerable<FieldDefinition>)type.Fields).FirstOrDefault((Func<FieldDefinition, bool>)((FieldDefinition x) => ((MemberReference)x).Name == want && !x.IsStatic));
				if (val == null)
				{
					report.Blockers.Add("找不到 Cargo." + want + " 字段");
					return report;
				}
				if ((int)((FieldReference)val).FieldType.MetadataType == 6)
				{
					report.Notes.Add("Cargo." + want + " 已经是 Int16,跳过(重复改写无害,但不该发生)");
					return report;
				}
				if ((int)((FieldReference)val).FieldType.MetadataType != 5)
				{
					report.Blockers.Add("Cargo." + want + " 的类型是 " + ((MemberReference)((FieldReference)val).FieldType).FullName + ",不是预期的 Byte——游戏版本可能变了,放弃改写");
					return report;
				}
				list.Add(val);
			}
			watched = ExtraTargets;
			foreach (string text in watched)
			{
				string[] parts = text.Split(new string[1] { "::" }, StringSplitOptions.None);
				TypeDefinition type2 = module.GetType(parts[0]);
				FieldDefinition val2 = ((type2 != null) ? ((IEnumerable<FieldDefinition>)type2.Fields).FirstOrDefault((Func<FieldDefinition, bool>)((FieldDefinition x) => ((MemberReference)x).Name == parts[1] && !x.IsStatic)) : null);
				if (val2 == null)
				{
					report.Blockers.Add("找不到 " + text);
					return report;
				}
				if ((int)((FieldReference)val2).FieldType.MetadataType != 6)
				{
					if ((int)((FieldReference)val2).FieldType.MetadataType != 5)
					{
						report.Blockers.Add(text + " 的类型是 " + ((MemberReference)((FieldReference)val2).FieldType).FullName + ",不是预期的 Byte");
						return report;
					}
					list.Add(val2);
				}
			}
			_ = list[0];
			TypeReference @int = module.TypeSystem.Int16;
			Dictionary<string, FieldDefinition> dictionary = new Dictionary<string, FieldDefinition>();
			foreach (FieldDefinition item in list)
			{
				dictionary[Key((FieldReference)(object)item)] = item;
			}
			DiscoverIncFields(module, dictionary, report);
			Dictionary<MethodDefinition, List<int>> dictionary2 = new Dictionary<MethodDefinition, List<int>>();
			foreach (TypeDefinition item2 in AllTypes(module))
			{
				Enumerator<MethodDefinition> enumerator3 = item2.Methods.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						MethodDefinition current2 = enumerator3.Current;
						List<int> list2 = null;
						for (int num = 0; num < ((MethodReference)current2).Parameters.Count; num++)
						{
							ParameterDefinition p = ((MethodReference)current2).Parameters[num];
							if (IsByteOrByteRef(((ParameterReference)p).ParameterType) && Watched.Any((string w) => ((ParameterReference)p).Name.StartsWith(w, StringComparison.Ordinal)))
							{
								(list2 ?? (list2 = new List<int>())).Add(num);
							}
						}
						if (list2 != null)
						{
							dictionary2[current2] = list2;
						}
					}
				}
				finally
				{
					((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose();
				}
			}
			AddSplitInc(module, dictionary2, report);
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			AddExtraParams(module, dictionary2, report);
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			Propagate(module, dictionary2, report);
			foreach (FieldDefinition value in dictionary.Values)
			{
				if (mutate)
				{
					((FieldReference)value).FieldType = @int;
				}
				if (!list.Contains(value))
				{
					report.ExtraFields.Add(((MemberReference)value).FullName);
				}
			}
			foreach (KeyValuePair<MethodDefinition, List<int>> item3 in dictionary2)
			{
				foreach (int item4 in item3.Value)
				{
					ParameterDefinition val3 = ((MethodReference)item3.Key).Parameters[item4];
					if (mutate)
					{
						((ParameterReference)val3).ParameterType = (TypeReference)((!((ParameterReference)val3).ParameterType.IsByReference) ? ((object)@int) : ((object)new ByReferenceType(@int)));
					}
					report.WidenedParams++;
				}
			}
			foreach (TypeDefinition item5 in AllTypes(module))
			{
				Enumerator<MethodDefinition> enumerator3 = item5.Methods.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						MethodDefinition current6 = enumerator3.Current;
						if (current6.HasBody)
						{
							FixBody(current6, dictionary, dictionary2, @int, report, mutate);
						}
					}
				}
				finally
				{
					((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose();
				}
			}
			SerializationFixer.Apply(module, dictionary.Values, report, mutate);
			report.Applied = report.Blockers.Count == 0;
			return report;
		}

		private static void Propagate(ModuleDefinition module, IDictionary<MethodDefinition, List<int>> widened, Report r)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			bool flag = true;
			int num = 0;
			while (flag && num++ < 16)
			{
				flag = false;
				foreach (TypeDefinition item in AllTypes(module))
				{
					Enumerator<MethodDefinition> enumerator2 = item.Methods.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							MethodDefinition current = enumerator2.Current;
							if (!current.HasBody)
							{
								continue;
							}
							Collection<Instruction> instructions = current.Body.Instructions;
							for (int i = 0; i < instructions.Count; i++)
							{
								if (instructions[i].OpCode != OpCodes.Call && instructions[i].OpCode != OpCodes.Callvirt)
								{
									continue;
								}
								MethodDefinition val = ResolveTarget(instructions[i]);
								if (val == null || !widened.TryGetValue(val, out var value))
								{
									continue;
								}
								int[] array = ArgStarts((IList<Instruction>)instructions, i, ((MethodReference)val).Parameters.Count);
								if (array == null)
								{
									continue;
								}
								foreach (int item2 in value)
								{
									int num2 = ((item2 + 1 < array.Length) ? (array[item2 + 1] - 1) : (i - 1));
									if (num2 < 0 || num2 < array[item2])
									{
										continue;
									}
									ParameterDefinition val2 = ArgOf(current, instructions[num2]);
									if (val2 != null && IsByteOrByteRef(((ParameterReference)val2).ParameterType))
									{
										if (!widened.TryGetValue(current, out var value2))
										{
											value2 = (widened[current] = new List<int>());
										}
										if (!value2.Contains(((ParameterReference)val2).Index))
										{
											value2.Add(((ParameterReference)val2).Index);
											r.Propagated.Add($"{((MemberReference)current.DeclaringType).Name}.{((MemberReference)current).Name} 第 {((ParameterReference)val2).Index} 参数 {((ParameterReference)val2).Name}");
											flag = true;
										}
									}
								}
							}
						}
					}
					finally
					{
						((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
					}
				}
			}
			if (num >= 16)
			{
				r.Blockers.Add("数据流传播 16 轮还没收敛,形状不对劲");
			}
		}

		private static void AddExtraParams(ModuleDefinition module, IDictionary<MethodDefinition, List<int>> widened, Report r)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			string[] extraParams = ExtraParams;
			foreach (string text in extraParams)
			{
				string[] array = text.Split(new string[1] { "::" }, StringSplitOptions.None);
				TypeDefinition type = module.GetType(array[0]);
				if (type == null)
				{
					r.Blockers.Add("找不到类型 " + array[0] + "(" + text + ")");
					continue;
				}
				int num = 0;
				Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						MethodDefinition current = enumerator.Current;
						if (((MemberReference)current).Name != array[1])
						{
							continue;
						}
						for (int j = 0; j < ((MethodReference)current).Parameters.Count; j++)
						{
							if (!(((ParameterReference)((MethodReference)current).Parameters[j]).Name != array[2]) && IsByteOrByteRef(((ParameterReference)((MethodReference)current).Parameters[j]).ParameterType))
							{
								if (!widened.TryGetValue(current, out var value))
								{
									value = (widened[current] = new List<int>());
								}
								if (!value.Contains(j))
								{
									value.Add(j);
								}
								num++;
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
				if (num == 0)
				{
					r.Blockers.Add(text + " 一个重载都没匹配上,签名可能变了");
				}
			}
		}

		private static MethodDefinition ResolveTarget(Instruction ins)
		{
			object operand = ins.Operand;
			MethodDefinition val = (MethodDefinition)((operand is MethodDefinition) ? operand : null);
			if (val != null)
			{
				return val;
			}
			object operand2 = ins.Operand;
			MethodReference val2 = (MethodReference)((operand2 is MethodReference) ? operand2 : null);
			if (val2 == null)
			{
				return null;
			}
			try
			{
				return val2.Resolve();
			}
			catch
			{
				return null;
			}
		}

		private static void AddSplitInc(ModuleDefinition module, IDictionary<MethodDefinition, List<int>> widened, Report r)
		{
			TypeDefinition type = module.GetType("StorageComponent");
			if (type == null)
			{
				r.Blockers.Add("找不到 StorageComponent");
				return;
			}
			MethodDefinition[] array = ((IEnumerable<MethodDefinition>)type.Methods).Where((MethodDefinition x) => ((MemberReference)x).Name == "split_inc").ToArray();
			MethodDefinition val = ((IEnumerable<MethodDefinition>)array).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition x) => ((MethodReference)x).Parameters.Count == 3 && ((IEnumerable<ParameterDefinition>)((MethodReference)x).Parameters).All((ParameterDefinition p) => IsByteOrByteRef(((ParameterReference)p).ParameterType))));
			if (val == null)
			{
				r.Blockers.Add($"找不到 split_inc 的全字节重载(共找到 {array.Length} 个同名方法)");
				return;
			}
			widened[val] = Enumerable.Range(0, ((MethodReference)val).Parameters.Count).ToList();
			r.Notes.Add("split_inc 的字节重载已列入加宽(Int32 重载保持不动)");
		}

		private static bool IsByteOrByteRef(TypeReference t)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Invalid comparison between Unknown and I4
			if ((int)t.MetadataType != 5)
			{
				if (t.IsByReference)
				{
					return (int)((TypeSpecification)(ByReferenceType)t).ElementType.MetadataType == 5;
				}
				return false;
			}
			return true;
		}

		private static void FixBody(MethodDefinition m, IDictionary<string, FieldDefinition> fields, IDictionary<MethodDefinition, List<int>> widened, TypeReference int16, Report r, bool mutate)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			Collection<Instruction> instructions = m.Body.Instructions;
			FixFeederLocals(m, (IList<Instruction>)instructions, fields, widened, int16, r, mutate);
			for (int i = 0; i < instructions.Count; i++)
			{
				Instruction val = instructions[i];
				if (val.OpCode == OpCodes.Stfld && IsWidened(val.Operand, fields))
				{
					Instruction val2 = ((i > 0) ? instructions[i - 1] : null);
					if (val2 != null && val2.OpCode == OpCodes.Conv_U1)
					{
						if (mutate)
						{
							val2.OpCode = OpCodes.Conv_I2;
						}
						r.FixedConv++;
					}
				}
				if (val.OpCode == OpCodes.Ldflda && IsWidened(val.Operand, fields))
				{
					FixIndirectRun((IList<Instruction>)instructions, i, r, mutate);
				}
				if (val.OpCode == OpCodes.Stind_I1 && StoresThroughWidenedParam(m, (IList<Instruction>)instructions, i, widened))
				{
					if (mutate)
					{
						val.OpCode = OpCodes.Stind_I2;
					}
					r.FixedIndirect++;
				}
				if (val.OpCode == OpCodes.Call || val.OpCode == OpCodes.Callvirt)
				{
					FixCallSite(m, (IList<Instruction>)instructions, i, widened, int16, r, mutate);
				}
			}
			SweepTruncations(m, (IList<Instruction>)instructions, r, mutate);
		}

		private static void SweepTruncations(MethodDefinition m, IList<Instruction> code, Report r, bool mutate)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Invalid comparison between Unknown and I4
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i + 1 < code.Count; i++)
			{
				if (code[i].OpCode != OpCodes.Conv_U1)
				{
					continue;
				}
				Instruction val = code[i + 1];
				TypeReference val2 = null;
				if (val.OpCode == OpCodes.Stfld || val.OpCode == OpCodes.Stsfld)
				{
					object operand = val.Operand;
					FieldReference val3 = (FieldReference)((operand is FieldReference) ? operand : null);
					if (val3 != null)
					{
						val2 = val3.FieldType;
						goto IL_0080;
					}
				}
				VariableDefinition val4 = VarOf(m, val, load: false);
				if (val4 != null)
				{
					val2 = ((VariableReference)val4).VariableType;
				}
				goto IL_0080;
				IL_0080:
				if (val2 != null && (int)val2.MetadataType == 6)
				{
					if (mutate)
					{
						code[i].OpCode = OpCodes.Conv_I2;
					}
					r.FixedConv++;
				}
			}
		}

		private static void FixFeederLocals(MethodDefinition m, IList<Instruction> code, IDictionary<string, FieldDefinition> fields, IDictionary<MethodDefinition, List<int>> widened, TypeReference int16, Report r, bool mutate)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Invalid comparison between Unknown and I4
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			HashSet<VariableDefinition> hashSet = new HashSet<VariableDefinition>();
			for (int i = 1; i < code.Count; i++)
			{
				if (!(code[i].OpCode != OpCodes.Stfld) && IsWidened(code[i].Operand, fields))
				{
					VariableDefinition val = VarOf(m, code[i - 1], load: true);
					if (val != null)
					{
						hashSet.Add(val);
					}
				}
			}
			for (int j = 0; j < code.Count; j++)
			{
				if (code[j].OpCode != OpCodes.Call && code[j].OpCode != OpCodes.Callvirt)
				{
					continue;
				}
				MethodDefinition val2 = ResolveTarget(code[j]);
				if (val2 == null || !widened.TryGetValue(val2, out var value))
				{
					continue;
				}
				int[] array = ArgStarts(code, j, ((MethodReference)val2).Parameters.Count);
				if (array == null)
				{
					continue;
				}
				foreach (int item in value)
				{
					if (((ParameterReference)((MethodReference)val2).Parameters[item]).ParameterType.IsByReference)
					{
						continue;
					}
					int num = ((item + 1 < array.Length) ? (array[item + 1] - 1) : (j - 1));
					if (num >= 0 && num >= array[item])
					{
						VariableDefinition val3 = VarOf(m, code[num], load: true);
						if (val3 != null)
						{
							hashSet.Add(val3);
						}
					}
				}
			}
			if (hashSet.Count == 0)
			{
				return;
			}
			for (int k = 1; k < code.Count; k++)
			{
				VariableDefinition val4 = VarOf(m, code[k], load: false);
				if (val4 == null || !hashSet.Contains(val4))
				{
					continue;
				}
				if (code[k - 1].OpCode == OpCodes.Conv_U1)
				{
					if (mutate)
					{
						code[k - 1].OpCode = OpCodes.Conv_I2;
					}
					r.FixedConv++;
				}
				if ((int)((VariableReference)val4).VariableType.MetadataType == 5)
				{
					if (mutate)
					{
						((VariableReference)val4).VariableType = int16;
					}
					r.WidenedLocals++;
				}
			}
		}

		private static VariableDefinition VarOf(MethodDefinition m, Instruction ins, bool load)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			object operand = ins.Operand;
			VariableDefinition val = (VariableDefinition)((operand is VariableDefinition) ? operand : null);
			if (val != null)
			{
				bool flag = ins.OpCode == OpCodes.Ldloc || ins.OpCode == OpCodes.Ldloc_S;
				bool flag2 = ins.OpCode == OpCodes.Stloc || ins.OpCode == OpCodes.Stloc_S;
				if (!load)
				{
					if (!flag2)
					{
						return null;
					}
					return val;
				}
				if (!flag)
				{
					return null;
				}
				return val;
			}
			int num = -1;
			if (load)
			{
				if (ins.OpCode == OpCodes.Ldloc_0)
				{
					num = 0;
				}
				else if (ins.OpCode == OpCodes.Ldloc_1)
				{
					num = 1;
				}
				else if (ins.OpCode == OpCodes.Ldloc_2)
				{
					num = 2;
				}
				else if (ins.OpCode == OpCodes.Ldloc_3)
				{
					num = 3;
				}
			}
			else if (ins.OpCode == OpCodes.Stloc_0)
			{
				num = 0;
			}
			else if (ins.OpCode == OpCodes.Stloc_1)
			{
				num = 1;
			}
			else if (ins.OpCode == OpCodes.Stloc_2)
			{
				num = 2;
			}
			else if (ins.OpCode == OpCodes.Stloc_3)
			{
				num = 3;
			}
			if (num < 0 || num >= m.Body.Variables.Count)
			{
				return null;
			}
			return m.Body.Variables[num];
		}

		private static string Key(FieldReference f)
		{
			return ((MemberReference)((MemberReference)f).DeclaringType).FullName + "::" + ((MemberReference)f).Name;
		}

		private static bool IsWidened(object operand, IDictionary<string, FieldDefinition> fields)
		{
			FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null);
			if (val != null)
			{
				return fields.ContainsKey(Key(val));
			}
			return false;
		}

		private static void DiscoverIncFields(ModuleDefinition module, IDictionary<string, FieldDefinition> fields, Report r)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Invalid comparison between Unknown and I4
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Invalid comparison between Unknown and I4
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			foreach (TypeDefinition item in AllTypes(module))
			{
				Enumerator<MethodDefinition> enumerator2 = item.Methods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current = enumerator2.Current;
						if (!current.HasBody)
						{
							continue;
						}
						Collection<Instruction> instructions = current.Body.Instructions;
						for (int i = 0; i < instructions.Count; i++)
						{
							if (instructions[i].OpCode != OpCodes.Stfld)
							{
								continue;
							}
							object operand = instructions[i].Operand;
							FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null);
							if (val == null || (int)val.FieldType.MetadataType != 5 || fields.ContainsKey(Key(val)))
							{
								continue;
							}
							bool flag = false;
							int num = i - 1;
							while (num >= 0 && num >= i - 8)
							{
								OpCode opCode = instructions[num].OpCode;
								if ((int)((OpCode)(ref opCode)).FlowControl == 0)
								{
									break;
								}
								opCode = instructions[num].OpCode;
								if ((int)((OpCode)(ref opCode)).FlowControl == 3)
								{
									break;
								}
								if (instructions[num].OpCode == OpCodes.Ldfld)
								{
									object operand2 = instructions[num].Operand;
									FieldReference val2 = (FieldReference)((operand2 is FieldReference) ? operand2 : null);
									if (val2 != null && ((MemberReference)((MemberReference)val2).DeclaringType).Name == "Cargo" && Watched.Contains(((MemberReference)val2).Name))
									{
										flag = true;
										break;
									}
								}
								num--;
							}
							if (flag)
							{
								FieldDefinition val3;
								try
								{
									val3 = val.Resolve();
								}
								catch
								{
									val3 = null;
								}
								if (val3 == null)
								{
									r.Blockers.Add("字段 " + ((MemberReference)val).FullName + " 接住了 Cargo.inc 但解析不到定义");
								}
								else
								{
									fields[Key(val)] = val3;
								}
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
				}
			}
		}

		private static void FixIndirectRun(IList<Instruction> code, int start, Report r, bool mutate)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			for (int i = start + 1; i < code.Count && i <= start + 10; i++)
			{
				Instruction val = code[i];
				if (val.OpCode == OpCodes.Ldind_U1)
				{
					if (mutate)
					{
						val.OpCode = OpCodes.Ldind_I2;
					}
					r.FixedIndirect++;
					continue;
				}
				if (val.OpCode == OpCodes.Conv_U1)
				{
					if (mutate)
					{
						val.OpCode = OpCodes.Conv_I2;
					}
					r.FixedConv++;
					continue;
				}
				if (val.OpCode == OpCodes.Stind_I1)
				{
					if (mutate)
					{
						val.OpCode = OpCodes.Stind_I2;
					}
					r.FixedIndirect++;
					break;
				}
				if (val.OpCode == OpCodes.Ldflda || val.OpCode == OpCodes.Ldfld)
				{
					break;
				}
			}
		}

		private static bool StoresThroughWidenedParam(MethodDefinition m, IList<Instruction> code, int at, IDictionary<MethodDefinition, List<int>> widened)
		{
			if (!widened.TryGetValue(m, out var value))
			{
				return false;
			}
			int num = at - 1;
			while (num >= 0 && num >= at - 12)
			{
				ParameterDefinition val = ArgOf(m, code[num]);
				if (val != null)
				{
					return value.Contains(((ParameterReference)val).Index);
				}
				num--;
			}
			return false;
		}

		private static ParameterDefinition ArgOf(MethodDefinition m, Instruction ins)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			object operand = ins.Operand;
			ParameterDefinition val = (ParameterDefinition)((operand is ParameterDefinition) ? operand : null);
			if (val != null)
			{
				return val;
			}
			int? num = ((ins.OpCode == OpCodes.Ldarg_0) ? new int?(0) : ((ins.OpCode == OpCodes.Ldarg_1) ? new int?(1) : ((ins.OpCode == OpCodes.Ldarg_2) ? new int?(2) : ((ins.OpCode == OpCodes.Ldarg_3) ? new int?(3) : ((int?)null)))));
			if (!num.HasValue)
			{
				return null;
			}
			int num2 = (((MethodReference)m).HasThis ? 1 : 0);
			int num3 = num.Value - num2;
			if (num3 < 0 || num3 >= ((MethodReference)m).Parameters.Count)
			{
				return null;
			}
			return ((MethodReference)m).Parameters[num3];
		}

		private static void FixCallSite(MethodDefinition m, IList<Instruction> code, int at, IDictionary<MethodDefinition, List<int>> widened, TypeReference int16, Report r, bool mutate)
		{
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			object operand = code[at].Operand;
			MethodDefinition val = (MethodDefinition)((operand is MethodDefinition) ? operand : null);
			if (val == null)
			{
				object operand2 = code[at].Operand;
				MethodReference val2 = (MethodReference)((operand2 is MethodReference) ? operand2 : null);
				if (val2 != null)
				{
					try
					{
						val = val2.Resolve();
					}
					catch
					{
						val = null;
					}
				}
			}
			if (val == null || !widened.TryGetValue(val, out var value))
			{
				return;
			}
			r.CallSites++;
			int[] array = ArgStarts(code, at, ((MethodReference)val).Parameters.Count);
			if (array == null)
			{
				r.Blockers.Add(((MemberReference)m).FullName + " 调用 " + ((MemberReference)val).Name + ":栈深度倒推切不出实参边界");
				return;
			}
			foreach (int item in value)
			{
				int num = ((item + 1 < array.Length) ? (array[item + 1] - 1) : (at - 1));
				if (num < 0 || num < array[item])
				{
					r.Blockers.Add($"{((MemberReference)m).FullName} 调用 {((MemberReference)val).Name} 第 {item} 参数:实参段为空");
				}
				else if (!((ParameterReference)((MethodReference)val).Parameters[item]).ParameterType.IsByReference)
				{
					if (code[num].OpCode == OpCodes.Conv_U1)
					{
						if (mutate)
						{
							code[num].OpCode = OpCodes.Conv_I2;
						}
						r.FixedConv++;
					}
				}
				else
				{
					Classify(m, code[num], val, item, widened, int16, r, mutate);
				}
			}
		}

		private static void Classify(MethodDefinition m, Instruction a, MethodDefinition target, int argIndex, IDictionary<MethodDefinition, List<int>> widened, TypeReference int16, Report r, bool mutate)
		{
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Invalid comparison between Unknown and I4
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Invalid comparison between Unknown and I4
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			object operand = a.Operand;
			VariableDefinition val = (VariableDefinition)((operand is VariableDefinition) ? operand : null);
			if (val != null)
			{
				bool isByReference = ((VariableReference)val).VariableType.IsByReference;
				TypeReference val2 = (isByReference ? ((TypeSpecification)(ByReferenceType)((VariableReference)val).VariableType).ElementType : ((VariableReference)val).VariableType);
				if ((int)val2.MetadataType == 5)
				{
					if (mutate)
					{
						((VariableReference)val).VariableType = (TypeReference)((!isByReference) ? ((object)int16) : ((object)new ByReferenceType(int16)));
					}
					r.WidenedLocals++;
				}
				else if ((int)val2.MetadataType != 6)
				{
					r.Blockers.Add($"{((MemberReference)m).FullName} 调用 {((MemberReference)target).Name} 第 {argIndex} 参数:" + "局部变量类型是 " + ((MemberReference)((VariableReference)val).VariableType).FullName + ",既不是 Byte 也不是 Int16");
				}
				return;
			}
			ParameterDefinition val3 = ArgOf(m, a);
			if (val3 != null)
			{
				if (!widened.TryGetValue(m, out var value) || !value.Contains(((ParameterReference)val3).Index))
				{
					r.Blockers.Add($"{((MemberReference)m).FullName} 调用 {((MemberReference)target).Name} 第 {argIndex} 参数:" + "转手的是本方法的参数 " + ((ParameterReference)val3).Name + ",但它不在加宽名单里");
				}
			}
			else if (a.OpCode == OpCodes.Ldflda || a.OpCode == OpCodes.Ldsflda)
			{
				object operand2 = a.Operand;
				FieldReference val4 = (FieldReference)((operand2 is FieldReference) ? operand2 : null);
				if (val4 == null || !(((MemberReference)((MemberReference)val4).DeclaringType).Name == "Cargo") || !Watched.Contains(((MemberReference)val4).Name))
				{
					r.Blockers.Add($"{((MemberReference)m).FullName} 调用 {((MemberReference)target).Name} 第 {argIndex} 参数:" + "传的是字段 " + ((val4 != null) ? ((MemberReference)val4).FullName : null) + " 的地址,那个字段没有被加宽");
				}
			}
			else
			{
				List<string> blockers = r.Blockers;
				string text = $"{((MemberReference)m).FullName} 调用 {((MemberReference)target).Name} 第 {argIndex} 参数:";
				OpCode opCode = a.OpCode;
				blockers.Add(text + "地址来源是 " + ((OpCode)(ref opCode)).Name + ",形状没见过");
			}
		}

		private static int[] ArgStarts(IList<Instruction> code, int at, int argCount)
		{
			if (argCount == 0)
			{
				return new int[0];
			}
			int[] array = new int[argCount];
			int num = at - 1;
			for (int num2 = argCount - 1; num2 >= 0; num2--)
			{
				int num3 = 0;
				bool flag = false;
				while (num >= 0)
				{
					num3 += PushCount(code[num]) - PopCount(code[num]);
					if (num3 == 1)
					{
						array[num2] = num;
						num--;
						flag = true;
						break;
					}
					num--;
				}
				if (!flag)
				{
					return null;
				}
			}
			return array;
		}

		private static int PopCount(Instruction ins)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected I4, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			OpCode opCode = ins.OpCode;
			StackBehaviour stackBehaviourPop = ((OpCode)(ref opCode)).StackBehaviourPop;
			switch ((int)stackBehaviourPop)
			{
			case 0:
				return 0;
			case 1:
			case 3:
			case 10:
				return 1;
			case 2:
			case 4:
			case 5:
			case 6:
			case 8:
			case 9:
			case 11:
			case 12:
				return 2;
			case 7:
			case 13:
			case 14:
			case 15:
			case 16:
			case 17:
				return 3;
			case 27:
			{
				object operand = ins.Operand;
				MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null);
				if (val != null)
				{
					int num = val.Parameters.Count;
					if (val.HasThis && ins.OpCode != OpCodes.Newobj)
					{
						num++;
					}
					return num;
				}
				return 0;
			}
			default:
				return 0;
			}
		}

		private static int PushCount(Instruction ins)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected I4, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Invalid comparison between Unknown and I4
			OpCode opCode = ins.OpCode;
			StackBehaviour stackBehaviourPush = ((OpCode)(ref opCode)).StackBehaviourPush;
			switch (stackBehaviourPush - 19)
			{
			case 0:
				return 0;
			case 1:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
				return 1;
			case 2:
				return 2;
			case 9:
			{
				object operand = ins.Operand;
				MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null);
				if (val != null)
				{
					return ((int)val.ReturnType.MetadataType != 1) ? 1 : 0;
				}
				return 1;
			}
			default:
				return 0;
			}
		}

		private static IEnumerable<TypeDefinition> AllTypes(ModuleDefinition module)
		{
			Enumerator<TypeDefinition> enumerator = module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					foreach (TypeDefinition item in WithNested(current))
					{
						yield return item;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static IEnumerable<TypeDefinition> WithNested(TypeDefinition t)
		{
			yield return t;
			Enumerator<TypeDefinition> enumerator = t.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					foreach (TypeDefinition item in WithNested(current))
					{
						yield return item;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
		}
	}
	public static class Patcher
	{
		private static readonly ManualLogSource Log = Logger.CreateLogSource("ProjectEden.Preloader");

		public static IEnumerable<string> TargetDLLs { get; } = new string[1] { "Assembly-CSharp.dll" };

		public static void Patch(AssemblyDefinition assembly)
		{
			CargoIncWidener.Report report = CargoIncWidener.Apply(assembly.MainModule);
			foreach (string note in report.Notes)
			{
				Log.LogInfo((object)note);
			}
			if (!report.Applied)
			{
				Log.LogError((object)$"Cargo.inc 加宽**未执行**,共 {report.Blockers.Count} 条阻塞项(程序集保持原样,游戏照常跑):");
				foreach (string blocker in report.Blockers)
				{
					Log.LogError((object)("  " + blocker));
				}
				Log.LogError((object)"传送带集装超过 63 层时,增产点数仍然只能按一个字节结算——运行时的 CargoIncClampPatches 会把它夹在 255,是确定的降级,不是失真。");
			}
			else
			{
				if (report.Propagated.Count > 0)
				{
					Log.LogInfo((object)($"数据流传播另外认出 {report.Propagated.Count} 个字节参数(名字上看不出来):" + string.Join("、", report.Propagated.ToArray())));
				}
				Log.LogWarning((object)($"Cargo.inc 已加宽为 Int16:签名 {report.WidenedParams} 处、局部变量 {report.WidenedLocals} 个、" + $"间接读写 {report.FixedIndirect} 处、截断指令 {report.FixedConv} 处,覆盖 {report.CallSites} 个调用点。" + "存档从此绑定本 mod。"));
				AddQualityFields(assembly);
			}
		}

		private static void AddQualityFields(AssemblyDefinition assembly)
		{
			QualityFieldAdder.Report report = QualityFieldAdder.Apply(assembly.MainModule);
			foreach (string note in report.Notes)
			{
				Log.LogInfo((object)note);
			}
			if (!report.Applied)
			{
				Log.LogError((object)$"物品品质:孪生字段**未添加**,共 {report.Blockers.Count} 条阻塞项(程序集这部分保持原样):");
				{
					foreach (string blocker in report.Blockers)
					{
						Log.LogError((object)("  " + blocker));
					}
					return;
				}
			}
			Log.LogWarning((object)$"物品品质:已添加 {report.Added.Count} 个孪生字段(阶段 1a)。");
			BuildQualityChannel(assembly);
		}

		private static void BuildQualityChannel(AssemblyDefinition assembly)
		{
			QualityChannelBuilder.Report report = QualityChannelBuilder.Apply(assembly.MainModule);
			foreach (string note in report.Notes)
			{
				Log.LogInfo((object)note);
			}
			if (!report.Applied)
			{
				Log.LogError((object)$"物品品质:侧信道**未合成**,共 {report.Blockers.Count} 条阻塞项:");
				{
					foreach (string blocker in report.Blockers)
					{
						Log.LogError((object)("  " + blocker));
					}
					return;
				}
			}
			Log.LogInfo((object)$"物品品质:侧信道已就位({report.Registers} 个线程静态寄存器)。");
			RewriteQualityFlow(assembly);
		}

		private static void RewriteQualityFlow(AssemblyDefinition assembly)
		{
			QualityTransform.Report report = QualityTransform.Apply(assembly.MainModule);
			foreach (string note in report.Notes)
			{
				Log.LogInfo((object)note);
			}
			if (report.Blockers.Count > 0 || report.Unhandled.Count > 0 || report.Pending.Count > 0)
			{
				Log.LogError((object)($"物品品质:**品质流动未启用**——阻塞 {report.Blockers.Count} 条、" + $"未识别形状 {report.Unhandled.Count} 种、认得但没发射 {report.Pending.Count} 种。" + "字段和侧信道仍在,品质恒为 0,游戏行为与不加时一致。"));
				foreach (string blocker in report.Blockers)
				{
					Log.LogError((object)("  " + blocker));
				}
				foreach (string key in report.Unhandled.Keys)
				{
					Log.LogError((object)("  未识别形状:" + key));
				}
				{
					foreach (string key2 in report.Pending.Keys)
					{
						Log.LogError((object)("  没有发射器:" + key2));
					}
					return;
				}
			}
			Log.LogInfo((object)($"物品品质:品质流动已启用——{report.Twinned} 条孪生语句、{report.TwinLocals} 个孪生局部、" + $"{report.ChannelUses} 处走侧信道,涉及 {report.Methods} 个方法体;{report.Dropped} 处明确丢弃。"));
			ExtendQualitySave(assembly);
		}

		private static void ExtendQualitySave(AssemblyDefinition assembly)
		{
			QualitySaveExtender.Report report = QualitySaveExtender.Apply(assembly.MainModule);
			foreach (string note in report.Notes)
			{
				Log.LogInfo((object)note);
			}
			if (!report.Applied)
			{
				Log.LogError((object)($"物品品质:**品质没能进存档**({report.Blockers.Count} 条阻塞项)。" + "品质仍然会随货物流动,但每次读档归零。存档格式一个字节都没改。"));
				{
					foreach (string blocker in report.Blockers)
					{
						Log.LogError((object)("  " + blocker));
					}
					return;
				}
			}
			Log.LogWarning((object)($"物品品质:品质已进存档——{report.Writes} 处写、{report.Reads} 处按版本分流读。" + "**存档格式变了**:新存档必须带着这个 mod 才能打开,老存档照常能读(品质按 0 算)。自动集装机「正在叠的那一堆」的品质仍不入档——它的 Import 没保留版本号,没法分流。"));
		}
	}
	internal static class QualityChannelBuilder
	{
		internal class Report
		{
			internal bool Applied;

			internal readonly List<string> Blockers = new List<string>();

			internal readonly List<string> Notes = new List<string>();

			internal int Registers;

			internal bool AlreadyThere;
		}

		internal const string TypeName = "ProjectEdenQualityChannel";

		internal const int RegisterCount = 4;

		internal const string SplitName = "Split";

		internal static Report Apply(ModuleDefinition module)
		{
			Report report = Run(module, mutate: false);
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			return Run(module, mutate: true);
		}

		private static Report Run(ModuleDefinition module, bool mutate)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			Report report = new Report();
			QualityFieldAnalyzer.Report report2 = QualityFieldAnalyzer.Analyze(module);
			if (report2.MaxParamSlots > 4)
			{
				report.Blockers.Add($"有方法带 {report2.MaxParamSlots} 个载荷参数位({report2.MaxParamSlotsAt})," + $"超过寄存器数 {4}——跨边界传递时会互相覆盖。把 RegisterCount 调大");
				return report;
			}
			TypeDefinition type = module.GetType("ProjectEdenQualityChannel");
			if (type != null)
			{
				report.AlreadyThere = true;
				report.Registers = ((IEnumerable<FieldDefinition>)type.Fields).Count((FieldDefinition f) => f.IsStatic);
				report.Applied = true;
				report.Notes.Add(string.Format("品质侧信道:{0} 已存在({1} 个寄存器),跳过", "ProjectEdenQualityChannel", report.Registers));
				return report;
			}
			MethodReference val = ResolveThreadStaticCtor(module, report);
			if (val == null)
			{
				return report;
			}
			if (mutate)
			{
				TypeDefinition val2 = new TypeDefinition(string.Empty, "ProjectEdenQualityChannel", (TypeAttributes)1048961, module.TypeSystem.Object);
				for (int num = 0; num < 4; num++)
				{
					FieldDefinition val3 = new FieldDefinition("Q" + num, (FieldAttributes)22, module.TypeSystem.Int32);
					val3.CustomAttributes.Add(new CustomAttribute(val));
					val2.Fields.Add(val3);
				}
				val2.Methods.Add(BuildSplit(module));
				module.Types.Add(val2);
			}
			report.Registers = 4;
			report.Applied = true;
			report.Notes.Add(string.Format("品质侧信道:已合成 {0},{1} 个 [ThreadStatic] Int32 寄存器", "ProjectEdenQualityChannel", 4) + $"(实测单方法最多 {report2.MaxParamSlots} 个槽位)。" + "签名一个都没动,其它 mod 不受影响。");
			return report;
		}

		private static MethodDefinition BuildSplit(ModuleDefinition module)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: 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)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			//IL_0356: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Unknown result type (might be due to invalid IL or missing references)
			//IL_037b: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0410: Unknown result type (might be due to invalid IL or missing references)
			//IL_0420: Expected O, but got Unknown
			TypeReference @int = module.TypeSystem.Int32;
			MethodDefinition val = new MethodDefinition("Split", (MethodAttributes)150, @int);
			((MethodReference)val).Parameters.Add(new ParameterDefinition("countAfter", (ParameterAttributes)0, @int));
			((MethodReference)val).Parameters.Add(new ParameterDefinition("qua", (ParameterAttributes)0, (TypeReference)new ByReferenceType(@int)));
			((MethodReference)val).Parameters.Add(new ParameterDefinition("p", (ParameterAttributes)0, @int));
			VariableDefinition val2 = new VariableDefinition(@int);
			VariableDefinition val3 = new VariableDefinition(@int);
			VariableDefinition val4 = new VariableDefinition(@int);
			VariableDefinition val5 = new VariableDefinition(@int);
			val.Body.Variables.Add(val2);
			val.Body.Variables.Add(val3);
			val.Body.Variables.Add(val4);
			val.Body.Variables.Add(val5);
			val.Body.InitLocals = true;
			ILProcessor iLProcessor = val.Body.GetILProcessor();
			Instruction val6 = iLProcessor.Create(OpCodes.Ldarg_1);
			Instruction val7 = iLProcessor.Create(OpCodes.Ldarg_1);
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldarg_0));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldarg_2));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Add));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Stloc, val2));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val2));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldc_I4_0));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Bgt, val6));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldarg_1));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldc_I4_0));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Stind_I4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldc_I4_0));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ret));
			iLProcessor.Append(val6);
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldind_I4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val2));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Div));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Stloc, val3));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldarg_1));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldind_I4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val3));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val2));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Mul));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Sub));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Stloc, val4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldarg_0));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Sub));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Stloc, val4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val3));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldarg_2));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Mul));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Stloc, val5));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldc_I4_0));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ble, val7));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val5));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Add));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Stloc, val5));
			iLProcessor.Append(val7);
			iLProcessor.Append(iLProcessor.Create(OpCodes.Dup));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldind_I4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val5));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Sub));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Stind_I4));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ldloc, val5));
			iLProcessor.Append(iLProcessor.Create(OpCodes.Ret));
			return val;
		}

		private static MethodReference ResolveThreadStaticCtor(ModuleDefinition module, Report r)
		{
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			AssemblyNameReference val = ((IEnumerable<AssemblyNameReference>)module.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference x) => x.Name == "mscorlib")) ?? ((IEnumerable<AssemblyNameReference>)module.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference x) => x.Name == "System.Runtime")) ?? ((IEnumerable<AssemblyNameReference>)module.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference x) => x.Name == "netstandard"));
			if (val == null)
			{
				r.Blockers.Add("在目标模块的程序集引用里找不到 mscorlib / System.Runtime,无法建 ThreadStatic 引用");
				return null;
			}
			TypeReference val2 = new TypeReference("System", "ThreadStaticAttribute", module, (IMetadataScope)(object)val);
			return new MethodReference(".ctor", module.TypeSystem.Void, val2)
			{
				HasThis = true
			};
		}

		internal static Report Verify(ModuleDefinition module)
		{
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Invalid comparison between Unknown and I4
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Invalid comparison between Unknown and I4
			Report report = new Report();
			TypeDefinition type = module.GetType("ProjectEdenQualityChannel");
			if (type == null)
			{
				report.Blockers.Add("写盘之后找不到 ProjectEdenQualityChannel");
				return report;
			}
			MethodDefinition val = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition x) => ((MemberReference)x).Name == "Split"));
			if (val == null)
			{
				report.Blockers.Add("ProjectEdenQualityChannel::Split 写盘之后不见了");
			}
			else if (!val.IsStatic || ((MethodReference)val).Parameters.Count != 3 || !((ParameterReference)((MethodReference)val).Parameters[1]).ParameterType.IsByReference || (int)((MethodReference)val).ReturnType.MetadataType != 8)
			{
				report.Blockers.Add("ProjectEdenQualityChannel::Split 的签名不对:应为 static int Split(int, ref int, int)");
			}
			else if (!val.HasBody || val.Body.Instructions.Count < 20)
			{
				report.Blockers.Add("ProjectEdenQualityChannel::Split 的方法体太短,像是没写完");
			}
			Enumerator<FieldDefinition> enumerator = type.Fields.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					FieldDefinition current = enumerator.Current;
					if (!current.IsStatic)
					{
						report.Blockers.Add("ProjectEdenQualityChannel::" + ((MemberReference)current).Name + " 不是静态字段");
					}
					else if ((int)((FieldReference)current).FieldType.MetadataType != 8)
					{
						report.Blockers.Add("ProjectEdenQualityChannel::" + ((MemberReference)current).Name + " 的类型是 " + ((MemberReference)((FieldReference)current).FieldType).Name + ",不是 Int32");
					}
					else if (!((IEnumerable<CustomAttribute>)current.CustomAttributes).Any((CustomAttribute c) => ((MemberReference)c.AttributeType).Name == "ThreadStaticAttribute"))
					{
						report.Blockers.Add("ProjectEdenQualityChannel::" + ((MemberReference)current).Name + " 没有 ThreadStatic 特性——三十多个 tick 线程会共用同一个寄存器,品质会在高负载下偶尔串味且不报错");
					}
					else
					{
						report.Registers++;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			if (report.Registers != 4)
			{
				report.Blockers.Add($"寄存器数是 {report.Registers},期望 {4}");
			}
			report.Applied = report.Blockers.Count == 0;
			return report;
		}
	}
	internal static class QualityFieldAdder
	{
		internal class Report
		{
			internal bool Applied;

			internal readonly List<string> Blockers = new List<string>();

			internal readonly List<string> Notes = new List<string>();

			internal readonly List<string> Added = new List<string>();

			internal int AlreadyThere;
		}

		internal const int ExpectedFields = 29;

		internal static Report Apply(ModuleDefinition module)
		{
			Report report = Run(module, mutate: false);
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			return Run(module, mutate: true);
		}

		private static Report Run(ModuleDefinition module, bool mutate)
		{
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Expected O, but got Unknown
			Report report = new Report();
			QualityFieldAnalyzer.Report report2 = QualityFieldAnalyzer.Analyze(module);
			if (!report2.Clean)
			{
				report.Blockers.Add($"分析未通过({report2.Blockers.Count} 条),不加任何字段");
				{
					foreach (string blocker in report2.Blockers)
					{
						report.Blockers.Add("  " + blocker);
					}
					return report;
				}
			}
			Dictionary<string, FieldDefinition> dictionary = new Dictionary<string, FieldDefinition>(StringComparer.Ordinal);
			QualityFieldAnalyzer.ResolvePayload(module, dictionary, report.Blockers);
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			TypeReference @int = module.TypeSystem.Int32;
			foreach (FieldDefinition item in dictionary.Values.OrderBy<FieldDefinition, string>((FieldDefinition f) => ((MemberReference)f).FullName, StringComparer.Ordinal))
			{
				string twinName = TwinName(((MemberReference)item).Name);
				if (twinName == null)
				{
					report.Blockers.Add(((MemberReference)item.DeclaringType).FullName + "::" + ((MemberReference)item).Name + " 的名字推不出孪生名——TwinName 只认 inc / _inc / inc* / *Inc 四种形状,加字段前先决定它该叫什么");
					continue;
				}
				TypeDefinition declaringType = item.DeclaringType;
				FieldDefinition val = ((IEnumerable<FieldDefinition>)declaringType.Fields).FirstOrDefault((Func<FieldDefinition, bool>)((FieldDefinition f) => ((MemberReference)f).Name == twinName));
				if (val != null)
				{
					report.AlreadyThere++;
					if (((MemberReference)((FieldReference)val).FieldType).FullName != ((MemberReference)TwinType(item, @int)).FullName)
					{
						report.Blockers.Add(((MemberReference)declaringType).FullName + "::" + twinName + " 已存在但类型是 " + ((MemberReference)((FieldReference)val).FieldType).FullName + ",和预期的孪生类型不符");
					}
					continue;
				}
				TypeReference val2 = TwinType(item, @int);
				if (mutate)
				{
					FieldDefinition val3 = new FieldDefinition(twinName, (FieldAttributes)6, val2);
					declaringType.Fields.Add(val3);
				}
				report.Added.Add(((MemberReference)declaringType).FullName + "::" + ((MemberReference)item).Name + " → " + twinName + " (" + ((MemberReference)val2).Name + ")");
			}
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			int num = report.Added.Count + report.AlreadyThere;
			if (num != 29)
			{
				report.Blockers.Add($"孪生字段数是 {num},期望 {29}——" + "载荷清单和程序集对不上,先跑 tools\\verify_quality.ps1 看分析报告");
				return report;
			}
			report.Notes.Add($"品质孪生字段:新增 {report.Added.Count} 个" + ((report.AlreadyThere > 0) ? $",{report.AlreadyThere} 个已存在(重复执行?)" : "") + "。此刻它们恒为 0 / null,游戏行为零变化——写它们的代码在 1b / 1c。");
			report.Applied = true;
			return report;
		}

		internal static Report Verify(ModuleDefinition module)
		{
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Invalid comparison between Unknown and I4
			Report report = new Report();
			Dictionary<string, FieldDefinition> dictionary = new Dictionary<string, FieldDefinition>(StringComparer.Ordinal);
			QualityFieldAnalyzer.ResolvePayload(module, dictionary, report.Blockers);
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			foreach (FieldDefinition item in dictionary.Values.OrderBy<FieldDefinition, string>((FieldDefinition f) => ((MemberReference)f).FullName, StringComparer.Ordinal))
			{
				string twinName = TwinName(((MemberReference)item).Name);
				if (twinName == null)
				{
					report.Blockers.Add(((MemberReference)item.DeclaringType).FullName + "::" + ((MemberReference)item).Name + " 推不出孪生名");
					continue;
				}
				FieldDefinition val = ((IEnumerable<FieldDefinition>)item.DeclaringType.Fields).FirstOrDefault((Func<FieldDefinition, bool>)((FieldDefinition f) => ((MemberReference)f).Name == twinName && !f.IsStatic));
				if (val == null)
				{
					report.Blockers.Add(((MemberReference)item.DeclaringType).FullName + "::" + twinName + " 写盘之后不见了");
					continue;
				}
				bool num = ((FieldReference)item).FieldType is ArrayType;
				bool flag = ((FieldReference)val).FieldType is ArrayType;
				if (num != flag)
				{
					report.Blockers.Add(((MemberReference)item.DeclaringType).FullName + "::" + twinName + " 的数组性和原字段不一致(原 " + ((MemberReference)((FieldReference)item).FieldType).Name + " / 孪生 " + ((MemberReference)((FieldReference)val).FieldType).Name + ")");
					continue;
				}
				TypeReference val2 = (flag ? ((TypeSpecification)(ArrayType)((FieldReference)val).FieldType).ElementType : ((FieldReference)val).FieldType);
				if ((int)val2.MetadataType != 8)
				{
					report.Blockers.Add(((MemberReference)item.DeclaringType).FullName + "::" + twinName + " 的元素类型是 " + ((MemberReference)val2).Name + ",不是 Int32");
				}
				else
				{
					report.Added.Add(((MemberReference)item.DeclaringType).FullName + "::" + twinName);
				}
			}
			if (report.Added.Count != 29)
			{
				report.Blockers.Add($"写盘后核到 {report.Added.Count} 个孪生字段,期望 {29}");
			}
			report.Applied = report.Blockers.Count == 0;
			return report;
		}

		private static TypeReference TwinType(FieldDefinition src, TypeReference int32)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			if (!(((FieldReference)src).FieldType is ArrayType))
			{
				return int32;
			}
			return (TypeReference)new ArrayType(int32);
		}

		internal static string TwinName(string name)
		{
			if (name == "inc")
			{
				return "qua";
			}
			if (name == "_inc")
			{
				return "_qua";
			}
			if (name.StartsWith("inc", StringComparison.Ordinal) && name.Length > 3 && char.IsUpper(name[3]))
			{
				return "qua" + name.Substring(3);
			}
			if (name.EndsWith("Inc", StringComparison.Ordinal) && name.Length > 3)
			{
				return name.Substring(0, name.Length - 3) + "Qua";
			}
			int num = name.LastIndexOf("Inc", StringComparison.Ordinal);
			if (num > 0 && num + 3 < name.Length && AllDigits(name, num + 3))
			{
				return name.Substring(0, num) + "Qua" + name.Substring(num + 3);
			}
			return null;
		}

		private static bool AllDigits(string s, int from)
		{
			for (int i = from; i < s.Length; i++)
			{
				if (!char.IsDigit(s[i]))
				{
					return false;
				}
			}
			return true;
		}
	}
	internal static class QualityFieldAnalyzer
	{
		internal class Report
		{
			internal bool Clean;

			internal readonly List<string> Blockers = new List<string>();

			internal readonly List<string> Notes = new List<string>();

			internal int PayloadFields;

			internal int MoveMethods;

			internal int MoveAccesses;

			internal int MixedMethods;

			internal int MixedAccesses;

			internal int EffectOnlyMethods;

			internal int UiMethods;

			internal int UiAccesses;

			internal int ParamMethods;

			internal int ParamSlots;

			internal int SkippedParamMethods;

			internal int MaxParamSlots;

			internal string MaxParamSlotsAt = "-";

			internal int SaveStreams;

			internal readonly List<string> MoveDetail = new List<string>();

			internal readonly List<string> MixedFound = new List<string>();

			internal readonly List<string> Suspects = new List<string>();
		}

		private static readonly string[] DeclaredPayload = new string[29]
		{
			"Cargo::inc", "StorageComponent/GRID::inc", "StationStore::inc", "DeliveryPackage/GRID::inc", "DispenserStore::inc", "InserterComponent::itemInc", "ShipData::inc", "AssemblerComponent::incServed", "LabComponent::incServed", "FractionatorComponent::fluidInputInc",
			"FractionatorComponent::fluidOutputInc", "TankComponent::fluidInc", "PowerGeneratorComponent::fuelInc", "PowerExchangerComponent::emptyInc", "PowerExchangerComponent::fullInc", "PowerExchangerComponent::poolInc", "TurretComponent::itemInc", "TurretComponent::currentBulletInc", "EjectorComponent::bulletInc", "SiloComponent::bulletInc",
			"Mecha::reactorItemInc", "Mecha::ammoInc", "ItemPackage::inc", "CargoView::inc", "CountInc::inc", "IDCNTINC::inc", "IDCNTMAX::inc", "PilerComponent::cacheCargoInc1", "PilerComponent::cacheCargoInc2"
		};

		internal static readonly string[] MainlinePayload = new string[8] { "Cargo::inc", "StorageComponent/GRID::inc", "StationStore::inc", "AssemblerComponent::incServed", "IDCNTINC::inc", "IDCNTMAX::inc", "PilerComponent::cacheCargoInc1", "PilerComponent::cacheCargoInc2" };

		private static readonly string[] GpuUploaded = new string[3] { "TrashObject::inc", "DroneData::inc", "CourierData::inc" };

		private static readonly string[] NotPayload = new string[13]
		{
			"SpraycoaterComponent::incBeltId", "SpraycoaterComponent::incItemId", "SpraycoaterComponent::incAbility", "SpraycoaterComponent::incSprayTimes", "SpraycoaterComponent::incCount", "SpraycoaterComponent::incCapacity", "PrefabDesc::incCapacity", "PrefabDesc::incItemId", "PrefabDesc::dfTurretAttackDamageInc", "PrefabDesc::dfTurretColdSpeedInc",
			"PrefabDesc::unitColdSpeedInc", "DFGBaseComponent::incomingSkillsCursor", "DefenseSystem::incomingSupernovaTime"
		};

		private static readonly string[] NotifySink = new string[6] { "Player/DItemNotify::Invoke", "Player/DItemNotify::BeginInvoke", "Player::NotifyPackageAddItem", "Player::NotifyDeliveryPackageAddItem", "GameHistoryData::OnPlayerPackageAddItem", "Mecha::OnPlayerPackageAddItem" };

		private static readonly string[] EffectTables = new string[11]
		{
			"incTable", "accTable", "incTableMilli", "accTableMilli", "powerTable", "powerTableRatio", "fastIncArrowTable", "incFastDivisionNumerator", "incFastDivisionDenominator", "kSprayIncMax",
			"kIncLevelMax"
		};

		private static readonly string[] DeclaredMixed = new string[19]
		{
			"AssemblerComponent::InternalUpdate", "LabComponent::InternalUpdateAssemble", "FractionatorComponent::InternalUpdate", "FractionatorComponent::get_extraIncProduceProb", "EjectorComponent::InternalUpdate", "SiloComponent::InternalUpdate", "TurretComponent::LoadAmmo", "PlanetFactory::EntityFastFillIn", "PowerGeneratorComponent::GenEnergyByFuel", "PowerExchangerComponent::CalculateActualEnergyPerTick",
			"SpraycoaterComponent::InternalUpdate", "StorageComponent::TakeTailItemsWithIncTable", "MechaForge::GameTick", "Mecha::GenerateEnergy", "Mecha::LoadAmmo", "Mecha::get_reactorPowerGenRatio", "Mecha::get_reactorPowerGenEnhanced", "Mecha::get_reactorPowerForWeaponEnhanced", "CountInc::get_incArrows"
		};

		internal static void ResolvePayload(ModuleDefinition module, IDictionary<string, FieldDefinition> into, ICollection<string> blockers)
		{
			string[] declaredPayload = DeclaredPayload;
			foreach (string text in declaredPayload)
			{
				string[] parts = text.Split(new string[1] { "::" }, StringSplitOptions.None);
				TypeDefinition type = module.GetType(parts[0]);
				if (type == null)
				{
					blockers.Add("找不到类型 " + parts[0] + "(清单项 " + text + ")");
					continue;
				}
				FieldDefinition val = ((IEnumerable<FieldDefinition>)type.Fields).FirstOrDefault((Func<FieldDefinition, bool>)((FieldDefinition x) => ((MemberReference)x).Name == parts[1] && !x.IsStatic));
				if (val == null)
				{
					blockers.Add("找不到字段 " + text);
				}
				else if (!IsIntegerPayload(((FieldReference)val).FieldType))
				{
					blockers.Add(text + " 的类型是 " + ((MemberReference)((FieldReference)val).FieldType).FullName + ",不是预期的整数或整数数组");
				}
				else
				{
					into[Key((FieldReference)(object)val)] = val;
				}
			}
		}

		internal static Report Analyze(ModuleDefinition module)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			Report report = new Report();
			Dictionary<string, FieldDefinition> dictionary = new Dictionary<string, FieldDefinition>(StringComparer.Ordinal);
			ResolvePayload(module, dictionary, report.Blockers);
			report.PayloadFields = dictionary.Count;
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			FindSuspects(module, dictionary, report);
			CheckGpuUploads(module, dictionary, report);
			HashSet<string> hashSet = new HashSet<string>(DeclaredMixed, StringComparer.Ordinal);
			HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal);
			foreach (TypeDefinition item in AllTypes(module))
			{
				Enumerator<MethodDefinition> enumerator2 = item.Methods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						if (!current2.HasBody)
						{
							continue;
						}
						int num = 0;
						int num2 = 0;
						Enumerator<Instruction> enumerator3 = current2.Body.Instructions.GetEnumerator();
						try
						{
							while (enumerator3.MoveNext())
							{
								object operand = enumerator3.Current.Operand;
								FieldReference val = (FieldReference)((operand is FieldReference) ? operand : null);
								if (val != null)
								{
									if (dictionary.ContainsKey(Key(val)))
									{
										num++;
									}
									if (EffectTables.Contains(((MemberReference)val).Name))
									{
										num2++;
									}
								}
							}
						}
						finally
						{
							((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose();
						}
						string text = ((MemberReference)item).FullName + "::" + ((MemberReference)current2).Name;
						if (num == 0)
						{
							if (num2 > 0)
							{
								report.EffectOnlyMethods++;
							}
							if (hashSet.Contains(text))
							{
								report.Blockers.Add("声明的手工方法 " + text + " 一处载荷字段都不碰——游戏版本可能变了,对照 IL 重新确认后再改 DeclaredMixed");
							}
						}
						else if (IsDisplayOnly(item))
						{
							report.UiMethods++;
							report.UiAccesses += num;
						}
						else if (hashSet.Contains(text))
						{
							hashSet2.Add(text);
							report.MixedMethods++;
							report.MixedAccesses += num;
							report.MixedFound.Add($"{text}  载荷 {num} / 效果表 {num2}");
						}
						else if (num2 > 0)
						{
							report.Blockers.Add($"发现未声明的混合方法 {text}(载荷 {num} / 效果表 {num2})——" + "它同时碰载荷和增产剂效果表,不能当纯搬运自动孪生。先决定它该怎么处理,再加进 DeclaredMixed");
						}
						else
						{
							report.MoveMethods++;
							report.MoveAccesses += num;
							report.MoveDetail.Add($"{text}  {num}");
						}
					}
				}
				finally
				{
					((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
				}
			}
			foreach (string gone in hashSet.Except(hashSet2).OrderBy<string, string>((string x) => x, StringComparer.Ordinal))
			{
				if (!report.Blockers.Any((string b) => b.Contains(gone)))
				{
					report.Blockers.Add("声明的手工方法 " + gone + " 在程序集里找不到——对照 IL 重新确认");
				}
			}
			CountParams(module, dictionary, report);
			CountSaveStreams(module, dictionary, report);
			report.Clean = report.Blockers.Count == 0;
			return report;
		}

		private static void FindSuspects(ModuleDefinition module, IDictionary<string, FieldDefinition> payload, Report r)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			HashSet<string> hashSet = new HashSet<string>(NotPayload, StringComparer.Ordinal);
			string[] gpuUploaded = GpuUploaded;
			foreach (string item in gpuUploaded)
			{
				hashSet.Add(item);
			}
			HashSet<string> hashSet2 = new HashSet<string>(hashSet, StringComparer.Ordinal);
			foreach (TypeDefinition item2 in AllTypes(module))
			{
				if (IsDisplayOnly(item2) || !((IEnumerable<FieldDefinition>)item2.Fields).Any((FieldDefinition f) => !f.IsStatic && LooksLikeCount(f)))
				{
					continue;
				}
				Enumerator<FieldDefinition> enumerator2 = item2.Fields.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						FieldDefinition current2 = enumerator2.Current;
						if (current2.IsStatic || !LooksLikeInc(((MemberReference)current2).Name) || !IsIntegerPayload(((FieldReference)current2).FieldType))
						{
							continue;
						}
						string text = Key((FieldReference)(object)current2);
						if (!payload.ContainsKey(text))
						{
							if (hashSet.Contains(text))
							{
								hashSet2.Remove(text);
								continue;
							}
							r.Suspects.Add(((MemberReference)item2).FullName + "::" + ((MemberReference)current2).Name + " (" + ((MemberReference)((FieldReference)current2).FieldType).Name + ")");
						}
					}
				}
				finally
				{
					((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
				}
			}
			foreach (string item3 in hashSet2.OrderBy<string, string>((string x) => x, StringComparer.Ordinal))
			{
				r.Notes.Add("排除表里的 " + item3 + " 在程序集里不存在了,该清掉这一条");
			}
			r.Notes.Add((r.Suspects.Count == 0) ? $"反查:清单外没有形状像载荷的新字段({hashSet.Count - hashSet2.Count} 个已知非载荷已排除)" : $"反查:{r.Suspects.Count} 个字段形状像载荷、既不在清单也不在排除表里,逐个确认");
			r.Notes.Add($"**已知缺口**:{GpuUploaded.Length} 个载荷字段因为所属结构体要原样喂给 GPU 而暂时没加孪生(" + string.Join("、", GpuUploaded) + ")。TrashObject 无所谓;DroneData / CourierData 是运输机在飞的那趟货,1c 必须解决。");
		}

		private static void CheckGpuUploads(ModuleDefinition module, IDictionary<string, FieldDefinition> payload, Report r)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			HashSet<string> hashSet = new HashSet<string>(new string[1] { "Cargo" }, StringComparer.Ordinal);
			HashSet<string> hashSet2 = new HashSet<string>(payload.Values.Select((FieldDefinition f) => ((MemberReference)f.DeclaringType).FullName), StringComparer.Ordinal);
			HashSet<string> hashSet3 = new HashSet<string>(StringComparer.Ordinal);
			foreach (TypeDefinition item in AllTypes(module))
			{
				Enumerator<MethodDefinition> enumerator2 = item.Methods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						if (!current2.HasBody)
						{
							continue;
						}
						Collection<Instruction> instructions = current2.Body.Instructions;
						for (int num = 0; num < instructions.Count; num++)
						{
							object operand = instructions[num].Operand;
							MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null);
							if (val == null || ((MemberReference)val).Name != "SetData" || ((MemberReference)((MemberReference)val).DeclaringType).Name != "ComputeBuffer")
							{
								continue;
							}
							int num2 = num - 1;
							while (num2 >= 0 && num2 >= num - 8)
							{
								object operand2 = instructions[num2].Operand;
								FieldReference val2 = (FieldReference)((operand2 is FieldReference) ? operand2 : null);
								if (val2 != null)
								{
									TypeReference fieldType = val2.FieldType;
									ArrayType val3 = (ArrayType)(object)((fieldType is ArrayType) ? fieldType : null);
									if (val3 != null)
									{
										string fullName = ((MemberReference)((TypeSpecification)val3).ElementType).FullName;
										if (hashSet2.Contains(fullName) && !hashSet.Contains(fullName))
										{
											hashSet3.Add(fullName + "(" + ((MemberReference)item).FullName + "::" + ((MemberReference)current2).Name + ")");
										}
										break;
									}
								}
								num2--;
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
				}
			}
			foreach (string item2 in hashSet3.OrderBy<string, string>((string x) => x, StringComparer.Ordinal))
			{
				r.Blockers.Add("载荷结构体 " + item2 + " 会被原样上传到 ComputeBuffer——加字段会让它的 stride 和游戏里写死的那个对不上,表现是启动即 ArgumentException,栈里指不到你加的字段。要么把它放进 GpuUploaded 暂时摘掉,要么照 CargoWidening.UploadRepacked 的做法给它加重打包");
			}
			r.Notes.Add((hashSet3.Count == 0) ? "GPU 上传核对:清单里的结构体没有一个被原样喂给 ComputeBuffer" : $"GPU 上传核对:{hashSet3.Count} 个结构体会被喂给 GPU,见 Blockers");
		}

		internal static Dictionary<MethodDefinition, List<int>> SelectTwinParams(ModuleDefinition module, out int skipped)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			HashSet<string> hashSet = new HashSet<string>(NotifySink, StringComparer.Ordinal);
			Dictionary<MethodDefinition, List<int>> dictionary = new Dictionary<MethodDefinition, List<int>>();
			skipped = 0;
			foreach (TypeDefinition item in AllTypes(module))
			{
				if (IsDisplayOnly(item))
				{
					continue;
				}
				Enumerator<MethodDefinition> enumerator2 = item.Methods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						List<int> list = null;
						for (int i = 0; i < ((MethodReference)current2).Parameters.Count; i++)
						{
							ParameterDefinition val = ((MethodReference)current2).Parameters[i];
							if (LooksLikeInc(((ParameterReference)val).Name) && IsIntegerPayload(((ParameterReference)val).ParameterType))
							{
								(list ?? (list = new List<int>())).Add(i);
							}
						}
						if (list != null)
						{
							if (hashSet.Contains(((MemberReference)item).FullName + "::" + ((MemberReference)current2).Name))
							{
								skipped++;
							}
							else
							{
								dictionary[current2] = list;
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
				}
			}
			return dictionary;
		}

		private static void CountParams(ModuleDefinition module, IDictionary<string, FieldDefinition> payload, Report r)
		{
			int skipped;
			Dictionary<MethodDefinition, List<int>> dictionary = SelectTwinParams(module, out skipped);
			r.SkippedParamMethods = skipped;
			r.ParamMethods = dictionary.Count;
			r.ParamSlots = dictionary.Values.Sum((List<int> v) => v.Count);
			foreach (KeyValuePair<MethodDefinition, List<int>> item in dictionary)
			{
				if (item.Value.Count > r.MaxParamSlots)
				{
					r.MaxParamSlots = item.Value.Count;
					r.MaxParamSlotsAt = ((MemberReference)item.Key).FullName;
				}
			}
		}

		private static void CountSaveStreams(ModuleDefinition module, IDictionary<string, FieldDefinition> payload, Report r)
		{
			HashSet<string> hashSet = new HashSet<string>(payload.Values.Select((FieldDefinition f) => ((MemberReference)f.DeclaringType).FullName), StringComparer.Ordinal);
			foreach (TypeDefinition item in AllTypes(module))
			{
				if (hashSet.Contains(((MemberReference)item).FullName))
				{
					bool flag = ((IEnumerable<MethodDefinition>)item.Methods).Any((MethodDefinition m) => ((MemberReference)m).Name == "Export" && m.HasBody);
					bool flag2 = ((IEnumerable<MethodDefinition>)item.Methods).Any((MethodDefinition m) => ((MemberReference)m).Name == "Import" && m.HasBody);
					if (flag && flag2)
					{
						r.SaveStreams++;
					}
					else if (flag || flag2)
					{
						r.Notes.Add(((MemberReference)item).FullName + " 只有 Export / Import 其中一半,存档分支要单独想");
					}
				}
			}
		}

		private static bool IsIntegerPayload(TypeReference t)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			ArrayType val = (ArrayType)(object)((t is ArrayType) ? t : null);
			if (val != null)
			{
				return IsIntegerPayload(((TypeSpecification)val).ElementType);
			}
			ByReferenceType val2 = (ByReferenceType)(object)((t is ByReferenceType) ? t : null);
			if (val2 != null)
			{
				return IsIntegerPayload(((TypeSpecification)val2).ElementType);
			}
			MetadataType metadataType = t.MetadataType;
			if (metadataType - 4 <= 5)
			{
				return true;
			}
			return false;
		}

		private static bool LooksLikeInc(string n)
		{
			if (!(n == "inc") && !(n == "_inc") && !n.EndsWith("Inc", StringComparison.Ordinal))
			{
				return n.StartsWith("inc", StringComparison.Ordinal);
			}
			return true;
		}

		private static bool LooksLikeCount(FieldDefinition f)
		{
			if (!(((MemberReference)f).Name == "count") && !(((MemberReference)f).Name == "stack") && !(((MemberReference)f).Name == "itemCount"))
			{
				return ((MemberReference)f).Name.EndsWith("Count", StringComparison.Ordinal);
			}
			return true;
		}

		private static bool IsDisplayOnly(TypeDefinition t)
		{
			if (!((MemberReference)t).Name.StartsWith("UI", StringComparison.Ordinal))
			{
				return ((MemberReference)t).FullName.StartsWith("UI", StringComparison.Ordinal);
			}
			return true;
		}

		private static string Key(FieldReference f)
		{
			return ((MemberReference)((MemberReference)f).DeclaringType).FullName + "::" + ((MemberReference)f).Name;
		}

		private static IEnumerable<TypeDefinition> AllTypes(ModuleDefinition module)
		{
			return ((IEnumerable<TypeDefinition>)module.Types).SelectMany(WithNested);
		}

		private static IEnumerable<TypeDefinition> WithNested(TypeDefinition t)
		{
			yield return t;
			Enumerator<TypeDefinition> enumerator = t.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					foreach (TypeDefinition item in WithNested(current))
					{
						yield return item;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
		}
	}
	internal static class QualitySaveExtender
	{
		internal class Report
		{
			internal bool Applied;

			internal readonly List<string> Blockers = new List<string>();

			internal readonly List<string> Notes = new List<string>();

			internal int Writes;

			internal int Reads;

			internal readonly Dictionary<string, int> Versions = new Dictionary<string, int>(StringComparer.Ordinal);
		}

		private sealed class Target
		{
			internal string Type;

			internal string Owner;

			internal string Payload;
		}

		private static readonly Target[] Targets = new Target[4]
		{
			new Target
			{
				Type = "CargoContainer",
				Owner = "Cargo",
				Payload = "inc"
			},
			new Target
			{
				Type = "StorageComponent",
				Owner = "StorageComponent/GRID",
				Payload = "inc"
			},
			new Target
			{
				Type = "StationStore",
				Owner = "StationStore",
				Payload = "inc"
			},
			new Target
			{
				Type = "AssemblerComponent",
				Owner = "AssemblerComponent",
				Payload = "incServed"
			}
		};

		internal static Report Apply(ModuleDefinition module)
		{
			Report report = Run(module, mutate: false);
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			return Run(module, mutate: true);
		}

		private static Report Run(ModuleDefinition module, bool mutate)
		{
			Report report = new Report();
			Target[] targets = Targets;
			foreach (Target target in targets)
			{
				TypeDefinition type = module.GetType(target.Owner);
				TypeDefinition type2 = module.GetType(target.Type);
				if (type == null || type2 == null)
				{
					report.Blockers.Add(target.Type + " / " + target.Owner + " 找不到");
					continue;
				}
				string twinName = QualityFieldAdder.TwinName(target.Payload);
				FieldDefinition val = ((IEnumerable<FieldDefinition>)type.Fields).FirstOrDefault((Func<FieldDefinition, bool>)((FieldDefinition f) => ((MemberReference)f).Name == twinName && !f.IsStatic));
				if (val == null)
				{
					report.Blockers.Add(target.Owner + "::" + twinName + " 不存在——1a 没跑或清单对不上");
					continue;
				}
				MethodDefinition val2 = Body(type2, "Export");
				MethodDefinition val3 = Body(type2, "Import");
				if (val2 == null || val3 == null)
				{
					report.Blockers.Add(target.Type + " 缺 Export 或 Import");
					continue;
				}
				int num = BumpVersion(val2, target, report, mutate);
				if (num >= 0)
				{
					report.Versions[target.Type] = num;
					int writes = report.Writes;
					int reads = report.Reads;
					ExtendExport(module, val2, type, val, target, report, mutate);
					ExtendImport(module, val3, type, val, num, target, report, mutate);
					if (report.Writes - writes != report.Reads - reads)
					{
						report.Blockers.Add($"{target.Type}:写 {report.Writes - writes} 处、读 {report.Reads - reads} 处," + "两边对不上——存档流会错位,整刀不做");
					}
				}
			}
			if (report.Blockers.Count > 0)
			{
				return report;
			}
			report.Notes.Add($"品质进存档:{report.Writes} 处写入、{report.Reads} 处按版本分流读入,涉及 " + string.Join("、", report.Versions.Select((KeyValuePair<string, int> kv) => $"{kv.Key}→v{kv.Value}").ToArray()) + "。老存档读不到品质,按 0 处理。");
			report.Applied = true;
			return report;
		}

		private static int BumpVersion(MethodDefinition m, Target t, Report r, bool mutate)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			Collection<Instruction> instructions = m.Body.Instructions;
			for (int i = 0; i + 1 < instructions.Count && i < 12; i++)
			{
				if (IsConstInt(instructions[i], out var v) && IsWriterCall(instructions[i + 1], "Int32"))
				{
					if (mutate)
					{
						instructions[i].OpCode = OpCodes.Ldc_I4;
						instructions[i].Operand = v + 1;
					}
					return v + 1;
				}
			}
			r.Blockers.Add(t.Type + ".Export 开头找不到版本号常量");
			return -1;
		}

		private static void ExtendExport(ModuleDefinition module, MethodDefinition m, TypeDefinition owner, FieldDefinition qua, Target t, Report r, bool mutate)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			MethodBodyRocks.SimplifyMacros(m.Body);
			Collection<Instruction> instructions = m.Body.Instructions;
			List<int> list = new List<int>();
			for (int i = 0; i < instructions.Count; i++)
			{
				if (IsWriterCall(instructions[i], null))
				{
					int[] array = Args((IList<Instruction>)instructions, i, 2);
					if (array != null && Mentions((IList<Instruction>)instructions, array[1], i - 1, owner, t.Payload) && !Has((IList<Instruction>)instructions, array[1], i - 1, OpCodes.Ldlen))
					{
						list.Add(i);
					}
				}
			}
			if (list.Count == 0)
			{
				r.Blockers.Add(t.Type + ".Export 里找不到写 " + t.Payload + " 的地方");
				MethodBodyRocks.OptimizeMacros(m.Body);
				return;
			}
			if (mutate)
			{
				ILProcessor iLProcessor = m.Body.GetILProcessor();
				for (int num = list.Count - 1; num >= 0; num--)
				{
					int num2 = list[num];
					int[] array2 = Args((IList<Instruction>)instructions, num2, 2);
					List<Instruction> list2 = new List<Instruction>();
					for (int j = array2[0]; j < array2[1]; j++)
					{
						list2.Add(Clone(instructions[j]));
					}
					for (int k = array2[1]; k < num2; k++)
					{
						list2.Add(Swap(instructions[k], owner, t.Payload, qua));
					}
					list2.Add(Instruction.Create(OpCodes.Callvirt, Writer(module, "Int32")));
					Instruction val = instructions[num2];
					foreach (Instruction item in list2)
					{
						iLProcessor.InsertAfter(val, item);
						val = item;
					}
				}
			}
			r.Writes += list.Count;
			MethodBodyRocks.OptimizeMacros(m.Body);
		}

		private static void ExtendImport(ModuleDefinition module, MethodDefinition m, TypeDefinition owner, FieldDefinition qua, int version, Target t, Report r, bool mutate)
		{
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
			MethodBodyRocks.SimplifyMacros(m.Body);
			Collection<Instruction> instructions = m.Body.Instructions;
			VariableDefinition val = VersionLocal(m);
			if (val == null)
			{
				r.Blockers.Add(t.Type + ".Import 没有把版本号存进局部,没法做分流");
				MethodBodyRocks.OptimizeMacros(m.Body);
				return;
			}
			ParameterDefinition val2 = ((IEnumerable<ParameterDefinition>)((MethodReference)m).Parameters).FirstOrDefault((Func<ParameterDefinition, bool>)((ParameterDefinition p) => ((MemberReference)((ParameterReference)p).ParameterType).FullName == "System.IO.BinaryReader"));
			if (val2 == null)
			{
				r.Blockers.Add(t.Type + ".Import 的参数里找不到 BinaryReader");
				MethodBodyRocks.OptimizeMacros(m.Body);
				return;
			}
			List<int> list = new List<int>();
			for (int num = 0; num < instructions.Count; num++)
			{
				if (!StoresPayload((IList<Instruction>)instructions, num, owner, t.Payload) || !ReadsStream((IList<Instruction>)instructions, num, owner, t.Payload))
				{
					continue;
				}
				int item = num;
				for (int num2 = num + 1; num2 < instructions.Count && num2 <= num + 12; num2++)
				{
					if (StoresTwin((IList<Instruction>)instructions, num2, qua))
					{
						item = num2;
						break;
					}
				}
				list.Add(item);
			}
			if (list.Count == 0)
			{
				r.Blockers.Add(t.Type + ".Import 里找不到 1c 发射的 " + ((MemberReference)qua).Name + " 置零——1c 没跑?");
				MethodBodyRocks.OptimizeMacros(m.Body);
				return;
			}
			if (mutate)
			{
				ILProcessor iLProcessor = m.Body.GetILProcessor();
				for (int num3 = list.Count - 1; num3 >= 0; num3--)
				{
					int num4 = list[num3];
					OpCode opCode = instructions[num4].OpCode;
					bool flag = ((OpCode)(ref opCode)).Name.StartsWith("stelem", StringComparison.Ordinal);
					int[] array = Args((IList<Instruction>)instructions, num4, flag ? 3 : 2);
					if (array == null)
					{
						r.Blockers.Add(t.Type + ".Import 的 " + ((MemberReference)qua).Name + " 置零处数不出实参边界");
						MethodBodyRocks.OptimizeMacros(m.Body);
						return;
					}
					List<Instruction> list2 = new List<Instruction>();
					for (int num5 = array[0]; num5 < array[^1]; num5++)
					{
						list2.Add(Swap(instructions[num5], owner, t.Payload, qua));
					}
					list2.Add(Instruction.Create(OpCodes.Ldarg, val2));
					list2.Add(In

plugins/Newtonsoft.Json.dll

Decompiled 8 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")]
[assembly: AssemblyFileVersion("12.0.3.23909")]
[assembly: AssemblyInformationalVersion("12.0.3+7c3d7f8da7e35dde8fa74188b0decff70f8f10e3")]
[assembly: AssemblyProduct("Json.NET")]
[assembly: AssemblyTitle("Json.NET .NET Standard 2.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("12.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
}
namespace Newtonsoft.Json
{
	public enum ConstructorHandling
	{
		Default,
		AllowNonPublicDefaultConstructor
	}
	public enum DateFormatHandling
	{
		IsoDateFormat,
		MicrosoftDateFormat
	}
	public enum DateParseHandling
	{
		None,
		DateTime,
		DateTimeOffset
	}
	public enum DateTimeZoneHandling
	{
		Local,
		Utc,
		Unspecified,
		RoundtripKind
	}
	public class DefaultJsonNameTable : JsonNameTable
	{
		private class Entry
		{
			internal readonly string Value;

			internal readonly int HashCode;

			internal Entry Next;

			internal Entry(string value, int hashCode, Entry next)
			{
				Value = value;
				HashCode = hashCode;
				Next = next;
			}
		}

		private static readonly int HashCodeRandomizer;

		private int _count;

		private Entry[] _entries;

		private int _mask = 31;

		static DefaultJsonNameTable()
		{
			HashCodeRandomizer = Environment.TickCount;
		}

		public DefaultJsonNameTable()
		{
			_entries = new Entry[_mask + 1];
		}

		public override string? Get(char[] key, int start, int length)
		{
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			num += (num << 7) ^ key[start];
			int num2 = start + length;
			for (int i = start + 1; i < num2; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			int num3 = num & _mask;
			for (Entry entry = _entries[num3]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && TextEquals(entry.Value, key, start, length))
				{
					return entry.Value;
				}
			}
			return null;
		}

		public string Add(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			int length = key.Length;
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			for (int i = 0; i < key.Length; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal))
				{
					return entry.Value;
				}
			}
			return AddEntry(key, num);
		}

		private string AddEntry(string str, int hashCode)
		{
			int num = hashCode & _mask;
			Entry entry = new Entry(str, hashCode, _entries[num]);
			_entries[num] = entry;
			if (_count++ == _mask)
			{
				Grow();
			}
			return entry.Value;
		}

		private void Grow()
		{
			Entry[] entries = _entries;
			int num = _mask * 2 + 1;
			Entry[] array = new Entry[num + 1];
			for (int i = 0; i < entries.Length; i++)
			{
				Entry entry = entries[i];
				while (entry != null)
				{
					int num2 = entry.HashCode & num;
					Entry next = entry.Next;
					entry.Next = array[num2];
					array[num2] = entry;
					entry = next;
				}
			}
			_entries = array;
			_mask = num;
		}

		private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
		{
			if (str1.Length != str2Length)
			{
				return false;
			}
			for (int i = 0; i < str1.Length; i++)
			{
				if (str1[i] != str2[str2Start + i])
				{
					return false;
				}
			}
			return true;
		}
	}
	[Flags]
	public enum DefaultValueHandling
	{
		Include = 0,
		Ignore = 1,
		Populate = 2,
		IgnoreAndPopulate = 3
	}
	public enum FloatFormatHandling
	{
		String,
		Symbol,
		DefaultValue
	}
	public enum FloatParseHandling
	{
		Double,
		Decimal
	}
	public enum Formatting
	{
		None,
		Indented
	}
	public interface IArrayPool<T>
	{
		T[] Rent(int minimumLength);

		void Return(T[]? array);
	}
	public interface IJsonLineInfo
	{
		int LineNumber { get; }

		int LinePosition { get; }

		bool HasLineInfo();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonArrayAttribute : JsonContainerAttribute
	{
		private bool _allowNullItems;

		public bool AllowNullItems
		{
			get
			{
				return _allowNullItems;
			}
			set
			{
				_allowNullItems = value;
			}
		}

		public JsonArrayAttribute()
		{
		}

		public JsonArrayAttribute(bool allowNullItems)
		{
			_allowNullItems = allowNullItems;
		}

		public JsonArrayAttribute(string id)
			: base(id)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)]
	public sealed class JsonConstructorAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public abstract class JsonContainerAttribute : Attribute
	{
		internal bool? _isReference;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		private Type? _namingStrategyType;

		private object[]? _namingStrategyParameters;

		public string? Id { get; set; }

		public string? Title { get; set; }

		public string? Description { get; set; }

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType
		{
			get
			{
				return _namingStrategyType;
			}
			set
			{
				_namingStrategyType = value;
				NamingStrategyInstance = null;
			}
		}

		public object[]? NamingStrategyParameters
		{
			get
			{
				return _namingStrategyParameters;
			}
			set
			{
				_namingStrategyParameters = value;
				NamingStrategyInstance = null;
			}
		}

		internal NamingStrategy? NamingStrategyInstance { get; set; }

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		protected JsonContainerAttribute()
		{
		}

		protected JsonContainerAttribute(string id)
		{
			Id = id;
		}
	}
	public static class JsonConvert
	{
		public static readonly string True = "true";

		public static readonly string False = "false";

		public static readonly string Null = "null";

		public static readonly string Undefined = "undefined";

		public static readonly string PositiveInfinity = "Infinity";

		public static readonly string NegativeInfinity = "-Infinity";

		public static readonly string NaN = "NaN";

		public static Func<JsonSerializerSettings>? DefaultSettings { get; set; }

		public static string ToString(DateTime value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
		}

		public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
		{
			DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(DateTimeOffset value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat);
		}

		public static string ToString(DateTimeOffset value, DateFormatHandling format)
		{
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(bool value)
		{
			if (!value)
			{
				return False;
			}
			return True;
		}

		public static string ToString(char value)
		{
			return ToString(char.ToString(value));
		}

		public static string ToString(Enum value)
		{
			return value.ToString("D");
		}

		public static string ToString(int value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(short value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ushort value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(uint value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(long value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		private static string ToStringInternal(BigInteger value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ulong value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(float value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value)))
			{
				return text;
			}
			if (floatFormatHandling == FloatFormatHandling.DefaultValue)
			{
				if (nullable)
				{
					return Null;
				}
				return "0.0";
			}
			return quoteChar + text + quoteChar;
		}

		public static string ToString(double value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureDecimalPlace(double value, string text)
		{
			if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		private static string EnsureDecimalPlace(string text)
		{
			if (text.IndexOf('.') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		public static string ToString(byte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(sbyte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(decimal value)
		{
			return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
		}

		public static string ToString(Guid value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(Guid value, char quoteChar)
		{
			string text = value.ToString("D", CultureInfo.InvariantCulture);
			string text2 = quoteChar.ToString(CultureInfo.InvariantCulture);
			return text2 + text + text2;
		}

		public static string ToString(TimeSpan value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(TimeSpan value, char quoteChar)
		{
			return ToString(value.ToString(), quoteChar);
		}

		public static string ToString(Uri? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ToString(value, '"');
		}

		internal static string ToString(Uri value, char quoteChar)
		{
			return ToString(value.OriginalString, quoteChar);
		}

		public static string ToString(string? value)
		{
			return ToString(value, '"');
		}

		public static string ToString(string? value, char delimiter)
		{
			return ToString(value, delimiter, StringEscapeHandling.Default);
		}

		public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling)
		{
			if (delimiter != '"' && delimiter != '\'')
			{
				throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
			}
			return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling);
		}

		public static string ToString(object? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ConvertUtils.GetTypeCode(value.GetType()) switch
			{
				PrimitiveTypeCode.String => ToString((string)value), 
				PrimitiveTypeCode.Char => ToString((char)value), 
				PrimitiveTypeCode.Boolean => ToString((bool)value), 
				PrimitiveTypeCode.SByte => ToString((sbyte)value), 
				PrimitiveTypeCode.Int16 => ToString((short)value), 
				PrimitiveTypeCode.UInt16 => ToString((ushort)value), 
				PrimitiveTypeCode.Int32 => ToString((int)value), 
				PrimitiveTypeCode.Byte => ToString((byte)value), 
				PrimitiveTypeCode.UInt32 => ToString((uint)value), 
				PrimitiveTypeCode.Int64 => ToString((long)value), 
				PrimitiveTypeCode.UInt64 => ToString((ulong)value), 
				PrimitiveTypeCode.Single => ToString((float)value), 
				PrimitiveTypeCode.Double => ToString((double)value), 
				PrimitiveTypeCode.DateTime => ToString((DateTime)value), 
				PrimitiveTypeCode.Decimal => ToString((decimal)value), 
				PrimitiveTypeCode.DBNull => Null, 
				PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), 
				PrimitiveTypeCode.Guid => ToString((Guid)value), 
				PrimitiveTypeCode.Uri => ToString((Uri)value), 
				PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), 
				PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), 
				_ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), 
			};
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value)
		{
			return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting)
		{
			return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, JsonSerializerSettings settings)
		{
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			jsonSerializer.Formatting = formatting;
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
		{
			StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture);
			using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
			{
				jsonTextWriter.Formatting = jsonSerializer.Formatting;
				jsonSerializer.Serialize(jsonTextWriter, value, type);
			}
			return stringWriter.ToString();
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value)
		{
			return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, JsonSerializerSettings settings)
		{
			return DeserializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, Type type)
		{
			return DeserializeObject(value, type, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static T DeserializeObject<T>(string value)
		{
			return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
		{
			return DeserializeObject<T>(value);
		}

		[DebuggerStepThrough]
		public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
		{
			return DeserializeObject<T>(value, settings);
		}

		[DebuggerStepThrough]
		[return: MaybeNull]
		public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
		{
			return (T)DeserializeObject(value, typeof(T), converters);
		}

		[DebuggerStepThrough]
		[return: MaybeNull]
		public static T DeserializeObject<T>(string value, JsonSerializerSettings? settings)
		{
			return (T)DeserializeObject(value, typeof(T), settings);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return DeserializeObject(value, type, settings);
		}

		public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
		{
			ValidationUtils.ArgumentNotNull(value, "value");
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			if (!jsonSerializer.IsCheckAdditionalContentSet())
			{
				jsonSerializer.CheckAdditionalContent = true;
			}
			using JsonTextReader reader = new JsonTextReader(new StringReader(value));
			return jsonSerializer.Deserialize(reader, type);
		}

		[DebuggerStepThrough]
		public static void PopulateObject(string value, object target)
		{
			PopulateObject(value, target, null);
		}

		public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			using JsonReader jsonReader = new JsonTextReader(new StringReader(value));
			jsonSerializer.Populate(jsonReader, target);
			if (settings == null || !settings.CheckAdditionalContent)
			{
				return;
			}
			while (jsonReader.Read())
			{
				if (jsonReader.TokenType != JsonToken.Comment)
				{
					throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
				}
			}
		}

		public static string SerializeXmlNode(XmlNode? node)
		{
			return SerializeXmlNode(node, Formatting.None);
		}

		public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static XmlDocument? DeserializeXmlNode(string value)
		{
			return DeserializeXmlNode(value, null);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter);
		}

		public static string SerializeXNode(XObject? node)
		{
			return SerializeXNode(node, Formatting.None);
		}

		public static string SerializeXNode(XObject? node, Formatting formatting)
		{
			return SerializeXNode(node, formatting, omitRootObject: false);
		}

		public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static XDocument? DeserializeXNode(string value)
		{
			return DeserializeXNode(value, null);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter);
		}
	}
	public abstract class JsonConverter
	{
		public virtual bool CanRead => true;

		public virtual bool CanWrite => true;

		public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer);

		public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer);

		public abstract bool CanConvert(Type objectType);
	}
	public abstract class JsonConverter<T> : JsonConverter
	{
		public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
		{
			if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T))))
			{
				throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			WriteJson(writer, (T)value, serializer);
		}

		public abstract void WriteJson(JsonWriter writer, [AllowNull] T value, JsonSerializer serializer);

		public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
		{
			bool flag = existingValue == null;
			if (!flag && !(existingValue is T))
			{
				throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer);
		}

		public abstract T ReadJson(JsonReader reader, Type objectType, [AllowNull] T existingValue, bool hasExistingValue, JsonSerializer serializer);

		public sealed override bool CanConvert(Type objectType)
		{
			return typeof(T).IsAssignableFrom(objectType);
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonConverterAttribute : Attribute
	{
		private readonly Type _converterType;

		public Type ConverterType => _converterType;

		public object[]? ConverterParameters { get; }

		public JsonConverterAttribute(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			_converterType = converterType;
		}

		public JsonConverterAttribute(Type converterType, params object[] converterParameters)
			: this(converterType)
		{
			ConverterParameters = converterParameters;
		}
	}
	public class JsonConverterCollection : Collection<JsonConverter>
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonDictionaryAttribute : JsonContainerAttribute
	{
		public JsonDictionaryAttribute()
		{
		}

		public JsonDictionaryAttribute(string id)
			: base(id)
		{
		}
	}
	[Serializable]
	public class JsonException : Exception
	{
		public JsonException()
		{
		}

		public JsonException(string message)
			: base(message)
		{
		}

		public JsonException(string message, Exception? innerException)
			: base(message, innerException)
		{
		}

		public JsonException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			return new JsonException(message);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class JsonExtensionDataAttribute : Attribute
	{
		public bool WriteData { get; set; }

		public bool ReadData { get; set; }

		public JsonExtensionDataAttribute()
		{
			WriteData = true;
			ReadData = true;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonIgnoreAttribute : Attribute
	{
	}
	public abstract class JsonNameTable
	{
		public abstract string? Get(char[] key, int start, int length);
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonObjectAttribute : JsonContainerAttribute
	{
		private MemberSerialization _memberSerialization;

		internal MissingMemberHandling? _missingMemberHandling;

		internal Required? _itemRequired;

		internal NullValueHandling? _itemNullValueHandling;

		public MemberSerialization MemberSerialization
		{
			get
			{
				return _memberSerialization;
			}
			set
			{
				_memberSerialization = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public NullValueHandling ItemNullValueHandling
		{
			get
			{
				return _itemNullValueHandling.GetValueOrDefault();
			}
			set
			{
				_itemNullValueHandling = value;
			}
		}

		public Required ItemRequired
		{
			get
			{
				return _itemRequired.GetValueOrDefault();
			}
			set
			{
				_itemRequired = value;
			}
		}

		public JsonObjectAttribute()
		{
		}

		public JsonObjectAttribute(MemberSerialization memberSerialization)
		{
			MemberSerialization = memberSerialization;
		}

		public JsonObjectAttribute(string id)
			: base(id)
		{
		}
	}
	internal enum JsonContainerType
	{
		None,
		Object,
		Array,
		Constructor
	}
	internal struct JsonPosition
	{
		private static readonly char[] SpecialCharacters = new char[18]
		{
			'.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t',
			'\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029'
		};

		internal JsonContainerType Type;

		internal int Position;

		internal string? PropertyName;

		internal bool HasIndex;

		public JsonPosition(JsonContainerType type)
		{
			Type = type;
			HasIndex = TypeHasIndex(type);
			Position = -1;
			PropertyName = null;
		}

		internal int CalculateLength()
		{
			switch (Type)
			{
			case JsonContainerType.Object:
				return PropertyName.Length + 5;
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				return MathUtils.IntLength((ulong)Position) + 2;
			default:
				throw new ArgumentOutOfRangeException("Type");
			}
		}

		internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer)
		{
			switch (Type)
			{
			case JsonContainerType.Object:
			{
				string propertyName = PropertyName;
				if (propertyName.IndexOfAny(SpecialCharacters) != -1)
				{
					sb.Append("['");
					if (writer == null)
					{
						writer = new StringWriter(sb);
					}
					JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
					sb.Append("']");
				}
				else
				{
					if (sb.Length > 0)
					{
						sb.Append('.');
					}
					sb.Append(propertyName);
				}
				break;
			}
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				sb.Append('[');
				sb.Append(Position);
				sb.Append(']');
				break;
			}
		}

		internal static bool TypeHasIndex(JsonContainerType type)
		{
			if (type != JsonContainerType.Array)
			{
				return type == JsonContainerType.Constructor;
			}
			return true;
		}

		internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition)
		{
			int num = 0;
			if (positions != null)
			{
				for (int i = 0; i < positions.Count; i++)
				{
					num += positions[i].CalculateLength();
				}
			}
			if (currentPosition.HasValue)
			{
				num += currentPosition.GetValueOrDefault().CalculateLength();
			}
			StringBuilder stringBuilder = new StringBuilder(num);
			StringWriter writer = null;
			char[] buffer = null;
			if (positions != null)
			{
				foreach (JsonPosition position in positions)
				{
					position.WriteTo(stringBuilder, ref writer, ref buffer);
				}
			}
			currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer);
			return stringBuilder.ToString();
		}

		internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message)
		{
			if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
			{
				message = message.Trim();
				if (!StringUtils.EndsWith(message, '.'))
				{
					message += ".";
				}
				message += " ";
			}
			message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
			}
			message += ".";
			return message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonPropertyAttribute : Attribute
	{
		internal NullValueHandling? _nullValueHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal bool? _isReference;

		internal int? _order;

		internal Required? _required;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType { get; set; }

		public object[]? NamingStrategyParameters { get; set; }

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public int Order
		{
			get
			{
				return _order.GetValueOrDefault();
			}
			set
			{
				_order = value;
			}
		}

		public Required Required
		{
			get
			{
				return _required.GetValueOrDefault();
			}
			set
			{
				_required = value;
			}
		}

		public string? PropertyName { get; set; }

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public JsonPropertyAttribute()
		{
		}

		public JsonPropertyAttribute(string propertyName)
		{
			PropertyName = propertyName;
		}
	}
	public abstract class JsonReader : IDisposable
	{
		protected internal enum State
		{
			Start,
			Complete,
			Property,
			ObjectStart,
			Object,
			ArrayStart,
			Array,
			Closed,
			PostValue,
			ConstructorStart,
			Constructor,
			Error,
			Finished
		}

		private JsonToken _tokenType;

		private object? _value;

		internal char _quoteChar;

		internal State _currentState;

		private JsonPosition _currentPosition;

		private CultureInfo? _culture;

		private DateTimeZoneHandling _dateTimeZoneHandling;

		private int? _maxDepth;

		private bool _hasExceededMaxDepth;

		internal DateParseHandling _dateParseHandling;

		internal FloatParseHandling _floatParseHandling;

		private string? _dateFormatString;

		private List<JsonPosition>? _stack;

		protected State CurrentState => _currentState;

		public bool CloseInput { get; set; }

		public bool SupportMultipleContent { get; set; }

		public virtual char QuoteChar
		{
			get
			{
				return _quoteChar;
			}
			protected internal set
			{
				_quoteChar = value;
			}
		}

		public DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling;
			}
			set
			{
				if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateTimeZoneHandling = value;
			}
		}

		public DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling;
			}
			set
			{
				if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateParseHandling = value;
			}
		}

		public FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling;
			}
			set
			{
				if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_floatParseHandling = value;
			}
		}

		public string? DateFormatString
		{
			get
			{
				return _dateFormatString;
			}
			set
			{
				_dateFormatString = value;
			}
		}

		public int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
			}
		}

		public virtual JsonToken TokenType => _tokenType;

		public virtual object? Value => _value;

		public virtual Type? ValueType => _value?.GetType();

		public virtual int Depth
		{
			get
			{
				int num = _stack?.Count ?? 0;
				if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
				{
					return num;
				}
				return num + 1;
			}
		}

		public virtual string Path
		{
			get
			{
				if (_currentPosition.Type == JsonContainerType.None)
				{
					return string.Empty;
				}
				JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null);
				return JsonPosition.BuildPath(_stack, currentPosition);
			}
		}

		public CultureInfo Culture
		{
			get
			{
				return _culture ?? CultureInfo.InvariantCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync();
		}

		public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TokenType == JsonToken.PropertyName)
			{
				await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth)
				{
				}
			}
		}

		internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken)
		{
			if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
			{
				throw CreateUnexpectedEndException();
			}
		}

		public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean());
		}

		public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes());
		}

		internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
		{
			List<byte> buffer = new List<byte>();
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(buffer));
			byte[] array = buffer.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime());
		}

		public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset());
		}

		public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal());
		}

		public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return Task.FromResult(ReadAsDouble());
		}

		public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32());
		}

		public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString());
		}

		internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken)
		{
			bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (flag)
			{
				flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			return flag;
		}

		internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType = TokenType;
			if (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				return MoveToContentFromNonContentAsync(cancellationToken);
			}
			return AsyncUtils.True;
		}

		private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType;
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					return false;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment);
			return true;
		}

		internal JsonPosition GetPosition(int depth)
		{
			if (_stack != null && depth < _stack.Count)
			{
				return _stack[depth];
			}
			return _currentPosition;
		}

		protected JsonReader()
		{
			_currentState = State.Start;
			_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
			_dateParseHandling = DateParseHandling.DateTime;
			_floatParseHandling = FloatParseHandling.Double;
			CloseInput = true;
		}

		private void Push(JsonContainerType value)
		{
			UpdateScopeWithFinishedValue();
			if (_currentPosition.Type == JsonContainerType.None)
			{
				_currentPosition = new JsonPosition(value);
				return;
			}
			if (_stack == null)
			{
				_stack = new List<JsonPosition>();
			}
			_stack.Add(_currentPosition);
			_currentPosition = new JsonPosition(value);
			if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth)
			{
				return;
			}
			_hasExceededMaxDepth = true;
			throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
		}

		private JsonContainerType Pop()
		{
			JsonPosition currentPosition;
			if (_stack != null && _stack.Count > 0)
			{
				currentPosition = _currentPosition;
				_currentPosition = _stack[_stack.Count - 1];
				_stack.RemoveAt(_stack.Count - 1);
			}
			else
			{
				currentPosition = _currentPosition;
				_currentPosition = default(JsonPosition);
			}
			if (_maxDepth.HasValue && Depth <= _maxDepth)
			{
				_hasExceededMaxDepth = false;
			}
			return currentPosition.Type;
		}

		private JsonContainerType Peek()
		{
			return _currentPosition.Type;
		}

		public abstract bool Read();

		public virtual int? ReadAsInt32()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is int)
				{
					return (int)value;
				}
				int num;
				if (value is BigInteger bigInteger)
				{
					num = (int)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToInt32(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Integer, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadInt32String(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal int? ReadInt32String(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (int.TryParse(s, NumberStyles.Integer, Culture, out var result))
			{
				SetToken(JsonToken.Integer, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual string? ReadAsString()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.String:
				return (string)Value;
			default:
				if (JsonTokenUtils.IsPrimitiveToken(contentToken))
				{
					object value = Value;
					if (value != null)
					{
						string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture));
						SetToken(JsonToken.String, text, updateIndex: false);
						return text;
					}
				}
				throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		public virtual byte[]? ReadAsBytes()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.StartObject:
			{
				ReadIntoWrappedTypeObject();
				byte[] array2 = ReadAsBytes();
				ReaderReadAndAssert();
				if (TokenType != JsonToken.EndObject)
				{
					throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
				}
				SetToken(JsonToken.Bytes, array2, updateIndex: false);
				return array2;
			}
			case JsonToken.String:
			{
				string text = (string)Value;
				Guid g;
				byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray()));
				SetToken(JsonToken.Bytes, array3, updateIndex: false);
				return array3;
			}
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Bytes:
				if (Value is Guid guid)
				{
					byte[] array = guid.ToByteArray();
					SetToken(JsonToken.Bytes, array, updateIndex: false);
					return array;
				}
				return (byte[])Value;
			case JsonToken.StartArray:
				return ReadArrayIntoByteArray();
			default:
				throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal byte[] ReadArrayIntoByteArray()
		{
			List<byte> list = new List<byte>();
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(list));
			byte[] array = list.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
		{
			switch (TokenType)
			{
			case JsonToken.None:
				throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
			case JsonToken.Integer:
				buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
				return false;
			case JsonToken.EndArray:
				return true;
			case JsonToken.Comment:
				return false;
			default:
				throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		public virtual double? ReadAsDouble()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is double)
				{
					return (double)value;
				}
				double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger));
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDoubleString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal double? ReadDoubleString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual bool? ReadAsBoolean()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L));
				SetToken(JsonToken.Boolean, flag, updateIndex: false);
				return flag;
			}
			case JsonToken.String:
				return ReadBooleanString((string)Value);
			case JsonToken.Boolean:
				return (bool)Value;
			default:
				throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal bool? ReadBooleanString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (bool.TryParse(s, out var result))
			{
				SetToken(JsonToken.Boolean, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual decimal? ReadAsDecimal()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is decimal)
				{
					return (decimal)value;
				}
				decimal num;
				if (value is BigInteger bigInteger)
				{
					num = (decimal)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDecimalString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal decimal? ReadDecimalString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success)
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTime? ReadAsDateTime()
		{
			switch (GetContentToken())
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTimeOffset dateTimeOffset)
				{
					SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false);
				}
				return (DateTime)Value;
			case JsonToken.String:
				return ReadDateTimeString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		internal DateTime? ReadDateTimeString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTimeOffset? ReadAsDateTimeOffset()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTime dateTime)
				{
					SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false);
				}
				return (DateTimeOffset)Value;
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadDateTimeOffsetString(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal DateTimeOffset? ReadDateTimeOffsetString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		internal void ReaderReadAndAssert()
		{
			if (!Read())
			{
				throw CreateUnexpectedEndException();
			}
		}

		internal JsonReaderException CreateUnexpectedEndException()
		{
			return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
		}

		internal void ReadIntoWrappedTypeObject()
		{
			ReaderReadAndAssert();
			if (Value != null && Value.ToString() == "$type")
			{
				ReaderReadAndAssert();
				if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
				{
					ReaderReadAndAssert();
					if (Value.ToString() == "$value")
					{
						return;
					}
				}
			}
			throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
		}

		public void Skip()
		{
			if (TokenType == JsonToken.PropertyName)
			{
				Read();
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (Read() && depth < Depth)
				{
				}
			}
		}

		protected void SetToken(JsonToken newToken)
		{
			SetToken(newToken, null, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value)
		{
			SetToken(newToken, value, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value, bool updateIndex)
		{
			_tokenType = newToken;
			_value = value;
			switch (newToken)
			{
			case JsonToken.StartObject:
				_currentState = State.ObjectStart;
				Push(JsonContainerType.Object);
				break;
			case JsonToken.StartArray:
				_currentState = State.ArrayStart;
				Push(JsonContainerType.Array);
				break;
			case JsonToken.StartConstructor:
				_currentState = State.ConstructorStart;
				Push(JsonContainerType.Constructor);
				break;
			case JsonToken.EndObject:
				ValidateEnd(JsonToken.EndObject);
				break;
			case JsonToken.EndArray:
				ValidateEnd(JsonToken.EndArray);
				break;
			case JsonToken.EndConstructor:
				ValidateEnd(JsonToken.EndConstructor);
				break;
			case JsonToken.PropertyName:
				_currentState = State.Property;
				_currentPosition.PropertyName = (string)value;
				break;
			case JsonToken.Raw:
			case JsonToken.Integer:
			case JsonToken.Float:
			case JsonToken.String:
			case JsonToken.Boolean:
			case JsonToken.Null:
			case JsonToken.Undefined:
			case JsonToken.Date:
			case JsonToken.Bytes:
				SetPostValueState(updateIndex);
				break;
			case JsonToken.Comment:
				break;
			}
		}

		internal void SetPostValueState(bool updateIndex)
		{
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
			if (updateIndex)
			{
				UpdateScopeWithFinishedValue();
			}
		}

		private void UpdateScopeWithFinishedValue()
		{
			if (_currentPosition.HasIndex)
			{
				_currentPosition.Position++;
			}
		}

		private void ValidateEnd(JsonToken endToken)
		{
			JsonContainerType jsonContainerType = Pop();
			if (GetTypeForCloseToken(endToken) != jsonContainerType)
			{
				throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType));
			}
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
		}

		protected void SetStateBasedOnCurrent()
		{
			JsonContainerType jsonContainerType = Peek();
			switch (jsonContainerType)
			{
			case JsonContainerType.Object:
				_currentState = State.Object;
				break;
			case JsonContainerType.Array:
				_currentState = State.Array;
				break;
			case JsonContainerType.Constructor:
				_currentState = State.Constructor;
				break;
			case JsonContainerType.None:
				SetFinished();
				break;
			default:
				throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType));
			}
		}

		private void SetFinished()
		{
			_currentState = ((!SupportMultipleContent) ? State.Finished : State.Start);
		}

		private JsonContainerType GetTypeForCloseToken(JsonToken token)
		{
			return token switch
			{
				JsonToken.EndObject => JsonContainerType.Object, 
				JsonToken.EndArray => JsonContainerType.Array, 
				JsonToken.EndConstructor => JsonContainerType.Constructor, 
				_ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), 
			};
		}

		void IDisposable.Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (_currentState != State.Closed && disposing)
			{
				Close();
			}
		}

		public virtual void Close()
		{
			_currentState = State.Closed;
			_tokenType = JsonToken.None;
			_value = null;
		}

		internal void ReadAndAssert()
		{
			if (!Read())
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter)
		{
			if (!ReadForType(contract, hasConverter))
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal bool ReadForType(JsonContract? contract, bool hasConverter)
		{
			if (hasConverter)
			{
				return Read();
			}
			switch (contract?.InternalReadType ?? ReadType.Read)
			{
			case ReadType.Read:
				return ReadAndMoveToContent();
			case ReadType.ReadAsInt32:
				ReadAsInt32();
				break;
			case ReadType.ReadAsInt64:
			{
				bool result = ReadAndMoveToContent();
				if (TokenType == JsonToken.Undefined)
				{
					throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
				}
				return result;
			}
			case ReadType.ReadAsDecimal:
				ReadAsDecimal();
				break;
			case ReadType.ReadAsDouble:
				ReadAsDouble();
				break;
			case ReadType.ReadAsBytes:
				ReadAsBytes();
				break;
			case ReadType.ReadAsBoolean:
				ReadAsBoolean();
				break;
			case ReadType.ReadAsString:
				ReadAsString();
				break;
			case ReadType.ReadAsDateTime:
				ReadAsDateTime();
				break;
			case ReadType.ReadAsDateTimeOffset:
				ReadAsDateTimeOffset();
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			return TokenType != JsonToken.None;
		}

		internal bool ReadAndMoveToContent()
		{
			if (Read())
			{
				return MoveToContent();
			}
			return false;
		}

		internal bool MoveToContent()
		{
			JsonToken tokenType = TokenType;
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				if (!Read())
				{
					return false;
				}
				tokenType = TokenType;
			}
			return true;
		}

		private JsonToken GetContentToken()
		{
			JsonToken tokenType;
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
					return JsonToken.None;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.Comment);
			return tokenType;
		}
	}
	[Serializable]
	public class JsonReaderException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonReaderException()
		{
		}

		public JsonReaderException(string message)
			: base(message)
		{
		}

		public JsonReaderException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonReaderException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonReaderException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonReaderException(message, path, lineNumber, linePosition, ex);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonRequiredAttribute : Attribute
	{
	}
	[Serializable]
	public class JsonSerializationException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonSerializationException()
		{
		}

		public JsonSerializationException(string message)
			: base(message)
		{
		}

		public JsonSerializationException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonSerializationException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonSerializationException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonSerializationException(message, path, lineNumber, linePosition, ex);
		}
	}
	public class JsonSerializer
	{
		internal TypeNameHandling _typeNameHandling;

		internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling;

		internal PreserveReferencesHandling _preserveReferencesHandling;

		internal ReferenceLoopHandling _referenceLoopHandling;

		internal MissingMemberHandling _missingMemberHandling;

		internal ObjectCreationHandling _objectCreationHandling;

		internal NullValueHandling _nullValueHandling;

		internal DefaultValueHandling _defaultValueHandling;

		internal ConstructorHandling _constructorHandling;

		internal MetadataPropertyHandling _metadataPropertyHandling;

		internal JsonConverterCollection? _converters;

		internal IContractResolver _contractResolver;

		internal ITraceWriter? _traceWriter;

		internal IEqualityComparer? _equalityComparer;

		internal ISerializationBinder _serializationBinder;

		internal StreamingContext _context;

		private IReferenceResolver? _referenceResolver;

		private Formatting? _formatting;

		private DateFormatHandling? _dateFormatHandling;

		private DateTimeZoneHandling? _dateTimeZoneHandling;

		private DateParseHandling? _dateParseHandling;

		private FloatFormatHandling? _floatFormatHandling;

		private FloatParseHandling? _floatParseHandling;

		private StringEscapeHandling? _stringEscapeHandling;

		private CultureInfo _culture;

		private int? _maxDepth;

		private bool _maxDepthSet;

		private bool? _checkAdditionalContent;

		private string? _dateFormatString;

		private bool _dateFormatStringSet;

		public virtual IReferenceResolver? ReferenceResolver
		{
			get
			{
				return GetReferenceResolver();
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Reference resolver cannot be null.");
				}
				_referenceResolver = value;
			}
		}

		[Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
		public virtual SerializationBinder Binder
		{
			get
			{
				if (_serializationBinder is SerializationBinder result)
				{
					return result;
				}
				if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter)
				{
					return serializationBinderAdapter.SerializationBinder;
				}
				throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set.");
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value);
			}
		}

		public virtual ISerializationBinder SerializationBinder
		{
			get
			{
				return _serializationBinder;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = value;
			}
		}

		public virtual ITraceWriter? TraceWriter
		{
			get
			{
				return _traceWriter;
			}
			set
			{
				_traceWriter = value;
			}
		}

		public virtual IEqualityComparer? EqualityComparer
		{
			get
			{
				return _equalityComparer;
			}
			set
			{
				_equalityComparer = value;
			}
		}

		public virtual TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling;
			}
			set
			{
				if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameHandling = value;
			}
		}

		[Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
		public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
		{
			get
			{
				return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
			}
		}

		public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
		{
			get
			{
				return _typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = value;
			}
		}

		public virtual PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling;
			}
			set
			{
				if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_preserveReferencesHandling = value;
			}
		}

		public virtual ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling;
			}
			set
			{
				if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_referenceLoopHandling = value;
			}
		}

		public virtual MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling;
			}
			set
			{
				if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_missingMemberHandling = value;
			}
		}

		public virtual NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling;
			}
			set
			{
				if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_nullValueHandling = value;
			}
		}

		public virtual DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling;
			}
			set
			{
				if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_defaultValueHandling = value;
			}
		}

		public virtual ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling;
			}
			set
			{
				if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_objectCreationHandling = value;
			}
		}

		public virtual ConstructorHandling ConstructorHandling
		{
			get
			{
				return _constructorHandling;
			}
			set
			{
				if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_constructorHandling = value;
			}
		}

		public virtual MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling;
			}
			set
			{
				if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_metadataPropertyHandling = value;
			}
		}

		public virtual JsonConverterCollection Converters
		{
			get
			{
				if (_converters == null)
				{
					_converters = new JsonConverterCollection();
				}
				return _converters;
			}
		}

		public virtual IContractResolver ContractResolver
		{
			get
			{
				return _contractResolver;
			}
			set
			{
				_contractResolver = value ?? DefaultContractResolver.Instance;
			}
		}

		public virtual StreamingContext Context
		{
			get
			{
				return _context;
			}
			set
			{
				_context = value;
			}
		}

		public virtual Formatting Formatting
		{
			get
			{
				return _formatting.GetValueOrDefault();
			}
			set
			{
				_formatting = value;
			}
		}

		public virtual DateFormatHandling DateFormatHandling
		{
			get
			{
				return _dateFormatHandling.GetValueOrDefault();
			}
			set
			{
				_dateFormatHandling = value;
			}
		}

		public virtual DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind;
			}
			set
			{
				_dateTimeZoneHandling = value;
			}
		}

		public virtual DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling ?? DateParseHandling.DateTime;
			}
			set
			{
				_dateParseHandling = value;
			}
		}

		public virtual FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling.GetValueOrDefault();
			}
			set
			{
				_floatParseHandling = value;
			}
		}

		public virtual FloatFormatHandling FloatFormatHandling
		{
			get
			{
				return _floatFormatHandling.GetValueOrDefault();
			}
			set
			{
				_floatFormatHandling = value;
			}
		}

		public virtual StringEscapeHandling StringEscapeHandling
		{
			get
			{
				return _stringEscapeHandling.GetValueOrDefault();
			}
			set
			{
				_stringEscapeHandling = value;
			}
		}

		public virtual string DateFormatString
		{
			get
			{
				return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
			}
			set
			{
				_dateFormatString = value;
				_dateFormatStringSet = true;
			}
		}

		public virtual CultureInfo Culture
		{
			get
			{
				return _culture ?? JsonSerializerSettings.DefaultCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
				_maxDepthSet = true;
			}
		}

		public virtual bool CheckAdditionalContent
		{
			get
			{
				return _checkAdditionalContent.GetValueOrDefault();
			}
			set
			{
				_checkAdditionalContent = value;
			}
		}

		public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error;

		internal bool IsCheckAdditionalContentSet()
		{
			return _checkAdditionalContent.HasValue;
		}

		public JsonSerializer()
		{
			_referenceLoopHandling = ReferenceLoopHandling.Error;
			_missingMemberHandling = MissingMemberHandling.Ignore;
			_nullValueHandling = NullValueHandling.Include;
			_defaultValueHandling = DefaultValueHandling.Include;
			_objectCreationHandling = ObjectCreationHandling.Auto;
			_preserveReferencesHandling = PreserveReferencesHandling.None;
			_constructorHandling = ConstructorHandling.Default;
			_typeNameHandling = TypeNameHandling.None;
			_metadataPropertyHandling = MetadataPropertyHandling.Default;
			_context = JsonSerializerSettings.DefaultContext;
			_serializationBinder = DefaultSerializationBinder.Instance;
			_culture = JsonSerializerSettings.DefaultCulture;
			_contractResolver = DefaultContractResolver.Instance;
		}

		public static JsonSerializer Create()
		{
			return new JsonSerializer();
		}

		public static JsonSerializer Create(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = Create();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		public static JsonSerializer CreateDefault()
		{
			return Create(JsonConvert.DefaultSettings?.Invoke());
		}

		public static JsonSerializer CreateDefault(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = CreateDefault();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings)
		{
			if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
			{
				for (int i = 0; i < settings.Converters.Count; i++)
				{
					serializer.Converters.Insert(i, settings.Converters[i]);
				}
			}
			if (settings._typeNameHandling.HasValue)
			{
				serializer.TypeNameHandling = settings.TypeNameHandling;
			}
			if (settings._metadataPropertyHandling.HasValue)
			{
				serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling;
			}
			if (settings._typeNameAssemblyFormatHandling.HasValue)
			{
				serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling;
			}
			if (settings._preserveReferencesHandling.HasValue)
			{
				serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
			}
			if (settings._referenceLoopHandling.HasValue)
			{
				serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
			}
			if (settings._missingMemberHandling.HasValue)
			{
				serializer.MissingMemberHandling = settings.MissingMemberHandling;
			}
			if (settings._objectCreationHandling.HasValue)
			{
				serializer.ObjectCreationHandling = settings.ObjectCreationHandling;
			}
			if (settings._nullValueHandling.HasValue)
			{
				serializer.NullValueHandling = settings.NullValueHandling;
			}
			if (settings._defaultValueHandling.HasValue)
			{
				serializer.DefaultValueHandling = settings.DefaultValueHandling;
			}
			if (settings._constructorHandling.HasValue)
			{
				serializer.ConstructorHandling = settings.ConstructorHandling;
			}
			if (settings._context.HasValue)
			{
				serializer.Context = settings.Context;
			}
			if (settings._checkAdditionalContent.HasValue)
			{
				serializer._checkAdditionalContent = settings._checkAdditionalContent;
			}
			if (settings.Error != null)
			{
				serializer.Error += settings.Error;
			}
			if (settings.ContractResolver != null)
			{
				serializer.ContractResolver = settings.ContractResolver;
			}
			if (settings.ReferenceResolverProvider != null)
			{
				serializer.ReferenceResolver = settings.ReferenceResolverProvider();
			}
			if (settings.TraceWriter != null)
			{
				serializer.TraceWriter = settings.TraceWriter;
			}
			if (settings.EqualityComparer != null)
			{
				serializer.EqualityComparer = settings.EqualityComparer;
			}
			if (settings.SerializationBinder != null)
			{
				serializer.SerializationBinder = settings.SerializationBinder;
			}
			if (settings._formatting.HasValue)
			{
				serializer._formatting = settings._formatting;
			}
			if (settings._dateFormatHandling.HasValue)
			{
				serializer._dateFormatHandling = settings._dateFormatHandling;
			}
			if (settings._dateTimeZoneHandling.HasValue)
			{
				serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling;
			}
			if (settings._dateParseHandling.HasValue)
			{
				serializer._dateParseHandling = settings._dateParseHandling;
			}
			if (settings._dateFormatStringSet)
			{
				serializer._dateFormatString = settings._dateFormatString;
				serializer._dateFormatStringSet = settings._dateFormatStringSet;
			}
			if (settings._floatFormatHandling.HasValue)
			{
				serializer._floatFormatHandling = settings._floatFormatHandling;
			}
			if (settings._floatParseHandling.HasValue)
			{
				serializer._floatParseHandling = settings._floatParseHandling;
			}
			if (settings._stringEscapeHandling.HasValue)
			{
				serializer._stringEscapeHandling = settings._stringEscapeHandling;
			}
			if (settings._culture != null)
			{
				serializer._culture = settings._culture;
			}
			if (settings._maxDepthSet)
			{
				serializer._maxDepth = settings._maxDepth;
				serializer._maxDepthSet = settings._maxDepthSet;
			}
		}

		[DebuggerStepThrough]
		public void Populate(TextReader reader, object target)
		{
			Populate(new JsonTextReader(reader), target);
		}

		[DebuggerStepThrough]
		public void Populate(JsonReader reader, object target)
		{
			PopulateInternal(reader, target);
		}

		internal virtual void PopulateInternal(JsonReader reader, object target)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			ValidationUtils.ArgumentNotNull(target, "target");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader)
		{
			return Deserialize(reader, null);
		}

		[DebuggerStepThrough]
		public object? Deserialize(TextReader reader, Type objectType)
		{
			return Deserialize(new JsonTextReader(reader), objectType);
		}

		[DebuggerStepThrough]
		[return: MaybeNull]
		public T Deserialize<T>(JsonReader reader)
		{
			return (T)Deserialize(reader, typeof(T));
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader, Type? objectType)
		{
			return DeserializeInternal(reader, objectType);
		}

		internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
			return result;
		}

		private void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString)
		{
			if (_culture != null && !_culture.Equals(reader.Culture))
			{
				previousCulture = reader.Culture;
				reader.Culture = _culture;
			}
			else
			{
				previousCulture = null;
			}
			if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
			{
				previousDateTimeZoneHandling = reader.DateTimeZoneHandling;
				reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
			}
			else
			{
				previousDateTimeZoneHandling = null;
			}
			if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling)
			{
				previousDateParseHandling = reader.DateParseHandling;
				reader.DateParseHandling = _dateParseHandling.GetValueOrDefault();
			}
			else
			{
				previousDateParseHandling = null;
			}
			if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling)
			{
				previousFloatParseHandling = reader.FloatParseHandling;
				reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault();
			}
			else
			{
				previousFloatParseHandling = null;
			}
			if (_maxDepthSet && reader.MaxDepth != _maxDepth)
			{
				previousMaxDepth = reader.MaxDepth;
				reader.MaxDepth = _maxDepth;
			}
			else
			{
				previousMaxDepth = null;
			}
			if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString)
			{
				previousDateFormatString = reader.DateFormatString;
				reader.DateFormatString = _dateFormatString;
			}
			else
			{
				previousDateFormatString = null;
			}
			if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver)
			{
				jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable();
			}
		}

		private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString)
		{
			if (previousCulture != null)
			{
				reader.Culture = previousCulture;
			}
			if (previousDateTimeZoneHandling.HasValue)
			{
				reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault();
			}
			if (previousDateParseHandling.HasValue)
			{
				reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault();
			}
			if (previousFloatParseHandling.HasValue)
			{
				reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault();
			}
			if (_maxDepthSet)
			{
				reader.MaxDepth = previousMaxDepth;
			}
			if (_dateFormatStringSet)
			{
				reader.DateFormatString = previousDateFormatString;
			}
			if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable())
			{
				jsonTextReader.PropertyNameTable = null;
			}
		}

		public void Serialize(TextWriter textWriter, object? value)
		{
			Serialize(new JsonTextWriter(textWriter), value);
		}

		public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType)
		{
			SerializeInternal(jsonWriter, value, objectType);
		}

		public void Serialize(TextWriter textWriter, object? value, Type objectType)
		{
			Serialize(new JsonTextWriter(textWriter), value, objectType);
		}

		public void Serialize(JsonWriter jsonWriter, object? value)
		{
			SerializeInternal(jsonWriter, value, null);
		}

		private TraceJsonReader CreateTraceJsonReader(JsonReader reader)
		{
			TraceJsonReader traceJsonReader = new TraceJsonReader(reader);
			if (reader.TokenType != 0)
			{
				traceJsonReader.WriteCurrentToken();
			}
			return traceJsonReader;
		}

		internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
			Formatting? formatting = null;
			if (_formatting.HasValue && jsonWriter.Formatting != _formatting)
			{
				formatting = jsonWriter.Formatting;
				jsonWriter.Formatting = _formatting.GetValueOrDefault();
			}
			DateFormatHandling? dateFormatHandling = null;
			if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling)
			{
				dateFormatHandling = jsonWriter.DateFormatHandling;
				jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault();
			}
			DateTimeZoneHandling? dateTimeZoneHandling = null;
			if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling)
			{
				dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling;
				jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
			}
			FloatFormatHandling? floatFormatHandling = null;
			if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling)
			{
				floatFormatHandling = jsonWriter.FloatFormatHandling;
				jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault();
			}
			StringEscapeHandling? stringEscapeHandling = null;
			if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling)
			{
				stringEscapeHandling = jsonWriter.StringEscapeHandling;
				jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault();
			}
			CultureInfo cultureInfo = null;
			if (_culture != null && !_culture.Equals(jsonWriter.Culture))
			{
				cultureInfo = jsonWriter.Culture;
				jsonWriter.Culture = _culture;
			}
			string dateFormatString = null;
			if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString)
			{
				dateFormatString = jsonWriter.DateFormatString;
				jsonWriter.DateFormatString = _dateFormatString;
			}
			TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null);
			new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType);
			if (traceJsonWriter != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null);
			}
			if (formatting.HasValue)
			{
				jsonWriter.Formatting = formatting.GetValueOrDefault();
			}
			if (dateFormatHandling.HasValue)
			{
				jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault();
			}
			if (dateTimeZoneHandling.HasValue)
			{
				jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault();
			}
			if (floatFormatHandling.HasValue)
			{
				jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault();
			}
			if (stringEscapeHandling.HasValue)
			{
				jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault();
			}
			if (_dateFormatStringSet)
			{
				jsonWriter.DateFormatString = dateFormatString;
			}
			if (cultureInfo != null)
			{
				jsonWriter.Culture = cultureInfo;
			}
		}

		internal IReferenceResolver GetReferenceResolver()
		{
			if (_referenceResolver == null)
			{
				_referenceResolver = new DefaultReferenceResolver();
			}
			return _referenceResolver;
		}

		internal JsonConverter? GetMatchingConverter(Type type)
		{
			return GetMatchingConverter(_converters, type);
		}

		internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType)
		{
			if (converters != null)
			{
				for (int i = 0; i < converters.Count; i++)
				{
					JsonConverter jsonConverter = converters[i];
					if (jsonConverter.CanConvert(objectType))
					{
						return jsonConverter;
					}
				}
			}
			return null;
		}

		internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e)
		{
			this.Error?.Invoke(this, e);
		}
	}
	public class JsonSerializerSettings
	{
		internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error;

		internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore;

		internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include;

		internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include;

		internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto;

		internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None;

		internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default;

		internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None;

		internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default;

		internal static readonly StreamingContext DefaultContext;

		internal const Formatting DefaultFormatting = Formatting.None;

		internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat;

		internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;

		internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime;

		internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double;

		internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String;

		internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default;

		internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;

		internal static readonly CultureInfo DefaultCulture;

		internal const bool DefaultCheckAdditionalContent = false;

		internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";

		internal Formatting? _formatting;

		internal DateFormatHandling? _dateFormatHandling;

		internal DateTimeZoneHandling? _dateTimeZoneHandling;

		internal DateParseHandling? _dateParseHandling;

		internal FloatFormatHandling? _floatFormatHandling;

		internal FloatParseHandling? _floatParseHandling;

		internal StringEscapeHandling? _stringEscapeHandling;

		internal CultureInfo? _culture;

		internal bool? _checkAdditionalContent;

		internal int? _maxDepth;

		internal bool _maxDepthSet;

		internal string? _dateFormatString;

		internal bool _dateFormatStringSet;

		internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal PreserveReferencesHandling? _preserveReferencesHandling;

		internal NullValueHandling? _nullValueHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal MissingMemberHandling? _missingMemberHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal StreamingContext? _context;

		internal ConstructorHandling? _constructorHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal MetadataPropertyHandling? _metadataPropertyHandling;

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public IList<JsonConverter> Converters { get; set; }

		public PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling.GetValueOrDefault();
			}
			set
			{
				_preserveReferencesHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling.GetValu

plugins/ProjectEden.dll

Decompiled 8 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using CommonAPI;
using CommonAPI.Systems;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using ProjectEden.Compatibility;
using ProjectEden.Model;
using ProjectEden.Patches;
using ProjectEden.Utils;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;
using crecheng.DSPModSave;
using xiaoye97;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("ProjectEden")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.8.2.0")]
[assembly: AssemblyInformationalVersion("1.8.2+4cb507d33ee1b39fb2d135297296949dd4cb0a0b")]
[assembly: AssemblyProduct("Project Eden")]
[assembly: AssemblyTitle("ProjectEden")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.8.2.0")]
[module: UnverifiableCode]
[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 ProjectEden
{
	internal static class ExtraRecipeRegistry
	{
		internal static ExtraRecipesConfig Config;

		internal static void Load()
		{
			Config = JsonHelper.Load<ExtraRecipesConfig>("recipes");
		}

		internal static void OnPreAddData()
		{
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Expected O, but got Unknown
			if (Config?.recipes == null || Config.recipes.Length == 0)
			{
				return;
			}
			ExtraRecipeEntry[] recipes = Config.recipes;
			foreach (ExtraRecipeEntry extraRecipeEntry in recipes)
			{
				if (extraRecipeEntry == null || extraRecipeEntry.id <= 0)
				{
					continue;
				}
				if (((ProtoSet<RecipeProto>)(object)LDB.recipes).Select(extraRecipeEntry.id) != null)
				{
					ProjectEdenPlugin.Log.LogError((object)$"配方 ID {extraRecipeEntry.id} 已被占用,「{extraRecipeEntry.name}」未注册");
					continue;
				}
				RecipeProto val = FindSource(extraRecipeEntry);
				if (val == null)
				{
					ProjectEdenPlugin.Log.LogError((object)($"找不到「{(object)(ERecipeType)(byte)extraRecipeEntry.cloneFromType}」类型中产出物品 {extraRecipeEntry.cloneFromResult} 的原版配方," + "「" + extraRecipeEntry.name + "」未注册"));
					continue;
				}
				RecipeProto val2 = new RecipeProto
				{
					ID = extraRecipeEntry.id,
					Name = extraRecipeEntry.name,
					Description = (string.IsNullOrEmpty(extraRecipeEntry.description) ? val.Description : extraRecipeEntry.description),
					Type = (ERecipeType)(byte)extraRecipeEntry.type,
					Handcraft = false,
					Explicit = true,
					NonProductive = val.NonProductive,
					TimeSpend = ((extraRecipeEntry.timeSpend > 0) ? extraRecipeEntry.timeSpend : val.TimeSpend),
					Items = (int[])val.Items.Clone(),
					ItemCounts = (int[])val.ItemCounts.Clone(),
					Results = (int[])val.Results.Clone(),
					ResultCounts = (int[])val.ResultCounts.Clone(),
					GridIndex = MegaBuildingRegistry.GridIndex(extraRecipeEntry.gridRow, extraRecipeEntry.gridCol),
					IconPath = val.IconPath,
					preTech = null
				};
				((Proto)val2).name = extraRecipeEntry.name;
				LDBTool.PreAddProto((Proto)(object)val2);
				MegaBuildingRegistry.RecipeIds.Add(extraRecipeEntry.id);
				ProtoSlots.ReserveRecipeId(extraRecipeEntry.id);
				ProtoSlots.ReserveGrid(MegaBuildingRegistry.GridIndex(extraRecipeEntry.gridRow, extraRecipeEntry.gridCol), ProtoSlots.GridKind.Recipe);
				ProjectEdenPlugin.Log.LogInfo((object)($"已注册配方「{extraRecipeEntry.name}」({(object)(ERecipeType)(byte)extraRecipeEntry.type},格位 {val2.GridIndex}):" + $"克隆自「{((Proto)val).Name}」,{Describe(val2)},耗时 {(double)val2.TimeSpend / 60.0:0.##} 秒"));
			}
		}

		private static RecipeProto FindSource(ExtraRecipeEntry entry)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			ERecipeType val = (ERecipeType)(byte)entry.cloneFromType;
			RecipeProto[] dataArray = ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray;
			foreach (RecipeProto val2 in dataArray)
			{
				if (val2 == null || val2.Type != val || val2.Results == null || val2.Items == null)
				{
					continue;
				}
				int[] results = val2.Results;
				for (int j = 0; j < results.Length; j++)
				{
					if (results[j] == entry.cloneFromResult)
					{
						return val2;
					}
				}
			}
			return null;
		}

		private static string Describe(RecipeProto recipe)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, recipe.Items, recipe.ItemCounts);
			stringBuilder.Append(" → ");
			Append(stringBuilder, recipe.Results, recipe.ResultCounts);
			return stringBuilder.ToString();
		}

		private static void Append(StringBuilder text, int[] ids, int[] counts)
		{
			for (int i = 0; i < ids.Length; i++)
			{
				if (i > 0)
				{
					text.Append(" + ");
				}
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(ids[i]);
				text.Append((val != null) ? ((Proto)val).name : ids[i].ToString());
				text.Append(" ×");
				text.Append((i < counts.Length) ? counts[i] : 0);
			}
		}
	}
	[Serializable]
	internal class ExtraRecipesConfig
	{
		public ExtraRecipeEntry[] recipes;
	}
	[Serializable]
	internal class ExtraRecipeEntry
	{
		public int id;

		public string name;

		public string description;

		public int type;

		public int cloneFromType;

		public int cloneFromResult;

		public int timeSpend;

		public int gridRow;

		public int gridCol;
	}
	internal static class MachineRegistry
	{
		internal class Machine
		{
			internal MachineEntry Entry;

			internal int ItemId;

			internal int ModelId;

			internal int RecipeId;

			internal int Grid;

			internal int RecipeGrid;

			internal int BuildIndex;

			internal string SourceIconPath;

			internal int FullItemId;

			internal int RecipeType => Entry.recipeType;

			internal string Key => Entry.key ?? Entry.displayName;

			internal bool IsStation => Entry.kind == "station";

			internal bool IsAccumulator => Entry.kind == "accumulator";

			internal bool IsExchanger => Entry.kind == "exchanger";

			internal bool IsGenerator => Entry.kind == "generator";

			internal bool IsMiner => Entry.kind == "miner";
		}

		internal static readonly List<Machine> Machines = new List<Machine>();

		internal static MachinesConfig Config { get; private set; }

		internal static IEnumerable<int> StationItemIds
		{
			get
			{
				foreach (Machine machine in Machines)
				{
					if (machine.IsStation)
					{
						yield return machine.ItemId;
					}
				}
			}
		}

		internal static MachineGeneratorEntry FindGenerator(string key)
		{
			if (Config?.machines == null || string.IsNullOrEmpty(key))
			{
				return null;
			}
			MachineEntry[] machines = Config.machines;
			foreach (MachineEntry machineEntry in machines)
			{
				if (machineEntry != null && machineEntry.key == key)
				{
					return machineEntry.generator;
				}
			}
			return null;
		}

		internal static int EmptyForFull(int fullItemId)
		{
			if (fullItemId <= 0)
			{
				return 0;
			}
			for (int i = 0; i < Machines.Count; i++)
			{
				if (Machines[i].FullItemId == fullItemId)
				{
					return Machines[i].ItemId;
				}
			}
			return 0;
		}

		internal static void Load()
		{
			Config = JsonHelper.Load<MachinesConfig>("machines");
			if (Config == null)
			{
				ProjectEdenPlugin.Log.LogWarning((object)"读不到 machines.json,新生产设备未启用");
			}
			else if (!Config.enabled)
			{
				ProjectEdenPlugin.Log.LogInfo((object)"新生产设备已在配置里关闭");
			}
		}

		internal static bool IsCustomType(int recipeType)
		{
			if (recipeType >= 9)
			{
				return recipeType != 15;
			}
			return false;
		}

		internal static string RecipeTypeMachineName(int recipeType)
		{
			if (recipeType <= 0)
			{
				return null;
			}
			for (int i = 0; i < Machines.Count; i++)
			{
				if (Machines[i].RecipeType == recipeType)
				{
					return Machines[i].Entry.displayName;
				}
			}
			return MegaBuildingRecipeTypeName(recipeType);
		}

		private static string MegaBuildingRecipeTypeName(int recipeType)
		{
			if (!IsCustomType(recipeType))
			{
				return null;
			}
			MegaBuildingEntry[] array = MegaBuildingRegistry.Config?.buildings;
			if (array == null)
			{
				return null;
			}
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] != null && array[i].recipeType == recipeType)
				{
					return array[i].displayName;
				}
			}
			return null;
		}

		internal static string MachineTypeName(int itemId)
		{
			for (int i = 0; i < Machines.Count; i++)
			{
				if (Machines[i].ItemId == itemId)
				{
					return Machines[i].Entry.machineTypeName;
				}
			}
			MegaBuildingEntry[] array = MegaBuildingRegistry.Config?.buildings;
			if (array == null)
			{
				return null;
			}
			for (int j = 0; j < array.Length; j++)
			{
				if (array[j] != null && array[j].itemId == itemId && IsCustomType(array[j].recipeType))
				{
					if (!string.IsNullOrEmpty(array[j].machineTypeName))
					{
						return array[j].machineTypeName;
					}
					return array[j].displayName;
				}
			}
			return null;
		}

		internal static void OnPreAddData()
		{
			Machines.Clear();
			if (Config == null || !Config.enabled || Config.machines == null)
			{
				return;
			}
			MachineEntry[] machines = Config.machines;
			foreach (MachineEntry machineEntry in machines)
			{
				if (machineEntry == null || !machineEntry.enabled)
				{
					continue;
				}
				ItemProto val = (ProtoSlots.ItemIdTaken(machineEntry.copyFromItemId) ? ((ProtoSet<ItemProto>)(object)LDB.items).Select(machineEntry.copyFromItemId) : null);
				if (val == null)
				{
					ProjectEdenPlugin.Log.LogError((object)$"找不到源建筑 {machineEntry.copyFromItemId},{machineEntry.displayName} 未注册");
					continue;
				}
				bool flag = machineEntry.kind == "station";
				bool flag2 = machineEntry.kind == "accumulator";
				bool flag3 = machineEntry.kind == "exchanger";
				bool flag4 = machineEntry.kind == "generator";
				bool flag5 = machineEntry.kind == "miner";
				if (!flag && !flag2 && !flag3 && !flag4 && !flag5 && machineEntry.recipeType <= 0)
				{
					ProjectEdenPlugin.Log.LogError((object)(machineEntry.displayName + " 没有配 recipeType,跳过"));
					continue;
				}
				if (flag4 && !SourceIsPowerGen(val))
				{
					ProjectEdenPlugin.Log.LogError((object)($"{machineEntry.displayName} 配成了 generator,但来源建筑 {machineEntry.copyFromItemId} 的 " + "prefabDesc.isPowerGen 是 false,跳过。来源要选一台发电建筑。"));
					continue;
				}
				if (flag2 && !SourceIsAccumulator(val))
				{
					ProjectEdenPlugin.Log.LogError((object)($"{machineEntry.displayName} 配成了 accumulator,但来源建筑 {machineEntry.copyFromItemId} 的 " + "prefabDesc.isAccumulator 是 false,跳过。来源要选蓄电器。"));
					continue;
				}
				if (flag5 && !SourceIsVeinMiner(val))
				{
					ProjectEdenPlugin.Log.LogError((object)($"{machineEntry.displayName} 配成了 miner,但来源建筑 {machineEntry.copyFromItemId} 的 " + "prefabDesc.minerType 不是 Vein,跳过。来源要选一台采矿机。"));
					continue;
				}
				if (flag && !SourceIsStation(val))
				{
					ProjectEdenPlugin.Log.LogError((object)($"{machineEntry.displayName} 配成了 station,但来源建筑 {machineEntry.copyFromItemId} 的 prefabDesc.isStation 是 false,跳过。" + "想同时要行星内运输机和星际运输船,来源要选星际物流运输站。"));
					continue;
				}
				Machine machine = new Machine
				{
					Entry = machineEntry,
					SourceIconPath = val.IconPath
				};
				machine.ItemId = ProtoSlots.ResolveItemId(machineEntry.itemId, machineEntry.displayName);
				machine.ModelId = ProtoSlots.ResolveModelId(machineEntry.modelId, machineEntry.displayName);
				machine.Grid = ProtoSlots.ResolveGridIndex(WantedGrid(machineEntry, val), machineEntry.displayName, ProtoSlots.GridKind.Item, (int g) => Pending(g, ProtoSlots.GridKind.Item));
				machine.BuildIndex = ProtoSlots.ResolveBuildIndex(WantedBuildIndex(machineEntry, val), machineEntry.displayName, PendingBuild, MegaBuildingRegistry.Config?.buildCategory ?? 0);
				if (machine.ModelId <= 0)
				{
					ProjectEdenPlugin.Log.LogError((object)(machineEntry.displayName + " 找不到可用的模型 ID,未注册"));
					continue;
				}
				ProtoSlots.ReserveItemId(machine.ItemId);
				ProtoSlots.ReserveModelId(machine.ModelId);
				ProtoSlots.ReserveGrid(machine.Grid, ProtoSlots.GridKind.Item);
				ProtoSlots.ReserveBuildIndex(machine.BuildIndex);
				CloneModel(machine, val);
				AddItem(machine, val);
				AddFullVariant(machine);
				Machines.Add(machine);
				AddBuildRecipe(machine);
				object obj;
				if (!machine.IsStation)
				{
					obj = (machine.IsAccumulator ? "蓄电器" : (machine.IsExchanger ? "能量枢纽" : (machine.IsGenerator ? "发电设备" : (machine.IsMiner ? $"采矿设备:固定 {machineEntry.miner?.oresPerMinute ?? 0} 矿/分钟" : $"配方类型 {machineEntry.recipeType}({machineEntry.recipeTypeName})"))));
				}
				else
				{
					string text = $"物流站:运输机 {machineEntry.station?.maxDroneCount ?? 0} / 运输船 {machineEntry.station?.maxShipCount ?? 0}";
					MachineStationEntry station = machineEntry.station;
					obj = text + ((station != null && station.courierCount > 0) ? $" / 配送运输机 {machineEntry.station.courierCount}" : "");
				}
				string text2 = (string)obj;
				ProjectEdenPlugin.Log.LogInfo((object)($"{machineEntry.displayName}已注册:物品 {machine.ItemId},模型 {machine.ModelId},{text2}," + $"建造栏第 {machine.BuildIndex / 100} 类第 {machine.BuildIndex % 100} 槽"));
			}
		}

		private static int WantedGrid(MachineEntry entry, ItemProto source)
		{
			if (entry.megaTab && MegaBuildingRegistry.TabIndex > 0)
			{
				return MegaBuildingRegistry.GridIndex((entry.gridRow <= 0) ? 1 : entry.gridRow, (entry.gridCol <= 0) ? 1 : entry.gridCol);
			}
			if (entry.megaTab)
			{
				ProjectEdenPlugin.Log.LogWarning((object)(entry.displayName + " 配了 megaTab,但巨型建筑分页还没注册出来(索引 " + $"{MegaBuildingRegistry.TabIndex}),格位退回源建筑那一页"));
			}
			if (entry.gridIndex <= 0)
			{
				return source.GridIndex;
			}
			return entry.gridIndex;
		}

		private static int WantedBuildIndex(MachineEntry entry, ItemProto source)
		{
			int num = MegaBuildingRegistry.Config?.buildCategory ?? 0;
			if (entry.megaTab && num > 0)
			{
				return num * 100 + ((entry.buildSlot <= 0) ? 1 : entry.buildSlot);
			}
			if (entry.buildIndex <= 0)
			{
				return source.BuildIndex;
			}
			return entry.buildIndex;
		}

		private static bool Pending(int grid, ProtoSlots.GridKind kind)
		{
			bool flag = kind == ProtoSlots.GridKind.Item;
			for (int i = 0; i < Machines.Count; i++)
			{
				if (flag ? (Machines[i].Grid == grid) : (Machines[i].RecipeGrid == grid))
				{
					return true;
				}
			}
			return false;
		}

		private static bool PendingBuild(int buildIndex)
		{
			for (int i = 0; i < Machines.Count; i++)
			{
				if (Machines[i].BuildIndex == buildIndex)
				{
					return true;
				}
			}
			return false;
		}

		private static void CloneModel(Machine machine, ItemProto source)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Expected O, but got Unknown
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			ModelProto val = ((ProtoSet<ModelProto>)(object)LDB.models).Select(source.ModelIndex);
			if (val == null)
			{
				ProjectEdenPlugin.Log.LogError((object)$"找不到源模型 {source.ModelIndex},{machine.Entry.displayName} 将没有外观");
				return;
			}
			ModelProto val2 = new ModelProto
			{
				ObjectType = val.ObjectType,
				RuinType = val.RuinType,
				RendererType = val.RendererType,
				HpMax = val.HpMax,
				PrefabPath = val.PrefabPath,
				Order = val.Order,
				ID = machine.ModelId,
				Name = machine.ModelId.ToString(),
				SID = "",
				sid = ""
			};
			PrefabDesc prefabDesc = val.prefabDesc;
			GameObject val3 = (Object.op_Implicit((Object)(object)prefabDesc.prefab) ? prefabDesc.prefab : Resources.Load<GameObject>(val.PrefabPath));
			GameObject val4 = (Object.op_Implicit((Object)(object)prefabDesc.colliderPrefab) ? prefabDesc.colliderPrefab : Resources.Load<GameObject>(val._colliderPath));
			ref PrefabDesc prefabDesc2 = ref val2.prefabDesc;
			prefabDesc2 = (PrefabDesc)(((Object)(object)val3 == (Object)null) ? ((object)PrefabDesc.none) : ((object)((!((Object)(object)val4 == (Object)null)) ? new PrefabDesc(machine.ModelId, val3, val4) : new PrefabDesc(machine.ModelId, val3))));
			TintMaterials(prefabDesc2, machine.Entry.tint);
			prefabDesc2.modelIndex = machine.ModelId;
			prefabDesc2.hasBuildCollider = prefabDesc.hasBuildCollider;
			prefabDesc2.colliders = prefabDesc.colliders;
			prefabDesc2.buildCollider = prefabDesc.buildCollider;
			prefabDesc2.buildColliders = prefabDesc.buildColliders;
			prefabDesc2.colliderPrefab = prefabDesc.colliderPrefab;
			prefabDesc2.dragBuild = prefabDesc.dragBuild;
			prefabDesc2.dragBuildDist = prefabDesc.dragBuildDist;
			prefabDesc2.blueprintBoxSize = prefabDesc.blueprintBoxSize;
			prefabDesc2.roughHeight = prefabDesc.roughHeight;
			prefabDesc2.roughWidth = prefabDesc.roughWidth;
			prefabDesc2.roughRadius = prefabDesc.roughRadius;
			prefabDesc2.barHeight = prefabDesc.barHeight;
			if (machine.IsStation)
			{
				ApplyStation(prefabDesc2, machine.Entry.station);
			}
			else if (machine.IsAccumulator)
			{
				ApplyAccumulator(prefabDesc2, prefabDesc, machine);
			}
			else if (machine.IsExchanger)
			{
				ApplyExchanger(prefabDesc2, prefabDesc, machine);
			}
			else if (machine.IsGenerator)
			{
				ApplyGenerator(prefabDesc2, prefabDesc, machine);
			}
			else if (machine.IsMiner)
			{
				ApplyMiner(prefabDesc2, prefabDesc, machine);
			}
			else
			{
				prefabDesc2.assemblerRecipeType = (ERecipeType)(byte)machine.Entry.recipeType;
			}
			LDBTool.PreAddProto((Proto)val2);
		}

		private static void AddFullVariant(Machine machine)
		{
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Expected O, but got Unknown
			MachineFullVariantEntry machineFullVariantEntry = machine.Entry.accumulator?.fullVariant;
			if (!machine.IsAccumulator || machineFullVariantEntry == null)
			{
				return;
			}
			ItemProto val = (ProtoSlots.ItemIdTaken(machineFullVariantEntry.copyFromItemId) ? ((ProtoSet<ItemProto>)(object)LDB.items).Select(machineFullVariantEntry.copyFromItemId) : null);
			if (val == null)
			{
				ProjectEdenPlugin.Log.LogError((object)$"{machine.Entry.displayName}的「满」版本找不到源物品 {machineFullVariantEntry.copyFromItemId},未注册");
				return;
			}
			machine.FullItemId = ProtoSlots.ResolveItemId(machineFullVariantEntry.itemId, machineFullVariantEntry.displayName);
			int num = ProtoSlots.ResolveGridIndex((machineFullVariantEntry.gridIndex > 0) ? machineFullVariantEntry.gridIndex : val.GridIndex, machineFullVariantEntry.displayName, ProtoSlots.GridKind.Item, (int g) => Pending(g, ProtoSlots.GridKind.Item));
			float num2 = ((machine.Entry.accumulator.capacityMultiplier > 0f) ? machine.Entry.accumulator.capacityMultiplier : 1f);
			long num3 = ((machineFullVariantEntry.heatValue > 0) ? machineFullVariantEntry.heatValue : ((long)((float)val.HeatValue * num2)));
			ItemProto val2 = new ItemProto
			{
				ID = machine.FullItemId,
				Name = machineFullVariantEntry.displayName,
				Description = machineFullVariantEntry.description,
				Type = val.Type,
				GridIndex = num,
				StackSize = val.StackSize,
				IconPath = val.IconPath,
				IsFluid = false,
				IsEntity = true,
				CanBuild = true,
				BuildInGas = val.BuildInGas,
				BuildIndex = 0,
				BuildMode = val.BuildMode,
				ModelIndex = machine.ModelId,
				ModelCount = val.ModelCount,
				HpMax = val.HpMax,
				Grade = 0,
				Upgrades = new int[0],
				DescFields = val.DescFields,
				FuelType = ((machineFullVariantEntry.fuelType > 0) ? machineFullVariantEntry.fuelType : val.FuelType),
				HeatValue = num3,
				ReactorInc = ((machineFullVariantEntry.reactorInc != 0f) ? machineFullVariantEntry.reactorInc : val.ReactorInc),
				UnlockKey = -1,
				PreTechOverride = 0,
				prefabDesc = PrefabDesc.none
			};
			((Proto)val2).name = machineFullVariantEntry.displayName;
			LDBTool.PreAddProto((Proto)(object)val2);
			ProtoSlots.ReserveItemId(machine.FullItemId);
			ProtoSlots.ReserveGrid(num, ProtoSlots.GridKind.Item);
			ProjectEdenPlugin.Log.LogInfo((object)($"「{machineFullVariantEntry.displayName}」已注册:物品 {machine.FullItemId}," + $"燃料类型 {val2.FuelType},热值 {Energy(num3)}(源 {Energy(val.HeatValue)} ×{num2:0.##})," + $"机甲功率 ×{val2.ReactorInc + 1f:0.##}(源 ×{val.ReactorInc + 1f:0.##})"));
		}

		private static void ApplyExchanger(PrefabDesc target, PrefabDesc source, Machine machine)
		{
			MachineExchangerEntry exchanger = machine.Entry.exchanger;
			Machine machine2 = null;
			for (int i = 0; i < Machines.Count; i++)
			{
				if (Machines[i].Key == exchanger?.pairMachineKey)
				{
					machine2 = Machines[i];
				}
			}
			if (machine2 == null || machine2.FullItemId <= 0)
			{
				ProjectEdenPlugin.Log.LogError((object)(machine.Entry.displayName + " 的 pairMachineKey「" + exchanger?.pairMachineKey + "」找不到对应的蓄电器,或那台没有配 fullVariant。注册按 machines 数组顺序走,蓄电器那条必须排在枢纽之前。" + $"本台将继续服务原版的那一对({source.emptyId} / {source.fullId})"));
			}
			else
			{
				target.emptyId = machine2.ItemId;
				target.fullId = machine2.FullItemId;
				float num = ((exchanger.energyMultiplier > 0f) ? exchanger.energyMultiplier : 1f);
				float num2 = ((exchanger.poolMultiplier > 0f) ? exchanger.poolMultiplier : 1f);
				target.exchangeEnergyPerTick = (long)((float)source.exchangeEnergyPerTick * num);
				target.maxExcEnergy = (long)((float)source.maxExcEnergy * num2);
				ProjectEdenPlugin.Log.LogInfo((object)($"{machine.Entry.displayName}:服务「{machine2.Entry.displayName}」(空 {target.emptyId} / 满 {target.fullId})," + $"功率 {Power(source.exchangeEnergyPerTick)} → {Power(target.exchangeEnergyPerTick)}(×{num:0.##})," + $"能量池 {Energy(source.maxExcEnergy)} → {Energy(target.maxExcEnergy)}(×{num2:0.##})"));
			}
		}

		private static void TintFullVariant(Machine machine, MachineEntry e)
		{
			MachineFullVariantEntry machineFullVariantEntry = e.accumulator?.fullVariant;
			if (machine.FullItemId <= 0 || machineFullVariantEntry == null)
			{
				return;
			}
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(machineFullVariantEntry.copyFromItemId);
			ItemProto val2 = ((ProtoSet<ItemProto>)(object)LDB.items).Select(machine.FullItemId);
			if (!((Object)(object)val?._iconSprite == (Object)null) && val2 != null)
			{
				Sprite val3 = IconTinter.Tint(val._iconSprite, e.iconHue, e.iconSaturationScale, e.iconMinSaturation, e.iconValueScale);
				if ((Object)(object)val3 == (Object)null)
				{
					ProjectEdenPlugin.Log.LogWarning((object)(machineFullVariantEntry.displayName + "的图标改色失败,用的还是源物品的原图"));
				}
				else
				{
					val2._iconSprite = val3;
				}
			}
		}

		private static bool SourceIsVeinMiner(ItemProto source)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			ModelProto val = ((ProtoSet<ModelProto>)(object)LDB.models).Select(source.ModelIndex);
			if (val?.prefabDesc != null)
			{
				return (int)val.prefabDesc.minerType == 2;
			}
			return false;
		}

		private static void ApplyMiner(PrefabDesc target, PrefabDesc source, Machine machine)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			MachineMinerEntry miner = machine.Entry.miner;
			target.minerType = source.minerType;
			target.isVeinCollector = source.isVeinCollector;
			target.isStation = source.isStation;
			target.stationMaxItemKinds = source.stationMaxItemKinds;
			target.stationMaxDroneCount = source.stationMaxDroneCount;
			target.stationMaxShipCount = source.stationMaxShipCount;
			target.stationCollectSpeed = source.stationCollectSpeed;
			target.veinMiner = source.veinMiner;
			target.oilMiner = source.oilMiner;
			if (miner != null)
			{
				if (miner.stationCapacity > 0)
				{
					target.stationMaxItemCount = miner.stationCapacity;
				}
				if (miner.workEnergyWatt > 0)
				{
					target.workEnergyPerTick = miner.workEnergyWatt / 60;
					target.idleEnergyPerTick = target.workEnergyPerTick / 20;
				}
				ProjectEdenPlugin.Log.LogInfo((object)($"  {machine.Entry.displayName}:固定产量 {miner.oresPerMinute} 矿/分钟," + $"工作功率 {(float)miner.workEnergyWatt / 1000000f:0.##} MW," + $"仓位容量 {target.stationMaxItemCount}," + "矿脉" + (miner.consumeVeins ? "会" : "不会") + "消耗"));
			}
		}

		private static bool SourceIsPowerGen(ItemProto source)
		{
			ModelProto val = ((ProtoSet<ModelProto>)(object)LDB.models).Select(source.ModelIndex);
			if (val != null && val.prefabDesc != null)
			{
				return val.prefabDesc.isPowerGen;
			}
			return false;
		}

		private static void ApplyGenerator(PrefabDesc target, PrefabDesc source, Machine machine)
		{
			MachineGeneratorEntry generator = machine.Entry.generator;
			target.isPowerGen = true;
			target.subId = source.subId;
			target.photovoltaic = source.photovoltaic;
			target.windForcedPower = source.windForcedPower;
			target.gammaRayReceiver = source.gammaRayReceiver;
			target.geothermal = source.geothermal;
			target.fuelMask = ((generator != null && generator.fuelMask > 0) ? generator.fuelMask : source.fuelMask);
			target.powerCatalystId = source.powerCatalystId;
			target.powerProductId = source.powerProductId;
			target.powerProductHeat = source.powerProductHeat;
			float num = ((generator != null && generator.powerMultiplier > 0f) ? generator.powerMultiplier : 1f);
			target.genEnergyPerTick = (long)((float)source.genEnergyPerTick * num);
			if (generator != null && generator.efficiency > 0f)
			{
				target.useFuelPerTick = (long)((float)target.genEnergyPerTick / generator.efficiency);
			}
			else
			{
				target.useFuelPerTick = (long)((float)source.useFuelPerTick * ((generator != null && generator.fuelMultiplier > 0f) ? generator.fuelMultiplier : num));
			}
			string text = machine.Entry.displayName + ":发电 " + Power(source.genEnergyPerTick) + " → " + $"{Power(target.genEnergyPerTick)}(×{num:0.##})";
			if (source.useFuelPerTick > 0 && target.useFuelPerTick > 0)
			{
				double num2 = (double)source.genEnergyPerTick / (double)source.useFuelPerTick;
				double num3 = (double)target.genEnergyPerTick / (double)target.useFuelPerTick;
				text = text + ",耗料 " + Power(source.useFuelPerTick) + " → " + Power(target.useFuelPerTick) + $",能量利用率 {num2:0.###} → {num3:0.###}" + $",燃料掩码 {source.fuelMask} → {target.fuelMask}" + $",ABN 下限 useFuelPerTick ≥ {(double)target.useFuelPerTick * 0.7:0}";
			}
			else
			{
				text += ",无燃料";
			}
			ProjectEdenPlugin.Log.LogInfo((object)text);
		}

		private static bool SourceIsAccumulator(ItemProto source)
		{
			ModelProto val = ((ProtoSet<ModelProto>)(object)LDB.models).Select(source.ModelIndex);
			if (val != null && val.prefabDesc != null)
			{
				return val.prefabDesc.isAccumulator;
			}
			return false;
		}

		private static void ApplyAccumulator(PrefabDesc target, PrefabDesc source, Machine machine)
		{
			MachineAccumulatorEntry accumulator = machine.Entry.accumulator;
			target.isAccumulator = true;
			target.subId = source.subId;
			float num = ((accumulator != null && accumulator.capacityMultiplier > 0f) ? accumulator.capacityMultiplier : 1f);
			float num2 = ((accumulator != null && accumulator.inputMultiplier > 0f) ? accumulator.inputMultiplier : 1f);
			float num3 = ((accumulator != null && accumulator.outputMultiplier > 0f) ? accumulator.outputMultiplier : 1f);
			target.maxAcuEnergy = (long)((float)source.maxAcuEnergy * num);
			target.inputEnergyPerTick = (long)((float)source.inputEnergyPerTick * num2);
			target.outputEnergyPerTick = (long)((float)source.outputEnergyPerTick * num3);
			ProjectEdenPlugin.Log.LogInfo((object)($"{machine.Entry.displayName}:容量 {Energy(source.maxAcuEnergy)} → {Energy(target.maxAcuEnergy)}(×{num:0.##})," + $"充电 {Power(source.inputEnergyPerTick)} → {Power(target.inputEnergyPerTick)}(×{num2:0.##})," + $"放电 {Power(source.outputEnergyPerTick)} → {Power(target.outputEnergyPerTick)}(×{num3:0.##})"));
		}

		private static string Energy(long joule)
		{
			if (joule >= 1000000000)
			{
				return $"{(double)joule / 1000000000.0:0.##} GJ";
			}
			if (joule >= 1000000)
			{
				return $"{(double)joule / 1000000.0:0.##} MJ";
			}
			return $"{(double)joule / 1000.0:0.##} kJ";
		}

		private static string Power(long joulePerTick)
		{
			double num = (double)joulePerTick * 60.0;
			if (num >= 1000000000.0)
			{
				return $"{num / 1000000000.0:0.##} GW";
			}
			if (num >= 1000000.0)
			{
				return $"{num / 1000000.0:0.##} MW";
			}
			return $"{num / 1000.0:0.##} kW";
		}

		private static bool SourceIsStation(ItemProto source)
		{
			ModelProto val = ((ProtoSet<ModelProto>)(object)LDB.models).Select(source.ModelIndex);
			if (val != null && val.prefabDesc != null)
			{
				return val.prefabDesc.isStation;
			}
			return false;
		}

		private static void ApplyStation(PrefabDesc desc, MachineStationEntry station)
		{
			if (station == null)
			{
				return;
			}
			if (station.maxDroneCount > 0)
			{
				desc.stationMaxDroneCount = station.maxDroneCount;
			}
			if (station.maxShipCount > 0)
			{
				int num = ((station.maxShipCount > 64) ? 64 : station.maxShipCount);
				if (num != station.maxShipCount)
				{
					ProjectEdenPlugin.Log.LogWarning((object)($"运输船上限 {station.maxShipCount} 超过类型上限,已夹到 {num}——" + "StationComponent.idleShipIndices 是 64 位位图,再多会互相覆盖"));
				}
				desc.stationMaxShipCount = num;
			}
			if (station.maxItemCount > 0)
			{
				desc.stationMaxItemCount = station.maxItemCount;
			}
			if (station.maxItemKinds > 0)
			{
				desc.stationMaxItemKinds = station.maxItemKinds;
			}
			if (station.maxEnergyAcc > 0)
			{
				desc.stationMaxEnergyAcc = station.maxEnergyAcc;
			}
			if (station.workEnergyPerTick > 0)
			{
				desc.workEnergyPerTick = station.workEnergyPerTick;
			}
			if (station.courierCount > 0)
			{
				desc.isDispenser = true;
				desc.dispenserMaxCourierCount = station.courierCount;
				desc.dispenserMaxEnergyAcc = ((station.courierEnergyAcc > 0) ? station.courierEnergyAcc : 30000000);
				desc.isStorage = true;
				desc.storageCol = ((station.bufferCols > 0) ? station.bufferCols : 6);
				desc.storageRow = ((station.bufferRows > 0) ? station.bufferRows : 5);
			}
		}

		private static void TintMaterials(PrefabDesc desc, float[] tint)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			if (tint == null || tint.Length < 3 || desc.lodMaterials == null)
			{
				return;
			}
			Color val = default(Color);
			((Color)(ref val))..ctor(tint[0], tint[1], tint[2]);
			Material[][] lodMaterials = desc.lodMaterials;
			foreach (Material[] array in lodMaterials)
			{
				if (array == null)
				{
					continue;
				}
				for (int j = 0; j < array.Length; j++)
				{
					ref Material reference = ref array[j];
					if (!((Object)(object)reference == (Object)null))
					{
						reference = new Material(reference);
						reference.SetColor("_Color", val);
					}
				}
			}
		}

		private static void AddItem(Machine machine, ItemProto source)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			MachineEntry entry = machine.Entry;
			LDBTool.PreAddProto((Proto)new ItemProto
			{
				ID = machine.ItemId,
				Name = entry.displayName,
				Description = entry.description,
				Type = source.Type,
				GridIndex = machine.Grid,
				StackSize = source.StackSize,
				IconPath = source.IconPath,
				IsFluid = false,
				IsEntity = true,
				CanBuild = true,
				BuildInGas = source.BuildInGas,
				BuildIndex = machine.BuildIndex,
				BuildMode = source.BuildMode,
				ModelIndex = machine.ModelId,
				ModelCount = source.ModelCount,
				HpMax = source.HpMax,
				Grade = 0,
				Upgrades = new int[0],
				DescFields = source.DescFields,
				UnlockKey = -1,
				PreTechOverride = 0,
				prefabDesc = PrefabDesc.none,
				name = entry.displayName
			});
		}

		private static void AddBuildRecipe(Machine machine)
		{
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Expected O, but got Unknown
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			MachineEntry entry = machine.Entry;
			if (entry.recipeItems == null || entry.recipeItems.Length == 0)
			{
				ProjectEdenPlugin.Log.LogWarning((object)(entry.displayName + " 没有配建造配方,做不出来"));
				return;
			}
			int[] array = new int[entry.recipeItems.Length];
			int[] array2 = new int[entry.recipeItems.Length];
			for (int i = 0; i < entry.recipeItems.Length; i++)
			{
				RecipeItemEntry recipeItemEntry = entry.recipeItems[i];
				int num = (string.IsNullOrEmpty(recipeItemEntry.@ref) ? recipeItemEntry.id : OreRegistry.FindItemIdByRef(recipeItemEntry.@ref));
				if (!string.IsNullOrEmpty(recipeItemEntry.@ref) && num <= 0)
				{
					ProjectEdenPlugin.Log.LogError((object)(entry.displayName + " 的建造配方里,引用名「" + recipeItemEntry.@ref + "」解析不出物品——它得是 ores.json 里 items 段某条的 key,或者矿种的 key 加 .ore / .ingot 后缀。配方未注册"));
					return;
				}
				if (!ProtoSlots.ItemIdTaken(num))
				{
					ProjectEdenPlugin.Log.LogError((object)$"{entry.displayName} 的建造配方里,物品 ID {num} 不存在,配方未注册");
					return;
				}
				array[i] = num;
				array2[i] = ((recipeItemEntry.count <= 0) ? 1 : recipeItemEntry.count);
			}
			machine.RecipeId = ProtoSlots.ResolveRecipeId(entry.recipeId, entry.displayName);
			machine.RecipeGrid = ProtoSlots.ResolveGridIndex((entry.recipeGridIndex > 0) ? entry.recipeGridIndex : machine.Grid, entry.displayName + "(配方)", ProtoSlots.GridKind.Recipe, (int g) => Pending(g, ProtoSlots.GridKind.Recipe));
			RecipeProto val = new RecipeProto();
			((Proto)val).ID = machine.RecipeId;
			((Proto)val).Name = entry.displayName;
			val.Description = entry.description;
			val.Type = (ERecipeType)((!entry.recipeHandcraftOnly) ? 4 : 0);
			val.Handcraft = true;
			val.Explicit = true;
			val.TimeSpend = ((entry.recipeTimeSpend > 0) ? entry.recipeTimeSpend : 180);
			val.Items = array;
			val.ItemCounts = array2;
			val.Results = new int[1] { machine.ItemId };
			val.ResultCounts = new int[1] { 1 };
			val.GridIndex = machine.RecipeGrid;
			val.IconPath = machine.SourceIconPath;
			val.preTech = null;
			((Proto)val).name = entry.displayName;
			LDBTool.PreAddProto((Proto)(object)val);
			MegaBuildingRegistry.RecipeIds.Add(machine.RecipeId);
			ProtoSlots.ReserveRecipeId(machine.RecipeId);
			ProtoSlots.ReserveGrid(machine.RecipeGrid, ProtoSlots.GridKind.Recipe);
		}

		internal static void OnPostAddData()
		{
			foreach (Machine machine in Machines)
			{
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(machine.ItemId);
				if (val == null || ((Proto)val).Name != machine.Entry.displayName)
				{
					ProjectEdenPlugin.Log.LogError((object)($"「{machine.Entry.displayName}」本应占用物品 ID {machine.ItemId}," + "实际那里是「" + (((Proto)(val?)).Name ?? "空") + "」。多半是 BepInEx/config/LDBTool/LDBTool.CustomID.cfg 里存着旧的绑定——它按名字记 ID 并在本 mod 之后反向覆盖。删掉那一行再重开游戏。"));
				}
				TintIcon(machine);
			}
		}

		private static void TintIcon(Machine machine)
		{
			MachineEntry entry = machine.Entry;
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(entry.copyFromItemId);
			Sprite val2 = (((Object)(object)val?._iconSprite == (Object)null) ? null : IconTinter.Tint(val._iconSprite, entry.iconHue, entry.iconSaturationScale, entry.iconMinSaturation, entry.iconValueScale));
			if ((Object)(object)val2 == (Object)null)
			{
				ProjectEdenPlugin.Log.LogWarning((object)(entry.displayName + "的图标改色失败,用的还是源建筑的原图"));
				return;
			}
			ItemProto val3 = ((ProtoSet<ItemProto>)(object)LDB.items).Select(machine.ItemId);
			RecipeProto val4 = ((machine.RecipeId > 0) ? ((ProtoSet<RecipeProto>)(object)LDB.recipes).Select(machine.RecipeId) : null);
			if (val3 != null)
			{
				val3._iconSprite = val2;
			}
			if (val4 != null)
			{
				val4._iconSprite = val2;
			}
			TintFullVariant(machine, entry);
			ProjectEdenPlugin.Log.LogInfo((object)(entry.displayName + "的图标已由「" + ((Proto)val).name + "」改色生成" + $"(色相 {entry.iconHue:0}°,饱和度 ×{entry.iconSaturationScale:0.##},明度 ×{entry.iconValueScale:0.##})"));
		}
	}
	internal static class MegaBuildingRegistry
	{
		internal static readonly HashSet<int> RecipeIds = new HashSet<int>();

		private static readonly Dictionary<int, int> AssignedModelIds = new Dictionary<int, int>();

		private static int _tabIndex = -1;

		private static bool _modelModeReported;

		internal static MegaBuildingsConfig Config { get; private set; }

		internal static int TabIndex => _tabIndex;

		internal static int MegaSpeedThreshold
		{
			get
			{
				if (Config != null)
				{
					if (Config.megaSpeedThreshold <= 0)
					{
						return Config.assemblerSpeed;
					}
					return Config.megaSpeedThreshold;
				}
				return int.MaxValue;
			}
		}

		internal static void Load()
		{
			Config = JsonHelper.Load<MegaBuildingsConfig>("megabuildings");
		}

		internal static void RegisterTab()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			_tabIndex = TabSystem.RegisterTab(Config.tabId, new TabData(Config.tabName, Config.tabIconPath));
			ProjectEdenPlugin.Log.LogInfo((object)$"已注册建造栏分页「{Config.tabName}」,索引 {_tabIndex}");
		}

		internal static MegaBuildingEntry EntryOf(int itemId)
		{
			MegaBuildingEntry[] array = Config?.buildings;
			if (array == null)
			{
				return null;
			}
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] != null && array[i].itemId == itemId)
				{
					return array[i];
				}
			}
			return null;
		}

		internal static void OnPreAddData()
		{
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			PilerLevelPatches.ModifyPilerTeches();
			((ProtoSet<ItemProto>)(object)LDB.items).OnAfterDeserialize();
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(Config.copyFromItemId);
			if (val == null)
			{
				ProjectEdenPlugin.Log.LogError((object)$"找不到物品模板 {Config.copyFromItemId},巨型建筑注册中止");
				return;
			}
			if (Config.buildings == null || Config.buildings.Length == 0)
			{
				ProjectEdenPlugin.Log.LogError((object)"megabuildings.json 里没有解析出任何建筑(buildings 为空)。顶层字段能读到而 buildings 读不到,通常是 JSON 解析器的问题,不是文件内容的问题。");
				return;
			}
			ProtoSlots.ClearReservations();
			MegaBuildingEntry[] buildings = Config.buildings;
			foreach (MegaBuildingEntry megaBuildingEntry in buildings)
			{
				int num = ResolveModelId(megaBuildingEntry.modelId);
				if (num <= 0)
				{
					ProjectEdenPlugin.Log.LogError((object)(megaBuildingEntry.displayName + ":找不到可用的模型 ID,跳过"));
					continue;
				}
				AssignedModelIds[megaBuildingEntry.modelId] = num;
				ReportProceduralModels();
				CopyModelProto(Config.copyFromModelId, num, megaBuildingEntry, new Color(megaBuildingEntry.tintR, megaBuildingEntry.tintG, megaBuildingEntry.tintB));
				AddItemProto(val, megaBuildingEntry, num);
				AddRecipeProto(megaBuildingEntry);
				RecipeIds.Add(megaBuildingEntry.recipeId);
				ProtoSlots.ReserveItemId(megaBuildingEntry.itemId);
				ProtoSlots.ReserveRecipeId(megaBuildingEntry.recipeId);
				ProtoSlots.ReserveModelId(num);
				ProtoSlots.ReserveGrid(GridIndexOf(megaBuildingEntry), ProtoSlots.GridKind.Item);
				ProtoSlots.ReserveGrid(GridIndexOf(megaBuildingEntry), ProtoSlots.GridKind.Recipe);
				ProtoSlots.ReserveBuildIndex(Config.buildCategory * 100 + megaBuildingEntry.slot);
			}
			ExtraRecipeRegistry.OnPreAddData();
		}

		internal static void OnPostAddData()
		{
			((ProtoSet<ItemProto>)(object)LDB.items).OnAfterDeserialize();
			((ProtoSet<RecipeProto>)(object)LDB.recipes).OnAfterDeserialize();
			((ProtoSet<ModelProto>)(object)LDB.models).OnAfterDeserialize();
			ProtoPreload();
			ItemProto.InitConstructableItems();
			ItemProto.InitItemIds();
			ItemProto.InitItemIndices();
			ItemProto.InitProductionMask();
			ModelProto.InitMaxModelIndex();
			ModelProto.InitModelIndices();
			ModelProto.InitModelOrders();
			StorageComponent.staticLoaded = false;
			StorageComponent.LoadStatic();
			UIBuildMenu.staticLoaded = false;
			UIBuildMenu.StaticLoad();
			ReportBuildMenuSlots();
			PlanetFactory.PrefabDescByModelIndex = null;
			PlanetFactory.InitPrefabDescArray();
			if ((Object)(object)GameMain.instance != (Object)null)
			{
				GameMain.instance.CreateGPUInstancing();
				GameMain.instance.CreateBPGPUInstancing();
			}
			AdvancedMinerPatches.BuildProductMap();
			StationCapacityPatches.ApplyPrefabCapacity();
			GasCollectorPatches.ApplyPrefabSpeed();
			MatrixLabPatches.ApplyPrefabSpeed();
			PowerCoveragePatches.ApplyPrefabCoverage();
			MegaLightPatches.Collect();
			MegaBuildingEntry[] buildings = Config.buildings;
			foreach (MegaBuildingEntry megaBuildingEntry in buildings)
			{
				if (AssignedModelIds.TryGetValue(megaBuildingEntry.modelId, out var value))
				{
					ProjectEdenPlugin.Log.LogInfo((object)($"  已注册 {megaBuildingEntry.displayName}:物品 {megaBuildingEntry.itemId} / 模型 {value} / 配方 {megaBuildingEntry.recipeId}" + $"({(object)(ERecipeType)(byte)megaBuildingEntry.recipeType},{(double)Config.assemblerSpeed / 10000.0:0.#} 倍速)"));
					ReportSpeedCeiling();
				}
			}
		}

		private static void ReportBuildMenuSlots()
		{
			if (Config?.buildings == null)
			{
				return;
			}
			int buildCategory = Config.buildCategory;
			MegaBuildingEntry[] buildings = Config.buildings;
			foreach (MegaBuildingEntry megaBuildingEntry in buildings)
			{
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(megaBuildingEntry.itemId);
				if (val == null)
				{
					ProjectEdenPlugin.Log.LogWarning((object)$"建造栏核对:物品 {megaBuildingEntry.itemId} 不存在");
					continue;
				}
				int num = val.BuildIndex / 100;
				int num2 = val.BuildIndex % 100;
				ItemProto val2 = ((num >= 0 && num < 16 && num2 >= 0 && num2 < 13) ? UIBuildMenu.protos[num, num2] : null);
				string text = ((val2 == null) ? "格位为空" : ((((Proto)val2).ID == megaBuildingEntry.itemId) ? "已就位" : $"被 {((Proto)val2).name}({((Proto)val2).ID}) 占用"));
				ProjectEdenPlugin.Log.LogInfo((object)($"  建造栏核对 {((Proto)val).name}:BuildIndex {val.BuildIndex} → 第 {num} 类第 {num2} 格,{text}" + $"(期望分类 {buildCategory},IsEntity={val.IsEntity},UnlockKey={val.UnlockKey})"));
			}
		}

		private static void ReportSpeedCeiling()
		{
			int num = 0;
			RecipeProto val = null;
			RecipeProto[] dataArray = ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray;
			foreach (RecipeProto val2 in dataArray)
			{
				if (val2 != null)
				{
					int num2 = val2.TimeSpend * 10000;
					if (num2 > num)
					{
						num = num2;
						val = val2;
					}
				}
			}
			ProjectEdenPlugin.Log.LogInfo((object)($"跑满全部配方所需的最低 speed:{num}(最长配方「{((val != null) ? ((Proto)val).name : null)}」)," + $"当前设定 {Config.assemblerSpeed},吞吐上限为每 tick 一个周期(60 周期/秒)"));
			if (Config.assemblerSpeed < num)
			{
				ProjectEdenPlugin.Log.LogWarning((object)$"当前 assemblerSpeed 低于 {num},最长的那些配方达不到每 tick 一个周期。");
			}
		}

		private static int ResolveModelId(int desired)
		{
			ModelProto[] dataArray = ((ProtoSet<ModelProto>)(object)LDB.models).dataArray;
			int num = dataArray.Length + 64;
			if (desired > 0 && desired < num && ((ProtoSet<ModelProto>)(object)LDB.models).Select(desired) == null && !IsTaken(desired))
			{
				return desired;
			}
			for (int num2 = num - 1; num2 > 0; num2--)
			{
				if (((ProtoSet<ModelProto>)(object)LDB.models).Select(num2) == null && !IsTaken(num2))
				{
					ProjectEdenPlugin.Log.LogWarning((object)($"期望的模型 ID {desired} 不可用(当前模型数 {dataArray.Length},可用上界 {num}),改用 {num2}。" + $"建议把 data/megabuildings.json 里对应的 modelId 固定为 {num2}——" + "模型 ID 会随建筑写进存档,日后浮动会让已建成的建筑显示异常。"));
					return num2;
				}
			}
			return -1;
		}

		private static bool IsTaken(int id)
		{
			return AssignedModelIds.ContainsValue(id);
		}

		private static void ProtoPreload()
		{
			for (int i = 0; i < ((ProtoSet<ItemProto>)(object)LDB.items).dataArray.Length; i++)
			{
				ItemProto obj = ((ProtoSet<ItemProto>)(object)LDB.items).dataArray[i];
				obj.recipes = null;
				obj.rawMats = null;
				obj.Preload(i);
			}
			for (int j = 0; j < ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray.Length; j++)
			{
				((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray[j].Preload(j);
			}
		}

		private static int GridIndexOf(MegaBuildingEntry entry)
		{
			return GridIndex(entry.gridRow, entry.gridCol);
		}

		internal static int GridIndex(int row, int col)
		{
			return _tabIndex * 1000 + row * 100 + col;
		}

		private static void AddItemProto(ItemProto source, MegaBuildingEntry entry, int modelId)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			LDBTool.PreAddProto((Proto)new ItemProto
			{
				ID = entry.itemId,
				Name = entry.displayName,
				Description = entry.description,
				Type = source.Type,
				StackSize = Config.stackSize,
				GridIndex = GridIndexOf(entry),
				BuildIndex = Config.buildCategory * 100 + entry.slot,
				ModelIndex = modelId,
				ModelCount = 1,
				HpMax = Config.hpMax,
				IsEntity = true,
				CanBuild = true,
				BuildMode = source.BuildMode,
				IconPath = "Assets/projecteden/" + entry.iconName,
				PreTechOverride = 0,
				UnlockKey = -1,
				Grade = 0,
				Upgrades = new int[0],
				DescFields = MergeDescFields(source, entry),
				prefabDesc = PrefabDesc.none,
				name = entry.displayName
			});
		}

		private static void AddRecipeProto(MegaBuildingEntry entry)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			RecipeProto val = new RecipeProto();
			((Proto)val).ID = entry.recipeId;
			((Proto)val).Name = entry.displayName;
			val.Description = entry.description;
			val.Type = (ERecipeType)4;
			val.Handcraft = true;
			val.Explicit = true;
			val.TimeSpend = ((entry.recipeTimeSpend > 0) ? entry.recipeTimeSpend : Config.recipeTimeSpend);
			val.Items = ((entry.recipeItems != null && entry.recipeItems.Length != 0) ? entry.recipeItems : Config.recipeItems);
			val.ItemCounts = ((entry.recipeItemCounts != null && entry.recipeItemCounts.Length != 0) ? entry.recipeItemCounts : Config.recipeItemCounts);
			val.Results = new int[1] { entry.itemId };
			val.ResultCounts = new int[1] { 1 };
			val.GridIndex = GridIndexOf(entry);
			val.IconPath = "Assets/projecteden/" + entry.iconName;
			val.preTech = null;
			((Proto)val).name = entry.displayName;
			LDBTool.PreAddProto((Proto)(object)val);
		}

		private static void ReportProceduralModels()
		{
			if (!_modelModeReported)
			{
				_modelModeReported = true;
				if (Config.proceduralModels)
				{
					ProjectEdenPlugin.Log.LogInfo((object)"巨型建筑:启用程序化模型,五座各用各的几何(只换网格,占地与传送带接口仍来自原版 prefab)");
				}
				else
				{
					ProjectEdenPlugin.Log.LogInfo((object)($"巨型建筑:程序化模型已关闭,五座共用原版模型 {Config.copyFromModelId} 并只靠染色区分。" + "要打开就改 megabuildings.json 的 proceduralModels"));
				}
			}
		}

		private static int SafeStorageKinds(int wanted)
		{
			int expandedIconKinds = StationExpandPatches.ExpandedIconKinds;
			if (expandedIconKinds <= 0 || wanted <= expandedIconKinds)
			{
				return wanted;
			}
			ProjectEdenPlugin.Log.LogWarning((object)($"巨型建筑的储物格数 {wanted} 超过了悬停信息框能撑住的 {expandedIconKinds} 格,已夹到 {expandedIconKinds}。" + "那个上限来自 stations.json 的 stationMaxItemKinds(icons 数组按它扩容),要更多格就把两个文件一起调大"));
			return expandedIconKinds;
		}

		private static void CopyModelProto(int oriId, int id, MegaBuildingEntry entry, Color color)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Expected O, but got Unknown
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			ModelProto val = ((ProtoSet<ModelProto>)(object)LDB.models).Select(oriId);
			if (val == null)
			{
				ProjectEdenPlugin.Log.LogError((object)$"找不到源模型 {oriId},{entry.displayName} 将没有外观");
				return;
			}
			ModelProto val2 = new ModelProto
			{
				ObjectType = val.ObjectType,
				RuinType = val.RuinType,
				RendererType = val.RendererType,
				HpMax = val.HpMax,
				PrefabPath = val.PrefabPath,
				Order = val.Order,
				ID = id,
				Name = id.ToString(),
				SID = ""
			};
			((Proto)val2).sid = "";
			PrefabDesc prefabDesc = val.prefabDesc;
			GameObject val3 = (Object.op_Implicit((Object)(object)prefabDesc.prefab) ? prefabDesc.prefab : Resources.Load<GameObject>(val.PrefabPath));
			GameObject val4 = (Object.op_Implicit((Object)(object)prefabDesc.colliderPrefab) ? prefabDesc.colliderPrefab : Resources.Load<GameObject>(val._colliderPath));
			ref PrefabDesc prefabDesc2 = ref val2.prefabDesc;
			prefabDesc2 = (PrefabDesc)(((Object)(object)val3 == (Object)null) ? ((object)PrefabDesc.none) : ((object)((!((Object)(object)val4 == (Object)null)) ? new PrefabDesc(id, val3, val4) : new PrefabDesc(id, val3))));
			Material[][] lodMaterials = prefabDesc2.lodMaterials;
			foreach (Material[] array in lodMaterials)
			{
				if (array == null)
				{
					continue;
				}
				for (int j = 0; j < array.Length; j++)
				{
					ref Material reference = ref array[j];
					if (!((Object)(object)reference == (Object)null))
					{
						reference = new Material(reference);
						reference.SetColor("_Color", color);
					}
				}
			}
			if (Config.proceduralModels && prefabDesc2.lodMeshes != null)
			{
				MegaBuildingMeshes.Apply(ref prefabDesc2, entry.itemId, entry.displayName);
			}
			prefabDesc2.modelIndex = id;
			prefabDesc2.hasBuildCollider = prefabDesc.hasBuildCollider;
			prefabDesc2.colliders = prefabDesc.colliders;
			prefabDesc2.buildCollider = prefabDesc.buildCollider;
			prefabDesc2.buildColliders = prefabDesc.buildColliders;
			prefabDesc2.colliderPrefab = prefabDesc.colliderPrefab;
			prefabDesc2.dragBuild = prefabDesc.dragBuild;
			prefabDesc2.dragBuildDist = prefabDesc.dragBuildDist;
			prefabDesc2.blueprintBoxSize = prefabDesc.blueprintBoxSize;
			prefabDesc2.roughHeight = prefabDesc.roughHeight;
			prefabDesc2.roughWidth = prefabDesc.roughWidth;
			prefabDesc2.roughRadius = prefabDesc.roughRadius;
			prefabDesc2.barHeight = prefabDesc.barHeight;
			prefabDesc2.barWidth = prefabDesc.barWidth;
			prefabDesc2.isAssembler = true;
			prefabDesc2.assemblerRecipeType = (ERecipeType)(byte)entry.recipeType;
			prefabDesc2.assemblerSpeed = Config.assemblerSpeed;
			prefabDesc2.isStation = Config.stationEnabled;
			prefabDesc2.isCollectStation = false;
			prefabDesc2.isVeinCollector = false;
			if (Config.stationEnabled)
			{
				prefabDesc2.stationMaxItemCount = Config.stationMaxItemCount;
				prefabDesc2.stationMaxItemKinds = SafeStorageKinds(Config.stationMaxItemKinds);
				prefabDesc2.stationMaxDroneCount = Config.stationMaxDroneCount;
				prefabDesc2.stationMaxEnergyAcc = Config.stationMaxEnergyAcc;
				prefabDesc2.stationMaxShipCount = 0;
			}
			prefabDesc2.idleEnergyPerTick = entry.idleEnergyPerTick;
			prefabDesc2.workEnergyPerTick = entry.workEnergyPerTick;
			ApplyGenerator(ref prefabDesc2, entry);
			LDBTool.PreAddProto((Proto)(object)val2);
		}

		private static void ApplyGenerator(ref PrefabDesc desc, MegaBuildingEntry entry)
		{
			MegaGeneratorEntry generator = entry.generator;
			if (generator != null && generator.genEnergyPerTick > 0)
			{
				if (generator.useFuelPerTick <= generator.genEnergyPerTick)
				{
					ProjectEdenPlugin.Log.LogError((object)($"「{entry.displayName}」的 useFuelPerTick({generator.useFuelPerTick}) 不大于 " + $"genEnergyPerTick({generator.genEnergyPerTick})——那是能量利用率 >= 100% 的永动机," + "发电段已忽略"));
					return;
				}
				desc.isPowerGen = true;
				desc.photovoltaic = false;
				desc.windForcedPower = false;
				desc.gammaRayReceiver = false;
				desc.geothermal = false;
				desc.genEnergyPerTick = generator.genEnergyPerTick;
				desc.useFuelPerTick = generator.useFuelPerTick;
				desc.fuelMask = ((generator.fuelMask > 0) ? generator.fuelMask : 32);
				desc.powerCatalystId = 0;
				ApplyGridHookup(ref desc, generator, entry);
				double num = (double)generator.genEnergyPerTick / (double)generator.useFuelPerTick;
				ProjectEdenPlugin.Log.LogInfo((object)($"「{entry.displayName}」同时是发电机:发电 {(double)(generator.genEnergyPerTick * 60) / 1000000000.0:0.##} GW," + $"耗燃料 {(double)(generator.useFuelPerTick * 60) / 1000000000.0:0.##} GW,能量利用率 {num:0.###}," + $"燃料掩码 {desc.fuelMask}"));
			}
		}

		private static int[] MergeDescFields(ItemProto source, MegaBuildingEntry entry)
		{
			int[] array = source.DescFields ?? new int[0];
			MegaGeneratorEntry generator = entry.generator;
			if (generator == null || generator.genEnergyPerTick <= 0)
			{
				return array;
			}
			int num = ((generator.connectFromItemId > 0) ? generator.connectFromItemId : 2204);
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(num);
			if (val?.DescFields == null || val.DescFields.Length == 0)
			{
				ProjectEdenPlugin.Log.LogWarning((object)($"「{entry.displayName}」:量不到原版电厂 {num} 的 DescFields," + "提示栏里不会有发电功率那一行"));
				return array;
			}
			List<int> list = new List<int>(array);
			int[] descFields = val.DescFields;
			foreach (int item in descFields)
			{
				if (!list.Contains(item))
				{
					list.Add(item);
				}
			}
			if (list.Count == array.Length)
			{
				return array;
			}
			ProjectEdenPlugin.Log.LogInfo((object)($"「{entry.displayName}」提示栏字段:{array.Length} 项 → {list.Count} 项" + "(并入「" + ((Proto)val).Name + "」的 " + string.Join("/", val.DescFields.Select((int x) => x.ToString()).ToArray()) + ")"));
			return list.ToArray();
		}

		private static void ApplyGridHookup(ref PrefabDesc desc, MegaGeneratorEntry gen, MegaBuildingEntry entry)
		{
			int num = ((gen.connectFromItemId > 0) ? gen.connectFromItemId : 2204);
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(num);
			PrefabDesc val2 = val?.prefabDesc;
			if (val2 == null)
			{
				ProjectEdenPlugin.Log.LogError((object)($"「{entry.displayName}」:量不到原版电厂 {num} 的 prefab," + "接电网的参数没抄过来——它会照常生产、照常耗电,但一度电都发不进电网"));
				return;
			}
			if (!val2.isPowerNode)
			{
				ProjectEdenPlugin.Log.LogWarning((object)($"「{entry.displayName}」:物品 {num}({((Proto)val).Name})的 isPowerNode 是 false," + "它大概不是一座发电建筑。接电网的参数仍会照抄,但很可能接不上——把 generator.connectFromItemId 指到一座真的电厂上"));
			}
			desc.isPowerNode = val2.isPowerNode;
			desc.powerConnectDistance = val2.powerConnectDistance;
			desc.powerCoverRadius = val2.powerCoverRadius;
			ProjectEdenPlugin.Log.LogInfo((object)($"「{entry.displayName}」接电网的参数量自「{((Proto)val).Name}」({num}):" + $"isPowerNode={desc.isPowerNode},连接距离 {desc.powerConnectDistance:0.##}," + $"覆盖半径 {desc.powerCoverRadius:0.##}"));
		}
	}
	internal static class OreRegistry
	{
		internal class Ore
		{
			internal OreEntry Entry;

			internal int OreItemId;

			internal int IngotItemId;

			internal int VeinModelId;

			internal int OreGrid;

			internal int IngotGrid;

			internal string OreIconPath;

			internal string IngotIconPath;

			internal readonly List<Recipe> Recipes = new List<Recipe>();

			internal int VeinId => Entry.veinId;

			internal bool HasIngot => Entry.hasIngot;

			internal string Key => Entry.key ?? Entry.oreName;
		}

		internal class Recipe
		{
			internal OreRecipeEntry Entry;

			internal int RecipeId;

			internal int Grid;
		}

		internal class ExtraItem
		{
			internal ExtraItemEntry Entry;

			internal int ItemId;

			internal int Grid;

			internal string Key => Entry.key ?? Entry.name;
		}

		private const int IronOreItemId = 1001;

		private const int IronIngotItemId = 1101;

		private const int IronVeinId = 1;

		private const string IconPrefix = "Assets/projecteden/";

		internal static readonly List<Ore> Ores = new List<Ore>();

		internal static readonly List<ExtraItem> ExtraItems = new List<ExtraItem>();

		internal static readonly List<Recipe> StandaloneRecipes = new List<Recipe>();

		private static bool _themesDumped;

		internal static OreConfig Config { get; private set; }

		internal static bool Enabled
		{
			get
			{
				if (Config != null && Config.enabled)
				{
					return Ores.Count > 0;
				}
				return false;
			}
		}

		internal static int MaxVeinId
		{
			get
			{
				int num = 0;
				for (int i = 0; i < Ores.Count; i++)
				{
					if (Ores[i].VeinId > num)
					{
						num = Ores[i].VeinId;
					}
				}
				return num;
			}
		}

		private static string IconPathOf(string icon)
		{
			if (!string.IsNullOrEmpty(icon))
			{
				return "Assets/projecteden/" + icon;
			}
			return null;
		}

		internal static bool IsCustomVein(int veinType)
		{
			for (int i = 0; i < Ores.Count; i++)
			{
				if (Ores[i].VeinId == veinType)
				{
					return true;
				}
			}
			return false;
		}

		internal static Ore Find(int veinType)
		{
			for (int i = 0; i < Ores.Count; i++)
			{
				if (Ores[i].VeinId == veinType)
				{
					return Ores[i];
				}
			}
			return null;
		}

		internal static void Load()
		{
			Config = JsonHelper.Load<OreConfig>("ores");
			if (Config == null)
			{
				ProjectEdenPlugin.Log.LogWarning((object)"读不到 ores.json,自定义矿脉未启用");
			}
			else if (!Config.enabled)
			{
				ProjectEdenPlugin.Log.LogInfo((object)"自定义矿脉已在配置里关闭");
			}
		}

		internal static void OnPreAddData()
		{
			Ores.Clear();
			ExtraItems.Clear();
			StandaloneRecipes.Clear();
			if (Config == null || !Config.enabled)
			{
				return;
			}
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(1001);
			ItemProto val2 = ((ProtoSet<ItemProto>)(object)LDB.items).Select(1101);
			if (val == null || val2 == null)
			{
				ProjectEdenPlugin.Log.LogError((object)$"找不到铁矿({1001})或铁块({1101}),自定义矿脉未注册");
				return;
			}
			AddExtraItems();
			if (Config.ores == null)
			{
				return;
			}
			OreEntry[] ores = Config.ores;
			foreach (OreEntry oreEntry in ores)
			{
				if (oreEntry == null || !oreEntry.enabled)
				{
					continue;
				}
				if (oreEntry.veinId <= 0)
				{
					ProjectEdenPlugin.Log.LogError((object)("矿种「" + oreEntry.oreName + "」没有配 veinId,跳过"));
					continue;
				}
				Ore ore = new Ore
				{
					Entry = oreEntry
				};
				ore.OreItemId = ResolveItemId(oreEntry.oreItemId, oreEntry.oreName);
				ore.OreGrid = ResolveGridIndex(oreEntry.oreGridIndex, oreEntry.oreName, ProtoSlots.GridKind.Item);
				ore.OreIconPath = IconPathOf(oreEntry.oreIcon) ?? val.IconPath;
				AddItem(ore.OreItemId, oreEntry.oreName, oreEntry.oreDescription, (EItemType)1, ore.OreGrid, val, oreEntry.stackSize, oreEntry.veinName, "", isFluid: false, ore.OreIconPath);
				ProtoSlots.ReserveItemId(ore.OreItemId);
				ProtoSlots.ReserveGrid(ore.OreGrid, ProtoSlots.GridKind.Item);
				if (oreEntry.hasIngot)
				{
					ore.IngotItemId = ResolveItemId(oreEntry.ingotItemId, oreEntry.ingotName);
					ore.IngotGrid = ResolveGridIndex(oreEntry.ingotGridIndex, oreEntry.ingotName, ProtoSlots.GridKind.Item, ore.OreGrid);
					ore.IngotIconPath = IconPathOf(oreEntry.ingotIcon) ?? val2.IconPath;
					AddItem(ore.IngotItemId, oreEntry.ingotName, oreEntry.ingotDescription, (EItemType)2, ore.IngotGrid, val2, oreEntry.stackSize, "", ProduceFrom(oreEntry), isFluid: false, ore.IngotIconPath);
					ProtoSlots.ReserveItemId(ore.IngotItemId);
					ProtoSlots.ReserveGrid(ore.IngotGrid, ProtoSlots.GridKind.Item);
				}
				CloneVeinModel(ore);
				Ores.Add(ore);
			}
			Ores.Sort((Ore a, Ore b) => a.VeinId.CompareTo(b.VeinId));
			foreach (Ore ore2 in Ores)
			{
				AddRecipes(ore2.Entry.recipes, ore2);
			}
			AddRecipes(Config.recipes, null);
			if (Ores.Count > 0)
			{
				ProjectEdenPlugin.Log.LogInfo((object)string.Format("自定义矿脉已注册 {0} 种:{1}", Ores.Count, string.Join("、", Ores.ConvertAll((Ore o) => $"{o.Entry.veinName}(矿种 {o.VeinId})").ToArray())));
			}
			VerifyContiguous();
		}

		private static string ProduceFrom(OreEntry entry)
		{
			if (!string.IsNullOrEmpty(entry.ingotProduceFrom))
			{
				return entry.ingotProduceFrom;
			}
			if (entry.recipes == null)
			{
				return "";
			}
			string text = "";
			OreRecipeEntry[] recipes = entry.recipes;
			foreach (OreRecipeEntry oreRecipeEntry in recipes)
			{
				if (oreRecipeEntry != null && oreRecipeEntry.enabled)
				{
					string text2 = MachineName(oreRecipeEntry.type);
					if (text2.Length != 0 && !text.Contains(text2))
					{
						text += ((text.Length == 0) ? text2 : (" / " + text2));
					}
				}
			}
			return text;
		}

		private static string MachineName(int recipeType)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected I4, but got Unknown
			ERecipeType val = (ERecipeType)(byte)recipeType;
			return (val - 1) switch
			{
				0 => "冶炼厂", 
				1 => "化工厂", 
				2 => "精炼厂", 
				3 => "制造台", 
				4 => "粒子对撞机", 
				_ => MachineRegistry.RecipeTypeMachineName(recipeType) ?? "", 
			};
		}

		private static void AddExtraItems()
		{
			if (Config.items == null)
			{
				return;
			}
			ExtraItemEntry[] items = Config.items;
			foreach (ExtraItemEntry extraItemEntry in items)
			{
				if (extraItemEntry == null || !extraItemEntry.enabled)
				{
					continue;
				}
				if (extraItemEntry.iconFrom <= 0 && !string.IsNullOrEmpty(extraItemEntry.iconFromName))
				{
					int num = VanillaItemIdByName(extraItemEntry.iconFromName);
					if (num > 0)
					{
						extraItemEntry.iconFrom = num;
						ProjectEdenPlugin.Log.LogInfo((object)$"物品「{extraItemEntry.name}」的 proto 模板按名字反查到「{extraItemEntry.iconFromName}」= {num}");
					}
					else
					{
						ProjectEdenPlugin.Log.LogError((object)("物品「" + extraItemEntry.name + "」的 iconFromName「" + extraItemEntry.iconFromName + "」在原版里找不到。比的是 ItemProto.Name(原始中文键)不是翻译后的名字,检查有没有写错字"));
					}
				}
				ItemProto val = (ProtoSlots.ItemIdTaken(extraItemEntry.iconFrom) ? ((ProtoSet<ItemProto>)(object)LDB.items).Select(extraItemEntry.iconFrom) : null);
				if (val == null)
				{
					ProjectEdenPlugin.Log.LogError((object)($"物品「{extraItemEntry.name}」没有可用的 proto 模板:iconFrom = {extraItemEntry.iconFrom}," + "在原版里找不到。整条物品跳过,所有引用它的配方也会跟着失败。\n  **iconFrom 不只是图标来源,它是克隆模板**(要靠它抄 DescFields 等数组字段),所以即使自带了 icon 也必须填一个真实存在的原版物品号"));
					continue;
				}
				ExtraItem extraItem = new ExtraItem
				{
					Entry = extraItemEntry
				};
				extraItem.ItemId = ResolveItemId(extraItemEntry.itemId, extraItemEntry.name);
				extraItem.Grid = ResolveGridIndex(extraItemEntry.gridIndex, extraItemEntry.name, ProtoSlots.GridKind.Item);
				ItemProto obj = AddItem(extraItem.ItemId, extraItemEntry.name, extraItemEntry.description, (EItemType)2, extraItem.Grid, val, extraItemEntry.stackSize, extraItemEntry.miningFrom ?? "", extraItemEntry.produceFrom, extraItemEntry.isFluid, IconPathOf(extraItemEntry.icon) ?? val.IconPath);
				ApplyFuel(obj, extraItemEntry);
				ApplyProliferator(obj, extraItemEntry);
				ProtoSlots.ReserveItemId(extraItem.ItemId);
				ProtoSlots.ReserveGrid(extraItem.Grid, ProtoSlots.GridKind.Item);
				ExtraItems.Add(extraItem);
			}
			if (ExtraItems.Count > 0)
			{
				ProjectEdenPlugin.Log.LogInfo((object)string.Format("额外物品已注册 {0} 个:{1}", ExtraItems.Count, string.Join("、", ExtraItems.ConvertAll((ExtraItem x) => $"{x.Entry.name}({x.ItemId})").ToArray())));
			}
		}

		private static void VerifyContiguous()
		{
			if (Ores.Count == 0)
			{
				return;
			}
			List<int> list = new List<int>();
			foreach (Ore ore in Ores)
			{
				list.Add(ore.VeinId);
			}
			list.Sort();
			int num = 15;
			foreach (int item in list)
			{
				if (item == num)
				{
					num++;
					continue;
				}
				ProjectEdenPlugin.Log.LogError((object)($"矿种编号不连续:期望 {num},配置里是 {item}。" + "原版星球详情面板遍历矿种时会先解引用再判空,空号会让面板一打开就崩。请把 ores.json 里的 veinId 从 15 开始连续排。"));
				break;
			}
		}

		private static void VerifyVeinArrayOrder()
		{
			VeinProto[] array = ((ProtoSet<VeinProto>)(object)LDB.veins)?.dataArray;
			if (array == null || array.Length == 0)
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			VeinProto[] array2 = array;
			foreach (VeinProto val in array2)
			{
				if (val != null)
				{
					if (((Proto)val).ID > num)
					{
						num = ((Proto)val).ID;
					}
					num2 = ((Proto)val).ID;
				}
			}
			if (num2 >= num)
			{
				ProjectEdenPlugin.Log.LogInfo((object)($"矿脉表核对通过:共 {array.Length} 条,最大编号 {num},末位 {num2}," + $"PrepareWorks 会按 {num + 1} 定容"));
			}
			else
			{
				ProjectEdenPlugin.Log.LogError((object)($"矿脉表的末位是 {num2} 而最大编号是 {num}——**游戏会在启动时崩**。" + "原版 PlanetModelingManager.PrepareWorks 按<b>最后一个</b>元素的 ID+1 定容(那一句是赋值不是取最大值),然后按 ID 逐个写," + $"写到 {num} 号时越界,堆栈只指向 PrepareWorks 不指向本 mod。" + "检查 ores.json 里 veinId 的顺序,或者是否有别的 mod 往矿脉表里加了东西。"));
			}
		}

		private static void CloneVeinModel(Ore ore)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Expected O, but got Unknown
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Expected O, but got Unknown
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Expected O, but got Unknown
			//IL_0292: Unknown result type (might be due to invalid IL or missing references)
			ore.VeinModelId = 0;
			VeinProto val = ((ProtoSet<VeinProto>)(object)LDB.veins).Select(1);
			ModelProto val2 = ((val == null) ? null : ((ProtoSet<ModelProto>)(object)LDB.models).Select(val.ModelIndex));
			if (val2 == null)
			{
				ProjectEdenPlugin.Log.LogWarning((object)("找不到铁矿脉的模型," + ore.Entry.veinName + "将沿用铁矿脉的外观"));
				return;
			}
			int num = ProtoSlots.ResolveModelId(ore.Entry.veinModelId, ore.Entry.veinName);
			ProtoSlots.ReserveModelId(num);
			if (num <= 0)
			{
				ProjectEdenPlugin.Log.LogWarning((object)("没有可用的模型 ID," + ore.Entry.veinName + "将沿用铁矿脉的外观"));
				return;
			}
			ModelProto val3 = new ModelProto
			{
				ObjectType = val2.ObjectType,
				RuinType = val2.RuinType,
				RendererType = val2.RendererType,
				HpMax = val2.HpMax,
				PrefabPath = val2.PrefabPath,
				Order = val2.Order,
				ID = num,
				Name = num.ToString(),
				SID = ""
			};
			((Proto)val3).sid = "";
			PrefabDesc prefabDesc = val2.prefabDesc;
			GameObject val4 = (Object.op_Implicit((Object)(object)prefabDesc.prefab) ? prefabDesc.prefab : Resources.Load<GameObject>(val2.PrefabPath));
			GameObject val5 = (Object.op_Implicit((Object)(object)prefabDesc.colliderPrefab) ? prefabDesc.colliderPrefab : Resources.Load<GameObject>(val2._colliderPath));
			if ((Object)(object)val4 == (Object)null)
			{
				ProjectEdenPlugin.Log.LogWarning((object)$"铁矿脉模型 {val.ModelIndex} 没有 prefab,{ore.Entry.veinName}将沿用铁矿脉的外观");
				return;
			}
			ref PrefabDesc prefabDesc2 = ref val3.prefabDesc;
			prefabDesc2 = (((Object)(object)val5 == (Object)null) ? new PrefabDesc(num, val4) : new PrefabDesc(num, val4, val5));
			prefabDesc2.modelIndex = num;
			prefabDesc2.colliders = prefabDesc.colliders;
			prefabDesc2.buildCollider = prefabDesc.buildCollider;
			prefabDesc2.buildColliders = prefabDesc.buildColliders;
			prefabDesc2.colliderPrefab = prefabDesc.colliderPrefab;
			prefabDesc2.hasBuildCollider = prefabDesc.hasBuildCollider;
			prefabDesc2.roughHeight = prefabDesc.roughHeight;
			prefabDesc2.roughWidth = prefabDesc.roughWidth;
			prefabDesc2.roughRadius = prefabDesc.roughRadius;
			Color val6 = TintColor(ore.Entry);
			int num2 = 0;
			StringBuilder stringBuilder = new StringBuilder();
			Material[][] lodMaterials = prefabDesc2.lodMaterials;
			foreach (Material[] array in lodMaterials)
			{
				if (array == null)
				{
					continue;
				}
				for (int j = 0; j < array.Length; j++)
				{
					ref Material reference = ref array[j];
					if (!((Object)(object)reference == (Object)null))
					{
						reference = new Material(reference);
						num2 += TintMaterial(reference, val6, stringBuilder);
					}
				}
			}
			LDBTool.PreAddProto((Proto)(object)val3);
			ore.VeinModelId = num;
			ProjectEdenPlugin.Log.LogInfo((object)($"{ore.Entry.veinName}模型已克隆自铁矿脉模型 {val.ModelIndex} → {num},染色 {num2} 个颜色属性" + $"(R×{val6.r:0.##} G×{val6.g:0.##} B×{val6.b:0.##}){stringBuilder}"));
			if (num2 == 0)
			{
				ProjectEdenPlugin.Log.LogWarning((object)"矿脉材质里一个颜色属性都没有,颜色改不掉——上面那行列出了它实际有哪些属性");
			}
		}

		private static int TintMaterial(Material material, Color tint, StringBuilder report)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			Shader shader = material.shader;
			if ((Object)(object)shader == (Object)null)
			{
				return 0;
			}
			int num = 0;
			int propertyCount = shader.GetPropertyCount();
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < propertyCount; i++)
			{
				string propertyName = shader.GetPropertyName(i);
				ShaderPropertyType propertyType = shader.GetPropertyType(i);
				if ((int)propertyType == 0)
				{
					material.SetColor(propertyName, material.GetColor(propertyName) * tint);
					num++;
				}
				else
				{
					stringBuilder.Append(propertyName).Append('(').Append(propertyType)
						.Append(") ");
				}
			}
			if (num == 0 && report.Length < 600)
			{
				report.Append(" | 着色器 ").Append(((Object)shader).name).Append(" 的属性:")
					.Append((object?)stringBuilder);
			}
			return num;
		}

		private static Color TintColor(OreEntry entry)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			float[] veinTint = entry.veinTint;
			if (veinTint == null || veinTint.Length < 3)
			{
				return Color.white;
			}
			return new Color(veinTint[0], veinTint[1], veinTint[2]);
		}

		private static ItemProto AddItem(int id, string displayName, string description, EItemType type, int gridIndex, ItemProto source, int stackSize, string miningFrom, string produceFrom, bool isFluid, string iconPath)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			//IL_00c3: Expected O, but got Unknown
			ItemProto val = new ItemProto
			{
				ID = id,
				Name = displayName,
				Description = description,
				Type = type,
				GridIndex = gridIndex,
				StackSize = ((stackSize > 0) ? stackSize : source.StackSize),
				MiningFrom = miningFrom,
				ProduceFrom = produceFrom,
				IconPath = iconPath,
				IsFluid = isFluid,
				CanBuild = false,
				BuildIndex = 0,
				FuelType = 0,
				HeatValue = 0L,
				Grade = 0,
				Upgrades = new int[0],
				UnlockKey = -1,
				PreTechOverride = 0,
				DescFields = source.DescFields,
				prefabDesc = PrefabDesc.none,
				name = displayName
			};
			LDBTool.PreAddProto((Proto)val);
			return val;
		}

		private static void ApplyProliferator(ItemProto proto, ExtraItemEntry entry)
		{
			if (entry.ability > 0 || entry.hpMax > 0)
			{
				if (entry.ability <= 0 || entry.hpMax <= 0)
				{
					ProjectEdenPlugin.Log.LogError((object)($"物品「{entry.name}」的 ability({entry.ability}) 和 hpMax({entry.hpMax}) " + "只配了一半,增产剂两个都得有,已跳过"));
					return;
				}
				proto.Ability = entry.ability;
				proto.HpMax = entry.hpMax;
				ProjectEdenPlugin.Log.LogInfo((object)$"「{entry.name}」是增产剂:等级 {entry.ability},一份喷 {entry.hpMax} 件");
			}
		}

		private static void ApplyFuel(ItemProto item, ExtraItemEntry entry)
		{
			if (item != null && (entry.fuelType != 0 || entry.heatValue != 0L))
			{
				if (entry.fuelType == 0 || entry.heatValue <= 0)
				{
					ProjectEdenPlugin.Log.LogWarning((object)($"物品「{entry.name}」的 fuelType={entry.fuelType}、heatValue={entry.heatValue} 只配了一半," + "两个都要有才烧得起来,已忽略"));
					return;
				}
				item.FuelType = entry.fuelType;
				item.HeatValue = entry.heatValue;
				ProjectEdenPlugin.Log.LogInfo((object)$"「{entry.name}」可作燃料:类型 {entry.fuelType},热值 {(double)entry.heatValue / 1000000.0:0.##} MJ");
			}
		}

		private static void AddRecipes(OreRecipeEntry[] entries, Ore owner)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			if (entries == null)
			{
				return;
			}
			foreach (OreRecipeEntry oreRecipeEntry in entries)
			{
				if (oreRecipeEntry != null && oreRecipeEntry.enabled && BuildSide(oreRecipeEntry.items, owner, oreRecipeEntry.name, "原料", out var ids, out var counts, allowEmpty: true) && BuildSide(oreRecipeEntry.results, owner, oreRecipeEntry.name, "产物", out var ids2, out var counts2))
				{
					Recipe recipe = new Recipe
					{
						Entry = oreRecipeEntry
					};
					recipe.RecipeId = ResolveRecipeId(oreRecipeEntry.recipeId, oreRecipeEntry.name);
					recipe.Grid = ResolveGridIndex(oreRecipeEntry.gridIndex, oreRecipeEntry.name, ProtoSlots.GridKind.Recipe);
					LDBTool.PreAddProto((Proto)new RecipeProto
					{
						ID = recipe.RecipeId,
						Name = oreRecipeEntry.name,
						Description = oreRecipeEntry.description,
						Type = (ERecipeType)(byte)oreRecipeEntry.type,
						Handcraft = false,
						Explicit = true,
						TimeSpend = oreRecipeEntry.timeSpend,
						Items = ids,
						ItemCounts = counts,
						Results = ids2,
						ResultCounts = counts2,
						GridIndex = recipe.Grid,
						IconPath = (IconPathOf(oreRecipeEntry.icon) ?? ((oreRecipeEntry.iconFrom <= 0) ? null : ((ProtoSet<ItemProto>)(object)LDB.items).Select(oreRecipeEntry.iconFrom)?.IconPath) ?? owner?.IngotIconPath ?? owner?.OreIconPath),
						preTech = null,
						name = oreRecipeEntry.name
					});
					MegaBuildingRegistry.RecipeIds.Add(recipe.RecipeId);
					ProtoSlots.ReserveRecipeId(recipe.RecipeId);
					ProtoSlots.ReserveGrid(recipe.Grid, ProtoSlots.GridKind.Recipe);
					if (owner != null)
					{
						owner.Recipes.Add(recipe);
					}
					else
					{
						StandaloneRecipes.Add(recipe);
					}
					ProjectEdenPlugin.Log.LogInfo((object)($"配方「{oreRecipeEntry.name}」已注册:ID {recipe.RecipeId},{MachineName(oreRecipeEntry.type)}," + $"{Describe(ids, counts)} → {Describe(ids2, counts2)},{(float)oreRecipeEntry.timeSpend / 60f:0.##} 秒"));
				}
			}
		}

		private static string Describe(int[] ids, int[] counts)
		{
			string text = "";
			for (int i = 0; i < ids.Length; i++)
			{
				if (i > 0)
				{
					text += " + ";
				}
				text += $"{NameOf(ids[i])}×{counts[i]}";
			}
			return text;
		}

		private static string NameOf(int id)
		{
			foreach (ExtraItem extraItem in ExtraItems)
			{
				if (extraItem.ItemId == id)
				{
					return extraItem.Entry.name;
				}
			}
			foreach (Ore ore in Ores)
			{
				if (ore.OreItemId == id)
				{
					return ore.Entry.oreName;
				}
				if (ore.HasIngot && ore.IngotItemId == id)
				{
					return ore.Entry.ingotName;
				}
			}
			ItemProto obj = ((ProtoSet<ItemProto>)(object)LDB.items).Select(id);
			return ((obj != null) ? ((Proto)obj).name : null) ?? id.ToString();
		}

		private static bool BuildSide(RecipeItemEntry[] side, Ore owner, string recipeName, string label, out int[] ids, out int[] counts, bool allowEmpty = false)
		{
			ids = null;
			counts = null;
			if (side == null || side.Length == 0)
			{
				if (!allowEmpty)
				{
					ProjectEdenPlugin.Log.LogError((object)("配方「" + recipeName + "」没有配" + label + ",跳过"));
					return false;
				}
				ProjectEdenPlugin.Log.LogInfo((object)("配方「" + recipeName + "」是零原料配方——" + label + "一格都没有,这是配置里写明的"));
				ids = new int[0];
				counts = new int[0];
				return true;
			}
			ids = new int[side.Length];
			counts = new int[side.Length];
			for (int i = 0; i < side.Length; i++)
			{
				int num = ResolveRef(side[i], owner, recipeName, label);
				if (num <= 0)
				{
					return false;
				}
				ids[i] = num;
				counts[i] = ((side[i].count <= 0) ? 1 : side[i].count);
			}
			return true;
		}

		internal static int FindItemIdByRef(string @ref)
		{
			if (string.IsNullOrEmpty(@ref))
			{
				return 0;
			}
			foreach (ExtraItem extraItem in ExtraItems)
			{
				if (extraItem.Key == @ref)
				{
					return extraItem.ItemId;
				}
			}
			foreach (Ore ore in Ores)
			{
				if (@ref == ore.Key + ".ore")
				{
					return ore.OreItemId;
				}
				if (@ref == ore.Key + ".ingot" && ore.HasIngot)
				{
					return ore.IngotItemId;
				}
			}
			return VanillaIdByName(@ref);
		}

		private static int VanillaIdByName(string @ref)
		{
			if (@ref == null || !@ref.StartsWith("vanilla:", StringComparison.Ordinal))
			{
				return 0;
			}
			return VanillaItemIdByName(@ref.Substring("vanilla:".Length));
		}

		internal static int VanillaItemIdByName(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return 0;
			}
			ItemProto[] dataArray = ((ProtoSet<ItemProto>)(object)LDB.items).dataArray;
			foreach (ItemProto val in dataArray)
			{
				if (val != null && ((Proto)val).Name == name)
				{
					return ((Proto)val).ID;
				}
			}
			return 0;
		}

		private static int ResolveRef(RecipeItemEntry item, Ore owner, string recipeName, string label)
		{
			if (string.IsNullOrEmpty(item.@ref))
			{
				if (item.id > 0 && ProtoSlots.ItemIdTaken(item.id))
				{
					return item.id;
				}
				ProjectEdenPlugin.Log.LogError((object)$"配方「{recipeName}」的{label}里,物品 ID {item.id} 在原版里不存在,整条配方跳过");
				return 0;
			}
			if (item.@ref == "ore" || item.@ref == "ingot")
			{
				if (owner == null)
				{
					ProjectEdenPlugin.Log.LogError((object)("配方「" + recipeName + "」在顶层 recipes 段里,没有「本矿种」可言," + label + "不能引用 " + item.@ref + "——请改写成 items 段的 key 或「矿种key.ore」这样的全名。整条配方跳过"));
					return 0;
				}
				if (item.@ref == "ore")
				{
					return owner.OreItemId;
				}
				if (owner.HasIngot)
				{
					return owner.IngotItemId;
				}
				ProjectEdenPlugin.Log.LogError((object)("配方「" + recipeName + "」引用了 ingot,但矿种「" + owner.Key + "」的 hasIngot 是 false,整条配方跳过"));
				return 0;
			}
			foreach (ExtraItem extraItem in ExtraItems)
			{
				if (extraItem.Key == item.@ref)
				{
					return extraItem.ItemId;
				}
			}
			foreach (Ore ore in Ores)
			{
				if (item.@ref == ore.Key + ".ore")
				{
					return ore.OreItemId;
				}
				if (item.@ref == ore.Key + ".ingot" && ore.HasIngot)
				{
					return ore.IngotItemId;
				}
			}
			int num = VanillaIdByName(item.@ref);
			if (num > 0)
			{
				ProjectEdenPlugin.Log.LogInfo((object)$"配方「{recipeName}」的{label}按名字解析到原版物品:{[email protected](8)} = {num}");
				return num;
			}
			ProjectEdenPlugin.Log.LogError((object)("配方「" + recipeName + "」的" + label + "里,引用名「" + item.@ref + "」解析不出物品——它得是 ore / ingot、ores.json 里 items 段某条的 key、别的矿种的 key 加 .ore / .ingot 后缀,或者 vanilla: 加原版物品的中文名。整条配方跳过"));
			return 0;
		}

		private static void ApplyVanillaHeat()
		{
			VanillaHeatConfig vanillaHeatConfig = Config?.vanillaHeat;
			if (vanillaHeatConfig == null || !vanillaHeatConfig.enabled || vanillaHeatConfig.items == null || vanillaHeatConfig.items.Length == 0)
			{
				ProjectEdenPlugin.Log.LogInfo((object)"原版热值改写:未启用,原版燃料保持原值");
				return;
			}
			int num = 0;
			VanillaHeatEntry[] items = vanillaHeatConfig.items;
			foreach (VanillaHeatEntry vanillaHeatEntry in items)
			{
				if (vanillaHeatEntry == null || vanillaHeatEntry.id <= 0)
				{
					continue;
				}
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(vanillaHeatEntry.id);
				if (val == null)
				{
					ProjectEdenPlugin.Log.LogError((object)$"原版热值改写:找不到物品 {vanillaHeatEntry.id},跳过");
					continue;
				}
				if (!string.IsNullOrEmpty(vanillaHeatEntry.name) && ((Proto)val).Name != vanillaHeatEntry.n