1
0
mirror of https://github.com/soarqin/DSP_Mods.git synced 2025-12-09 12:53:34 +08:00

code cleanup

This commit is contained in:
2023-12-14 21:52:35 +08:00
parent aa5d8a2454
commit 51f35bb573
28 changed files with 318 additions and 466 deletions

View File

@@ -233,7 +233,7 @@ public static class FactoryPatch
} }
var labels = matcher.Labels; var labels = matcher.Labels;
matcher.Labels = new List<Label>(); matcher.Labels = [];
matcher.Insert( matcher.Insert(
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels), new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),
new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(BuildTool), nameof(BuildTool.factory))), new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(BuildTool), nameof(BuildTool.factory))),
@@ -608,7 +608,7 @@ public static class FactoryPatch
_portalFrom[v] = number; _portalFrom[v] = number;
if (!_portalTo.TryGetValue(number, out var set)) if (!_portalTo.TryGetValue(number, out var set))
{ {
set = new HashSet<long>(); set = [];
_portalTo[number] = set; _portalTo[number] = set;
} }
@@ -1166,7 +1166,7 @@ public static class FactoryPatch
new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.capacityCurrentTick))) new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.capacityCurrentTick)))
); );
var labels = matcher.Labels; var labels = matcher.Labels;
matcher.Labels = new List<Label>(); matcher.Labels = [];
matcher.Insert( matcher.Insert(
// if (this.fuelMask == 4) // if (this.fuelMask == 4)
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels), new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),

View File

@@ -123,7 +123,7 @@ public static class TechPatch
} }
else if (VFInput.alt) else if (VFInput.alt)
{ {
UnlockTechRecursive(node.techProto, 10000); UnlockTechRecursive(node.techProto);
} }
} }

View File

@@ -125,7 +125,7 @@ public class PatchSave
public static void CreateCompressBuffer() public static void CreateCompressBuffer()
{ {
const int bufSize = CompressionStream.MB; const int bufSize = CompressionStream.Mb;
var outBufSize = LZ4Wrapper.CompressBufferBound(bufSize); var outBufSize = LZ4Wrapper.CompressBufferBound(bufSize);
outBufSize = Math.Max(outBufSize, ZstdWrapper.CompressBufferBound(bufSize)); outBufSize = Math.Max(outBufSize, ZstdWrapper.CompressBufferBound(bufSize));
outBufSize = Math.Max(outBufSize, NoneWrapper.CompressBufferBound(bufSize)); outBufSize = Math.Max(outBufSize, NoneWrapper.CompressBufferBound(bufSize));
@@ -260,7 +260,7 @@ public class PatchSave
Stream stream = null; Stream stream = null;
if (writeflag && _compressionTypeForSaving == CompressionType.None) if (writeflag && _compressionTypeForSaving == CompressionType.None)
{ {
stream = ((CompressionStream)_compressionStream).outStream; stream = ((CompressionStream)_compressionStream).OutStream;
} }
// Dispose need to be done before fstream closed. // Dispose need to be done before fstream closed.
_compressionStream.Dispose(); _compressionStream.Dispose();
@@ -378,7 +378,7 @@ public class PatchSave
case CompressionType.LZ4: case CompressionType.LZ4:
case CompressionType.Zstd: case CompressionType.Zstd:
while (offset > 0) while (offset > 0)
offset -= _compressionStream.Read(_compressBuffer.outBuffer, 0, (int)offset); offset -= _compressionStream.Read(_compressBuffer.OutBuffer, 0, (int)offset);
return _compressionStream.Position; return _compressionStream.Position;
case CompressionType.None: case CompressionType.None:
return fileStream.Seek(offset, origin); return fileStream.Seek(offset, origin);

View File

@@ -18,10 +18,9 @@ public static class I18N
public static bool Initialized() => _initialized; public static bool Initialized() => _initialized;
private static int _nextID = 1; private static int _nextID = 1;
private static readonly List<StringProto> StringsToAdd = new(); private static readonly List<StringProto> StringsToAdd = [];
public static void Add(string key, string enus, string zhcn = null, string frfr = null) public static void Add(string key, string enus, string zhcn = null, string frfr = null)
{ {
var strings = LDB._strings;
var strProto = new StringProto var strProto = new StringProto
{ {
Name = key, Name = key,

View File

@@ -45,12 +45,14 @@ class PatchUILoadGame
if (created) if (created)
{ {
var rtrans = (RectTransform)__instance.loadSandboxGroup.transform; var rtrans = (RectTransform)__instance.loadSandboxGroup.transform;
var pos = rtrans.anchoredPosition3D; var anchoredPosition3D = rtrans.anchoredPosition3D;
rtrans.anchoredPosition3D = new Vector3(pos.x - 230, pos.y, pos.z); var pos = anchoredPosition3D;
anchoredPosition3D = new Vector3(pos.x - 230, pos.y, pos.z);
_decompressButton.gameObject.name = "button-decompress"; _decompressButton.gameObject.name = "button-decompress";
rtrans = (RectTransform)_decompressButton.transform; rtrans = (RectTransform)_decompressButton.transform;
pos = rtrans.anchoredPosition3D; pos = anchoredPosition3D;
rtrans.anchoredPosition3D = new Vector3(pos.x - 180, pos.y, pos.z); anchoredPosition3D = new Vector3(pos.x - 180, pos.y, pos.z);
rtrans.anchoredPosition3D = anchoredPosition3D;
_decompressButton.button.image.color = new Color32(0, 0xf4, 0x92, 0x77); _decompressButton.button.image.color = new Color32(0, 0xf4, 0x92, 0x77);
var textTrans = _decompressButton.transform.Find("button-text"); var textTrans = _decompressButton.transform.Find("button-text");
var text = textTrans.GetComponent<Text>(); var text = textTrans.GetComponent<Text>();

View File

@@ -1,4 +1,3 @@
using System.Collections.Generic;
using HarmonyLib; using HarmonyLib;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
@@ -142,7 +141,7 @@ static class PatchUISaveGame
var cb = cbctrl.GetComponent<UIComboBox>(); var cb = cbctrl.GetComponent<UIComboBox>();
cb.onSubmit.RemoveAllListeners(); cb.onSubmit.RemoveAllListeners();
cb.onItemIndexChange.RemoveAllListeners(); cb.onItemIndexChange.RemoveAllListeners();
cb.Items = new List<string> { "Store".Translate(), "LZ4", "Zstd" }; cb.Items = ["Store".Translate(), "LZ4", "Zstd"];
cb.itemIndex = (int)PatchSave.CompressionTypeForSaves; cb.itemIndex = (int)PatchSave.CompressionTypeForSaves;
cb.onItemIndexChange.AddListener(()=> cb.onItemIndexChange.AddListener(()=>
{ {
@@ -198,7 +197,7 @@ static class PatchUISaveGame
var cb = cbctrl.GetComponent<UIComboBox>(); var cb = cbctrl.GetComponent<UIComboBox>();
cb.onSubmit.RemoveAllListeners(); cb.onSubmit.RemoveAllListeners();
cb.onItemIndexChange.RemoveAllListeners(); cb.onItemIndexChange.RemoveAllListeners();
cb.Items = new List<string> { "已停用".Translate(), "Store".Translate(), "LZ4", "Zstd" }; cb.Items = ["已停用".Translate(), "Store".Translate(), "LZ4", "Zstd"];
cb.itemIndex = PatchSave.EnableForAutoSaves.Value ? (int)PatchSave.CompressionTypeForAutoSaves + 1 : 0; cb.itemIndex = PatchSave.EnableForAutoSaves.Value ? (int)PatchSave.CompressionTypeForAutoSaves + 1 : 0;
cb.onItemIndexChange.AddListener(() => cb.onItemIndexChange.AddListener(() =>
{ {

View File

@@ -5,7 +5,7 @@ namespace CompressSave.Wrapper;
class BlackHoleStream : Stream class BlackHoleStream : Stream
{ {
private long length; private long _length;
public override bool CanRead => true; public override bool CanRead => true;
@@ -13,18 +13,13 @@ class BlackHoleStream : Stream
public override bool CanWrite => true; public override bool CanWrite => true;
public override long Length => length; public override long Length => _length;
public override long Position { get; set; } public override long Position { get; set; }
public BlackHoleStream()
{
}
public override void Flush() public override void Flush()
{ {
;
} }
public override int Read(byte[] buffer, int offset, int count) public override int Read(byte[] buffer, int offset, int count)
@@ -39,12 +34,13 @@ class BlackHoleStream : Stream
public override void SetLength(long value) public override void SetLength(long value)
{ {
length = value; _length = value;
} }
public byte[] testBuffer = new byte[1024 * 1024];
private readonly byte[] _testBuffer = new byte[1024 * 1024];
public override void Write(byte[] buffer, int offset, int count) public override void Write(byte[] buffer, int offset, int count)
{ {
Array.Copy(buffer, offset, testBuffer, 0, Math.Min(count, testBuffer.Length)); Array.Copy(buffer, offset, _testBuffer, 0, Math.Min(count, _testBuffer.Length));
} }
} }

View File

@@ -7,21 +7,21 @@ namespace CompressSave.Wrapper;
public unsafe class BufferWriter : BinaryWriter public unsafe class BufferWriter : BinaryWriter
{ {
ByteSpan currentBuffer => doubleBuffer.writeBuffer; private ByteSpan CurrentBuffer => _doubleBuffer.WriteBuffer;
DoubleBuffer doubleBuffer; private readonly DoubleBuffer _doubleBuffer;
private Encoding _encoding; private readonly Encoding _encoding;
private int maxBytesPerChar; private readonly int _maxBytesPerChar;
byte[] Buffer => currentBuffer.Buffer; private byte[] Buffer => CurrentBuffer.Buffer;
long SuplusCapacity => endPos - curPos; private long SuplusCapacity => _endPos - _curPos;
long swapedBytes = 0; private long _swapedBytes;
public long WriteSum => swapedBytes + curPos - startPos; public long WriteSum => _swapedBytes + _curPos - _startPos;
public override Stream BaseStream => _baseStream; public override Stream BaseStream => _baseStream;
@@ -29,16 +29,16 @@ public unsafe class BufferWriter : BinaryWriter
{ {
if (chars == null) if (chars == null)
{ {
throw new ArgumentNullException("chars"); throw new ArgumentNullException(nameof(chars));
} }
byte[] bytes = _encoding.GetBytes(chars, index, count); byte[] bytes = _encoding.GetBytes(chars, index, count);
Write(bytes); Write(bytes);
} }
byte* curPos; private byte* _curPos;
byte* endPos; private byte* _endPos;
byte* startPos; private byte* _startPos;
private Stream _baseStream; private readonly Stream _baseStream;
public BufferWriter(DoubleBuffer doubleBuffer, CompressionStream outStream) public BufferWriter(DoubleBuffer doubleBuffer, CompressionStream outStream)
: this(doubleBuffer, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), outStream) : this(doubleBuffer, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), outStream)
@@ -46,34 +46,34 @@ public unsafe class BufferWriter : BinaryWriter
} }
BufferWriter(DoubleBuffer buffer , UTF8Encoding encoding, CompressionStream outStream) : base(Stream.Null, encoding) private BufferWriter(DoubleBuffer buffer , UTF8Encoding encoding, CompressionStream outStream) : base(Stream.Null, encoding)
{ {
_baseStream = outStream; _baseStream = outStream;
swapedBytes = 0; _swapedBytes = 0;
doubleBuffer = buffer; _doubleBuffer = buffer;
RefreshStatus(); RefreshStatus();
_encoding = encoding; _encoding = encoding;
maxBytesPerChar = _encoding.GetMaxByteCount(1); _maxBytesPerChar = _encoding.GetMaxByteCount(1);
} }
void SwapBuffer() private void SwapBuffer()
{ {
currentBuffer.Position = 0; CurrentBuffer.Position = 0;
currentBuffer.Length = (int)(curPos - startPos); CurrentBuffer.Length = (int)(_curPos - _startPos);
swapedBytes += currentBuffer.Length; _swapedBytes += CurrentBuffer.Length;
doubleBuffer.SwapBuffer(); _doubleBuffer.SwapBuffer();
RefreshStatus(); RefreshStatus();
} }
void RefreshStatus() private void RefreshStatus()
{ {
startPos = (byte*)Unsafe.AsPointer(ref Buffer[0]); _startPos = (byte*)Unsafe.AsPointer(ref Buffer[0]);
curPos = startPos; _curPos = _startPos;
endPos = (byte*)Unsafe.AsPointer(ref Buffer[Buffer.Length - 1]) + 1; _endPos = (byte*)Unsafe.AsPointer(ref Buffer[Buffer.Length - 1]) + 1;
} }
void CheckCapacityAndSwap(int requiredCapacity) private void CheckCapacityAndSwap(int requiredCapacity)
{ {
if (SuplusCapacity < requiredCapacity) if (SuplusCapacity < requiredCapacity)
{ {
@@ -84,7 +84,7 @@ public unsafe class BufferWriter : BinaryWriter
public override void Write(byte value) public override void Write(byte value)
{ {
CheckCapacityAndSwap(1); CheckCapacityAndSwap(1);
*(curPos++) = value; *(_curPos++) = value;
} }
public override void Write(bool value) => Write((byte)(value ? 1 : 0)); public override void Write(bool value) => Write((byte)(value ? 1 : 0));
@@ -115,43 +115,43 @@ public unsafe class BufferWriter : BinaryWriter
public override void Write(sbyte value) => Write((byte)value); public override void Write(sbyte value) => Write((byte)value);
public override void Write(byte[] _buffer) => Write(_buffer, 0, _buffer.Length); public override void Write(byte[] buffer) => Write(buffer, 0, buffer.Length);
public override void Write(byte[] _buffer, int index, int count) public override void Write(byte[] buffer, int index, int count)
{ {
if (_buffer == null) if (buffer == null)
{ {
throw new ArgumentNullException("buffer"); throw new ArgumentNullException(nameof(buffer));
} }
fixed (byte* start = _buffer) fixed (byte* start = buffer)
{ {
byte* srcPos = start + index; byte* srcPos = start + index;
while (SuplusCapacity <= count) while (SuplusCapacity <= count)
{ {
int dstSuplus = (int)SuplusCapacity; int dstSuplus = (int)SuplusCapacity;
//Array.Copy(_buffer, index + writed, Buffer, Position, SuplusCapacity); //Array.Copy(_buffer, index + writed, Buffer, Position, SuplusCapacity);
Unsafe.CopyBlock(curPos, srcPos, (uint)dstSuplus); Unsafe.CopyBlock(_curPos, srcPos, (uint)dstSuplus);
count -= dstSuplus; count -= dstSuplus;
srcPos += dstSuplus; srcPos += dstSuplus;
curPos = endPos; _curPos = _endPos;
SwapBuffer(); SwapBuffer();
} }
Unsafe.CopyBlock(curPos, srcPos, (uint)count); Unsafe.CopyBlock(_curPos, srcPos, (uint)count);
curPos += count; _curPos += count;
} }
} }
public unsafe override void Write(char ch) public override void Write(char ch)
{ {
if (char.IsSurrogate(ch)) if (char.IsSurrogate(ch))
{ {
throw new ArgumentException("Arg_SurrogatesNotAllowedAsSingleChar"); throw new ArgumentException("Arg_SurrogatesNotAllowedAsSingleChar");
} }
CheckCapacityAndSwap(maxBytesPerChar); CheckCapacityAndSwap(_maxBytesPerChar);
curPos += _encoding.GetBytes(&ch, 1, curPos, (int)SuplusCapacity); _curPos += _encoding.GetBytes(&ch, 1, _curPos, (int)SuplusCapacity);
} }
//slow //slow
@@ -159,24 +159,24 @@ public unsafe class BufferWriter : BinaryWriter
{ {
if (chars == null) if (chars == null)
{ {
throw new ArgumentNullException("chars"); throw new ArgumentNullException(nameof(chars));
} }
byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length); byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
Write(bytes); Write(bytes);
} }
public unsafe override void Write(double value) public override void Write(double value)
{ {
CheckCapacityAndSwap(8); CheckCapacityAndSwap(8);
ulong num = (ulong)(*(long*)(&value)); ulong num = (ulong)(*(long*)(&value));
*(curPos++) = (byte)num; *(_curPos++) = (byte)num;
*(curPos++) = (byte)(num >> 8); *(_curPos++) = (byte)(num >> 8);
*(curPos++) = (byte)(num >> 16); *(_curPos++) = (byte)(num >> 16);
*(curPos++) = (byte)(num >> 24); *(_curPos++) = (byte)(num >> 24);
*(curPos++) = (byte)(num >> 32); *(_curPos++) = (byte)(num >> 32);
*(curPos++) = (byte)(num >> 40); *(_curPos++) = (byte)(num >> 40);
*(curPos++) = (byte)(num >> 48); *(_curPos++) = (byte)(num >> 48);
*(curPos++) = (byte)(num >> 56); *(_curPos++) = (byte)(num >> 56);
} }
//slow //slow
@@ -195,15 +195,15 @@ public unsafe class BufferWriter : BinaryWriter
public override void Write(short value) public override void Write(short value)
{ {
CheckCapacityAndSwap(2); CheckCapacityAndSwap(2);
*(curPos++) = (byte)value; *(_curPos++) = (byte)value;
*(curPos++) = (byte)(value >> 8); *(_curPos++) = (byte)(value >> 8);
} }
public override void Write(ushort value) public override void Write(ushort value)
{ {
CheckCapacityAndSwap(2); CheckCapacityAndSwap(2);
*(curPos++) = (byte)value; *(_curPos++) = (byte)value;
*(curPos++) = (byte)(value >> 8); *(_curPos++) = (byte)(value >> 8);
} }
@@ -213,56 +213,56 @@ public unsafe class BufferWriter : BinaryWriter
{ {
SwapBuffer(); SwapBuffer();
} }
*(curPos++) = (byte)value; *(_curPos++) = (byte)value;
*(curPos++) = (byte)(value >> 8); *(_curPos++) = (byte)(value >> 8);
*(curPos++) = (byte)(value >> 16); *(_curPos++) = (byte)(value >> 16);
*(curPos++) = (byte)(value >> 24); *(_curPos++) = (byte)(value >> 24);
} }
public override void Write(uint value) public override void Write(uint value)
{ {
CheckCapacityAndSwap(4); CheckCapacityAndSwap(4);
*(curPos++) = (byte)value; *(_curPos++) = (byte)value;
*(curPos++) = (byte)(value >> 8); *(_curPos++) = (byte)(value >> 8);
*(curPos++) = (byte)(value >> 16); *(_curPos++) = (byte)(value >> 16);
*(curPos++) = (byte)(value >> 24); *(_curPos++) = (byte)(value >> 24);
} }
public override void Write(long value) public override void Write(long value)
{ {
CheckCapacityAndSwap(8); CheckCapacityAndSwap(8);
*(curPos++) = (byte)value; *(_curPos++) = (byte)value;
*(curPos++) = (byte)(value >> 8); *(_curPos++) = (byte)(value >> 8);
*(curPos++) = (byte)(value >> 16); *(_curPos++) = (byte)(value >> 16);
*(curPos++) = (byte)(value >> 24); *(_curPos++) = (byte)(value >> 24);
*(curPos++) = (byte)(value >> 32); *(_curPos++) = (byte)(value >> 32);
*(curPos++) = (byte)(value >> 40); *(_curPos++) = (byte)(value >> 40);
*(curPos++) = (byte)(value >> 48); *(_curPos++) = (byte)(value >> 48);
*(curPos++) = (byte)(value >> 56); *(_curPos++) = (byte)(value >> 56);
} }
public override void Write(ulong value) public override void Write(ulong value)
{ {
CheckCapacityAndSwap(8); CheckCapacityAndSwap(8);
*(curPos++) = (byte)value; *(_curPos++) = (byte)value;
*(curPos++) = (byte)(value >> 8); *(_curPos++) = (byte)(value >> 8);
*(curPos++) = (byte)(value >> 16); *(_curPos++) = (byte)(value >> 16);
*(curPos++) = (byte)(value >> 24); *(_curPos++) = (byte)(value >> 24);
*(curPos++) = (byte)(value >> 32); *(_curPos++) = (byte)(value >> 32);
*(curPos++) = (byte)(value >> 40); *(_curPos++) = (byte)(value >> 40);
*(curPos++) = (byte)(value >> 48); *(_curPos++) = (byte)(value >> 48);
*(curPos++) = (byte)(value >> 56); *(_curPos++) = (byte)(value >> 56);
} }
public unsafe override void Write(float value) public override void Write(float value)
{ {
CheckCapacityAndSwap(4); CheckCapacityAndSwap(4);
uint num = *(uint*)(&value); uint num = *(uint*)(&value);
*(curPos++) = (byte)num; *(_curPos++) = (byte)num;
*(curPos++) = (byte)(num >> 8); *(_curPos++) = (byte)(num >> 8);
*(curPos++) = (byte)(num >> 16); *(_curPos++) = (byte)(num >> 16);
*(curPos++) = (byte)(num >> 24); *(_curPos++) = (byte)(num >> 24);
} }
@@ -271,7 +271,7 @@ public unsafe class BufferWriter : BinaryWriter
{ {
if (value == null) if (value == null)
{ {
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
} }
byte[] bytes = _encoding.GetBytes(value); byte[] bytes = _encoding.GetBytes(value);
Write7BitEncodedInt(bytes.Length); Write7BitEncodedInt(bytes.Length);
@@ -279,7 +279,7 @@ public unsafe class BufferWriter : BinaryWriter
} }
protected new void Write7BitEncodedInt(int value) private new void Write7BitEncodedInt(int value)
{ {
uint num; uint num;
for (num = (uint)value; num >= 128; num >>= 7) for (num = (uint)value; num >= 128; num >>= 7)

View File

@@ -1,117 +0,0 @@
namespace CompressSave.Wrapper;
//public class BufferedFileStream : FileStream
//{
// public override bool CanTimeout => base.CanTimeout;
// public override int ReadTimeout { get => base.ReadTimeout; set => base.ReadTimeout = value; }
// public override int WriteTimeout { get => base.WriteTimeout; set => base.WriteTimeout = value; }
// public override long Position { get => base.Position; set => base.Position = value; }
// public override SafeFileHandle SafeFileHandle => base.SafeFileHandle;
// public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
// {
// return base.BeginRead(array, offset, numBytes, userCallback, stateObject);
// }
// public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
// {
// return base.BeginWrite(array, offset, numBytes, userCallback, stateObject);
// }
// public override void Close()
// {
// var bs = new BufferedStream(this);
// base.Close();
// }
// public override bool Equals(object obj)
// {
// return base.Equals(obj);
// }
// public override void Flush()
// {
// base.Flush();
// }
// public override void Flush(bool flushToDisk)
// {
// base.Flush(flushToDisk);
// }
// public override Task FlushAsync(CancellationToken cancellationToken)
// {
// return base.FlushAsync(cancellationToken);
// }
// public override int GetHashCode()
// {
// return base.GetHashCode();
// }
// public override object InitializeLifetimeService()
// {
// return base.InitializeLifetimeService();
// }
// public override void Lock(long position, long length)
// {
// base.Lock(position, length);
// }
// public override int Read(byte[] array, int offset, int count)
// {
// return base.Read(array, offset, count);
// }
// public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
// {
// return base.ReadAsync(buffer, offset, count, cancellationToken);
// }
// public override long Seek(long offset, SeekOrigin origin)
// {
// return base.Seek(offset, origin);
// }
// public override void SetLength(long value)
// {
// base.SetLength(value);
// }
// public override string ToString()
// {
// return base.ToString();
// }
// public override void Unlock(long position, long length)
// {
// base.Unlock(position, length);
// }
// public override void Write(byte[] array, int offset, int count)
// {
// base.Write(array, offset, count);
// }
// public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
// {
// return base.WriteAsync(buffer, offset, count, cancellationToken);
// }
// public override void WriteByte(byte value)
// {
// base.WriteByte(value);
// }
// protected override void Dispose(bool disposing)
// {
// base.Dispose(disposing);
// }
//}

View File

@@ -6,65 +6,68 @@ namespace CompressSave.Wrapper;
public class CompressionStream : Stream public class CompressionStream : Stream
{ {
public WrapperDefines wrapper; private readonly WrapperDefines _wrapper;
public const int MB = 1024 * 1024; public const int Mb = 1024 * 1024;
public override bool CanRead => false; public override bool CanRead => false;
public override bool CanSeek => false; public override bool CanSeek => false;
public override bool CanWrite => true; public override bool CanWrite => true;
public override long Length => totalWrite; public override long Length => _totalWrite;
// only use for game statistics // only use for game statistics
public override long Position { get => BufferWriter.WriteSum; set => new NotImplementedException(); } public override long Position
{
get => BufferWriter.WriteSum;
set => throw new NotImplementedException();
}
public readonly Stream outStream; public readonly Stream OutStream;
long totalWrite = 0; private long _totalWrite;
bool useMultiThread; private readonly bool _useMultiThread;
DoubleBuffer doubleBuffer; private DoubleBuffer _doubleBuffer;
private byte[] outBuffer; private byte[] _outBuffer;
IntPtr cctx; private IntPtr _cctx;
long lastError = 0; private long _lastError;
bool stopWorker = true; private bool _stopWorker = true;
Thread compressThread;
public bool HasError() public bool HasError()
{ {
return lastError != 0; return _lastError != 0;
} }
public void HandleError(long errorCode) private void HandleError(long errorCode)
{ {
if (errorCode < 0) if (errorCode < 0)
{ {
wrapper.CompressContextFree(cctx); _wrapper.CompressContextFree(_cctx);
cctx = IntPtr.Zero; _cctx = IntPtr.Zero;
lastError = errorCode; _lastError = errorCode;
throw new Exception(errorCode.ToString()); throw new Exception(errorCode.ToString());
} }
} }
public struct CompressBuffer public struct CompressBuffer
{ {
public byte[] readBuffer; public byte[] ReadBuffer;
public byte[] writeBuffer; public byte[] WriteBuffer;
public byte[] outBuffer; public byte[] OutBuffer;
} }
public static CompressBuffer CreateBuffer(int outBufferSize, int exBufferSize = 4 * MB) public static CompressBuffer CreateBuffer(int outBufferSize, int exBufferSize = 4 * Mb)
{ {
try try
{ {
return new CompressBuffer return new CompressBuffer
{ {
outBuffer = new byte[outBufferSize], OutBuffer = new byte[outBufferSize],
readBuffer = new byte[exBufferSize], ReadBuffer = new byte[exBufferSize],
writeBuffer = new byte[exBufferSize], WriteBuffer = new byte[exBufferSize],
}; };
} }
catch (Exception e) catch (Exception e)
@@ -78,79 +81,77 @@ public class CompressionStream : Stream
public CompressionStream(WrapperDefines wrap, int compressionLevel, Stream outputStream, CompressBuffer compressBuffer, bool multiThread) public CompressionStream(WrapperDefines wrap, int compressionLevel, Stream outputStream, CompressBuffer compressBuffer, bool multiThread)
{ {
wrapper = wrap; _wrapper = wrap;
outStream = outputStream; OutStream = outputStream;
InitBuffer(compressBuffer.readBuffer, compressBuffer.writeBuffer, compressBuffer.outBuffer); InitBuffer(compressBuffer.ReadBuffer, compressBuffer.WriteBuffer, compressBuffer.OutBuffer);
long writeSize = wrapper.CompressBegin(out cctx, compressionLevel, outBuffer, outBuffer.Length); var writeSize = _wrapper.CompressBegin(out _cctx, compressionLevel, _outBuffer, _outBuffer.Length);
HandleError(writeSize); HandleError(writeSize);
outputStream.Write(outBuffer, 0, (int)writeSize); outputStream.Write(_outBuffer, 0, (int)writeSize);
useMultiThread = multiThread; _useMultiThread = multiThread;
if(multiThread) if (!multiThread) return;
{ _stopWorker = false;
stopWorker = false; var compressThread = new Thread(CompressAsync);
compressThread = new Thread(() => CompressAsync()); compressThread.Start();
compressThread.Start();
}
} }
void InitBuffer(byte[] readBuffer, byte[] writeBuffer, byte[] outputBuffer) private void InitBuffer(byte[] readBuffer, byte[] writeBuffer, byte[] outputBuffer)
{ {
doubleBuffer = new DoubleBuffer(readBuffer ?? new byte[4 * MB], writeBuffer ?? new byte[4 * MB], Compress); _doubleBuffer = new DoubleBuffer(readBuffer ?? new byte[4 * Mb], writeBuffer ?? new byte[4 * Mb], Compress);
outBuffer = outputBuffer ?? new byte[wrapper.CompressBufferBound(writeBuffer?.Length ?? 4 * MB)]; _outBuffer = outputBuffer ?? new byte[_wrapper.CompressBufferBound(writeBuffer?.Length ?? 4 * Mb)];
BufferWriter = new BufferWriter(doubleBuffer,this); BufferWriter = new BufferWriter(_doubleBuffer,this);
} }
public override void Flush() public override void Flush()
{ {
doubleBuffer.SwapBuffer(); _doubleBuffer.SwapBuffer();
if(useMultiThread) if(_useMultiThread)
{ {
doubleBuffer.WaitReadEnd(); _doubleBuffer.WaitReadEnd();
} }
lock (outBuffer) lock (_outBuffer)
{ {
outStream.Flush(); OutStream.Flush();
} }
} }
void Compress() private void Compress()
{ {
if (!useMultiThread) if (!_useMultiThread)
{ {
Compress_Internal(); Compress_Internal();
} }
} }
void Compress_Internal() private void Compress_Internal()
{ {
var consumeBuffer = doubleBuffer.ReadBegin(); var consumeBuffer = _doubleBuffer.ReadBegin();
if (consumeBuffer.Length > 0) if (consumeBuffer.Length > 0)
{ {
lock (outBuffer) lock (_outBuffer)
{ {
long writeSize = 0; long writeSize;
try try
{ {
writeSize = wrapper.CompressUpdateEx(cctx, outBuffer, 0, consumeBuffer.Buffer, 0, consumeBuffer.Length); writeSize = _wrapper.CompressUpdateEx(_cctx, _outBuffer, 0, consumeBuffer.Buffer, 0, consumeBuffer.Length);
HandleError(writeSize); HandleError(writeSize);
} }
finally finally
{ {
doubleBuffer.ReadEnd(); _doubleBuffer.ReadEnd();
} }
outStream.Write(outBuffer, 0, (int)writeSize); OutStream.Write(_outBuffer, 0, (int)writeSize);
totalWrite += writeSize; _totalWrite += writeSize;
} }
} }
else else
{ {
doubleBuffer.ReadEnd(); _doubleBuffer.ReadEnd();
} }
} }
void CompressAsync() private void CompressAsync()
{ {
while(!stopWorker) while(!_stopWorker)
{ {
Compress_Internal(); Compress_Internal();
} }
@@ -187,32 +188,30 @@ public class CompressionStream : Stream
//inputSum += count; //inputSum += count;
} }
protected void FreeContext() private void FreeContext()
{ {
wrapper.CompressContextFree(cctx); _wrapper.CompressContextFree(_cctx);
cctx = IntPtr.Zero; _cctx = IntPtr.Zero;
} }
bool closed = false; private bool _closed;
public override void Close() public override void Close()
{ {
if(!closed) if (_closed) return;
{ BufferWriter.Close();
BufferWriter.Close(); _closed = true;
closed = true; //Console.WriteLine($"FLUSH");
//Console.WriteLine($"FLUSH");
Flush(); Flush();
// try stop the worker // try stop the worker
stopWorker = true; _stopWorker = true;
doubleBuffer.SwapBuffer(); _doubleBuffer.SwapBuffer();
long size = wrapper.CompressEnd(cctx, outBuffer, outBuffer.Length); var size = _wrapper.CompressEnd(_cctx, _outBuffer, _outBuffer.Length);
//Debug.Log($"End"); //Debug.Log($"End");
outStream.Write(outBuffer, 0, (int)size); OutStream.Write(_outBuffer, 0, (int)size);
base.Close(); base.Close();
}
} }
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)

View File

@@ -5,7 +5,7 @@ namespace CompressSave.Wrapper;
public class DecompressionStream : Stream public class DecompressionStream : Stream
{ {
public WrapperDefines wrapper; private readonly WrapperDefines _wrapper;
public override bool CanRead => true; public override bool CanRead => true;
@@ -13,18 +13,18 @@ public class DecompressionStream : Stream
public override bool CanWrite => false; public override bool CanWrite => false;
public override long Length => inStream.Length; public override long Length => _inStream.Length;
public override long Position public override long Position
{ {
get => readPos; get => _readPos;
set set
{ {
if (value < readPos) if (value < _readPos)
ResetStream(); ResetStream();
else else
value -= readPos; value -= _readPos;
byte[] tmpBuffer = new byte[1024]; var tmpBuffer = new byte[1024];
while (value > 0) while (value > 0)
{ {
value -= Read(tmpBuffer, 0, (int)(value < 1024 ? value : 1024)); value -= Read(tmpBuffer, 0, (int)(value < 1024 ? value : 1024));
@@ -32,56 +32,56 @@ public class DecompressionStream : Stream
} }
} }
public Stream inStream; private readonly Stream _inStream;
IntPtr dctx = IntPtr.Zero; private IntPtr _dctx = IntPtr.Zero;
readonly ByteSpan srcBuffer; private readonly ByteSpan _srcBuffer;
readonly ByteSpan dcmpBuffer; private readonly ByteSpan _dcmpBuffer;
private bool decompressFinish = false; private bool _decompressFinish;
readonly long startPos = 0; private readonly long _startPos;
long readPos = 0; //sum of readlen private long _readPos; //sum of readlen
public DecompressionStream(WrapperDefines wrap, Stream inputStream, int extraBufferSize = 512 * 1024) public DecompressionStream(WrapperDefines wrap, Stream inputStream, int extraBufferSize = 512 * 1024)
{ {
wrapper = wrap; _wrapper = wrap;
inStream = inputStream; _inStream = inputStream;
startPos = inputStream.Position; _startPos = inputStream.Position;
srcBuffer = new ByteSpan(new byte[extraBufferSize]); _srcBuffer = new ByteSpan(new byte[extraBufferSize]);
int len = Fill(); var len = Fill();
long expect = wrapper.DecompressBegin(ref dctx, srcBuffer.Buffer, ref len, out var blockSize); var expect = _wrapper.DecompressBegin(ref _dctx, _srcBuffer.Buffer, ref len, out var blockSize);
srcBuffer.Position += len; _srcBuffer.Position += len;
if (expect < 0) throw new Exception(expect.ToString()); if (expect < 0) throw new Exception(expect.ToString());
dcmpBuffer = new ByteSpan(new byte[blockSize]); _dcmpBuffer = new ByteSpan(new byte[blockSize]);
} }
public void ResetStream() public void ResetStream()
{ {
inStream.Seek(startPos, SeekOrigin.Begin); _inStream.Seek(_startPos, SeekOrigin.Begin);
decompressFinish = false; _decompressFinish = false;
srcBuffer.Clear(); _srcBuffer.Clear();
dcmpBuffer.Clear(); _dcmpBuffer.Clear();
wrapper.DecompressContextReset(dctx); _wrapper.DecompressContextReset(_dctx);
readPos = 0; _readPos = 0;
} }
public int Fill() private int Fill()
{ {
int suplus = srcBuffer.Length - srcBuffer.Position; var suplus = _srcBuffer.Length - _srcBuffer.Position;
if (srcBuffer.Length > 0 && srcBuffer.Position >= suplus) if (_srcBuffer.Length > 0 && _srcBuffer.Position >= suplus)
{ {
Array.Copy(srcBuffer, srcBuffer.Position, srcBuffer, 0, suplus); Array.Copy(_srcBuffer, _srcBuffer.Position, _srcBuffer, 0, suplus);
srcBuffer.Length -= srcBuffer.Position; _srcBuffer.Length -= _srcBuffer.Position;
srcBuffer.Position = 0; _srcBuffer.Position = 0;
} }
if (srcBuffer.IdleCapacity > 0) if (_srcBuffer.IdleCapacity > 0)
{ {
var readlen = inStream.Read(srcBuffer, srcBuffer.Length, srcBuffer.IdleCapacity); var readlen = _inStream.Read(_srcBuffer, _srcBuffer.Length, _srcBuffer.IdleCapacity);
srcBuffer.Length += readlen; _srcBuffer.Length += readlen;
} }
return srcBuffer.Length - srcBuffer.Position; return _srcBuffer.Length - _srcBuffer.Position;
} }
public override void Flush() public override void Flush()
@@ -90,51 +90,51 @@ public class DecompressionStream : Stream
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
wrapper.DecompressEnd(dctx); _wrapper.DecompressEnd(_dctx);
dctx = IntPtr.Zero; _dctx = IntPtr.Zero;
base.Dispose(disposing); base.Dispose(disposing);
} }
public override int Read(byte[] buffer, int offset, int count) public override int Read(byte[] buffer, int offset, int count)
{ {
int readlen = 0; var readlen = 0;
while (count > (readlen += dcmpBuffer.Read(buffer, offset + readlen, count - readlen)) && !decompressFinish) while (count > (readlen += _dcmpBuffer.Read(buffer, offset + readlen, count - readlen)) && !_decompressFinish)
{ {
var buffSize = Fill(); var buffSize = Fill();
if (buffSize <= 0) return readlen; if (buffSize <= 0) return readlen;
var rt = wrapper.DecompressUpdateEx(dctx, dcmpBuffer, 0, dcmpBuffer.Capacity, srcBuffer, srcBuffer.Position, var rt = _wrapper.DecompressUpdateEx(_dctx, _dcmpBuffer, 0, _dcmpBuffer.Capacity, _srcBuffer, _srcBuffer.Position,
buffSize); buffSize);
if (rt.Expect < 0) throw new Exception(rt.Expect.ToString()); if (rt.Expect < 0) throw new Exception(rt.Expect.ToString());
if (rt.Expect == 0) decompressFinish = true; if (rt.Expect == 0) _decompressFinish = true;
srcBuffer.Position += (int)rt.ReadLen; _srcBuffer.Position += (int)rt.ReadLen;
dcmpBuffer.Position = 0; _dcmpBuffer.Position = 0;
dcmpBuffer.Length = (int)rt.WriteLen; _dcmpBuffer.Length = (int)rt.WriteLen;
} }
readPos += readlen; _readPos += readlen;
return readlen; return readlen;
} }
public int PeekByte() public int PeekByte()
{ {
if (dcmpBuffer.Length <= dcmpBuffer.Position) if (_dcmpBuffer.Length <= _dcmpBuffer.Position)
{ {
var buffSize = Fill(); var buffSize = Fill();
if (buffSize <= 0) return -1; if (buffSize <= 0) return -1;
var rt = wrapper.DecompressUpdateEx(dctx, dcmpBuffer, 0, dcmpBuffer.Capacity, srcBuffer, srcBuffer.Position, var rt = _wrapper.DecompressUpdateEx(_dctx, _dcmpBuffer, 0, _dcmpBuffer.Capacity, _srcBuffer, _srcBuffer.Position,
buffSize); buffSize);
if (rt.Expect < 0) throw new Exception(rt.Expect.ToString()); if (rt.Expect < 0) throw new Exception(rt.Expect.ToString());
if (rt.Expect == 0) decompressFinish = true; if (rt.Expect == 0) _decompressFinish = true;
srcBuffer.Position += (int)rt.ReadLen; _srcBuffer.Position += (int)rt.ReadLen;
dcmpBuffer.Position = 0; _dcmpBuffer.Position = 0;
dcmpBuffer.Length = (int)rt.WriteLen; _dcmpBuffer.Length = (int)rt.WriteLen;
} }
return dcmpBuffer.Buffer[dcmpBuffer.Position]; return _dcmpBuffer.Buffer[_dcmpBuffer.Position];
} }
public override long Seek(long offset, SeekOrigin origin) public override long Seek(long offset, SeekOrigin origin)

View File

@@ -5,10 +5,10 @@ namespace CompressSave.Wrapper;
public class ByteSpan public class ByteSpan
{ {
public byte[] Buffer { get; private set; } public byte[] Buffer { get; }
//public int Start; //public int Start;
public int Length; public int Length;
public int Capacity; public readonly int Capacity;
public int IdleCapacity => Capacity - Length; public int IdleCapacity => Capacity - Length;
public int Position; public int Position;
@@ -41,61 +41,45 @@ public class ByteSpan
public static implicit operator byte[](ByteSpan bs) => bs.Buffer; public static implicit operator byte[](ByteSpan bs) => bs.Buffer;
} }
public struct ReadOnlySpan public struct ReadOnlySpan(byte[] buffer, int length)
{ {
public readonly int Length; private readonly byte[] _buffer = buffer;
public readonly byte[] Buffer; private int _position = 0;
public int Position;
public ReadOnlySpan(byte[] buffer, int length)
{
Buffer = buffer;
Length = length;
Position = 0;
}
public int Read(byte[] dst, int offset, int count) public int Read(byte[] dst, int offset, int count)
{ {
count = Math.Min(Length - Position, count); count = Math.Min(length - _position, count);
Array.Copy(Buffer, Position, dst, offset, count); Array.Copy(_buffer, _position, dst, offset, count);
Position += count; _position += count;
return count; return count;
} }
public static implicit operator byte[](ReadOnlySpan s) => s.Buffer; public static implicit operator byte[](ReadOnlySpan s) => s._buffer;
} }
public class DoubleBuffer public class DoubleBuffer(byte[] readingBuffer, byte[] writingBuffer, Action onReadBufferReadyAction)
{ {
public const int MB = 1024 * 1024; public const int Mb = 1024 * 1024;
public ByteSpan writeBuffer; public ByteSpan WriteBuffer = new(writingBuffer);
public ByteSpan readBuffer; private ByteSpan _readBuffer;
private ByteSpan midBuffer; private ByteSpan _midBuffer = new(readingBuffer);
private Action onReadBufferReady;
Semaphore readEnd = new Semaphore(1, 1); private readonly Semaphore _readEnd = new Semaphore(1, 1);
Semaphore writeEnd = new Semaphore(0, 1); private readonly Semaphore _writeEnd = new Semaphore(0, 1);
public DoubleBuffer(byte[] readingBuffer, byte[] writingBuffer, Action onReadBufferReadyAction)
{
onReadBufferReady = onReadBufferReadyAction;
midBuffer = new ByteSpan(readingBuffer);
writeBuffer = new ByteSpan(writingBuffer);
}
public ByteSpan ReadBegin() public ByteSpan ReadBegin()
{ {
writeEnd.WaitOne(); _writeEnd.WaitOne();
return readBuffer; return _readBuffer;
} }
public void ReadEnd() public void ReadEnd()
{ {
readBuffer.Clear(); _readBuffer.Clear();
midBuffer = readBuffer; _midBuffer = _readBuffer;
readBuffer = null; _readBuffer = null;
readEnd.Release(); _readEnd.Release();
} }
/// <summary> /// <summary>
/// swap current write buffer to read and wait a new write buffer /// swap current write buffer to read and wait a new write buffer
@@ -105,27 +89,27 @@ public class DoubleBuffer
{ {
var write = SwapBegin(); var write = SwapBegin();
SwapEnd(); SwapEnd();
onReadBufferReady?.Invoke(); onReadBufferReadyAction?.Invoke();
return write; return write;
} }
public void WaitReadEnd() public void WaitReadEnd()
{ {
readEnd.WaitOne(); _readEnd.WaitOne();
readEnd.Release(); _readEnd.Release();
} }
public ByteSpan SwapBegin() private ByteSpan SwapBegin()
{ {
readEnd.WaitOne(); _readEnd.WaitOne();
readBuffer = writeBuffer; _readBuffer = WriteBuffer;
writeBuffer = midBuffer; WriteBuffer = _midBuffer;
midBuffer = null; _midBuffer = null;
return writeBuffer; return WriteBuffer;
} }
public void SwapEnd() private void SwapEnd()
{ {
writeEnd.Release(); _writeEnd.Release();
} }
} }

View File

@@ -12,8 +12,8 @@ public class LZ4API: WrapperDefines
static LZ4API() static LZ4API()
{ {
Avaliable = true; Avaliable = true;
string assemblyPath = System.Reflection.Assembly.GetAssembly(typeof(LZ4API)).Location; var assemblyPath = System.Reflection.Assembly.GetAssembly(typeof(LZ4API)).Location;
string root = string.Empty; var root = string.Empty;
try try
{ {
if (!string.IsNullOrEmpty(assemblyPath)) if (!string.IsNullOrEmpty(assemblyPath))
@@ -24,16 +24,15 @@ public class LZ4API: WrapperDefines
var map = new Dictionary<string, List<DynDllMapping>> var map = new Dictionary<string, List<DynDllMapping>>
{ {
{ {
"lz4wrap.dll", new List<DynDllMapping> "lz4wrap.dll", [
{
"lz4wrap.dll", "lz4wrap.dll",
"x64/lz4wrap.dll", "x64/lz4wrap.dll",
"plugins/x64/lz4wrap.dll", "plugins/x64/lz4wrap.dll",
"BepInEx/scripts/x64/lz4wrap.dll", "BepInEx/scripts/x64/lz4wrap.dll",
Path.Combine(root, "lz4wrap.dll"), Path.Combine(root, "lz4wrap.dll"),
Path.Combine(root, "x64/lz4wrap.dll"), Path.Combine(root, "x64/lz4wrap.dll"),
Path.Combine(root, "plugins/x64/lz4wrap.dll"), Path.Combine(root, "plugins/x64/lz4wrap.dll")
} ]
}, },
}; };
typeof(LZ4API).ResolveDynDllImports(map); typeof(LZ4API).ResolveDynDllImports(map);

View File

@@ -24,16 +24,15 @@ public class NoneAPI: WrapperDefines
var map = new Dictionary<string, List<DynDllMapping>> var map = new Dictionary<string, List<DynDllMapping>>
{ {
{ {
"nonewrap.dll", new List<DynDllMapping> "nonewrap.dll", [
{
"nonewrap.dll", "nonewrap.dll",
"x64/nonewrap.dll", "x64/nonewrap.dll",
"plugins/x64/nonewrap.dll", "plugins/x64/nonewrap.dll",
"BepInEx/scripts/x64/nonewrap.dll", "BepInEx/scripts/x64/nonewrap.dll",
Path.Combine(root, "nonewrap.dll"), Path.Combine(root, "nonewrap.dll"),
Path.Combine(root, "x64/nonewrap.dll"), Path.Combine(root, "x64/nonewrap.dll"),
Path.Combine(root, "plugins/x64/nonewrap.dll"), Path.Combine(root, "plugins/x64/nonewrap.dll")
} ]
}, },
}; };
typeof(NoneAPI).ResolveDynDllImports(map); typeof(NoneAPI).ResolveDynDllImports(map);

View File

@@ -2,16 +2,10 @@
namespace CompressSave.Wrapper; namespace CompressSave.Wrapper;
class PeekableReader : BinaryReader internal class PeekableReader(DecompressionStream input) : BinaryReader(input)
{ {
DecompressionStream decompressionStream;
public PeekableReader(DecompressionStream input) : base (input)
{
decompressionStream = input;
}
public override int PeekChar() public override int PeekChar()
{ {
return decompressionStream.PeekByte(); return input.PeekByte();
} }
} }

View File

@@ -24,16 +24,15 @@ public class ZstdAPI: WrapperDefines
var map = new Dictionary<string, List<DynDllMapping>> var map = new Dictionary<string, List<DynDllMapping>>
{ {
{ {
"zstdwrap.dll", new List<DynDllMapping> "zstdwrap.dll", [
{
"zstdwrap.dll", "zstdwrap.dll",
"x64/zstdwrap.dll", "x64/zstdwrap.dll",
"plugins/x64/zstdwrap.dll", "plugins/x64/zstdwrap.dll",
"BepInEx/scripts/x64/zstdwrap.dll", "BepInEx/scripts/x64/zstdwrap.dll",
Path.Combine(root, "zstdwrap.dll"), Path.Combine(root, "zstdwrap.dll"),
Path.Combine(root, "x64/zstdwrap.dll"), Path.Combine(root, "x64/zstdwrap.dll"),
Path.Combine(root, "plugins/x64/zstdwrap.dll"), Path.Combine(root, "plugins/x64/zstdwrap.dll")
} ]
}, },
}; };
typeof(ZstdAPI).ResolveDynDllImports(map); typeof(ZstdAPI).ResolveDynDllImports(map);

View File

@@ -105,7 +105,7 @@ public static class BeltSignal
if (obj != null) return obj; if (obj != null) return obj;
} }
obj = new HashSet<int>(); obj = [];
_signalBelts[index] = obj; _signalBelts[index] = obj;
return obj; return obj;
} }

View File

@@ -120,7 +120,7 @@ public class HideTips : BaseUnityPlugin
); );
var labels = matcher.Labels; var labels = matcher.Labels;
var label1 = generator.DefineLabel(); var label1 = generator.DefineLabel();
matcher.Labels = new List<Label>(); matcher.Labels = [];
matcher.InsertAndAdvance( matcher.InsertAndAdvance(
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(HideTips), nameof(_noResearchCompletionTips))).WithLabels(labels), new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(HideTips), nameof(_noResearchCompletionTips))).WithLabels(labels),
new CodeInstruction(OpCodes.Brtrue, label1) new CodeInstruction(OpCodes.Brtrue, label1)

View File

@@ -363,7 +363,7 @@ public class LogisticMiner : BaseUnityPlugin
} }
else else
{ {
_veins.Add(productId, new List<int> { i }); _veins.Add(productId, [i]);
} }
if (vg.TryGetValue(productId, out var hs)) if (vg.TryGetValue(productId, out var hs))
@@ -372,7 +372,7 @@ public class LogisticMiner : BaseUnityPlugin
} }
else else
{ {
vg.Add(productId, new HashSet<int> { veinPool[i].groupIndex }); vg.Add(productId, [veinPool[i].groupIndex]);
} }
} }

View File

@@ -18,7 +18,7 @@ public static class I18N
public static bool Initialized() => _initialized; public static bool Initialized() => _initialized;
private static int _nextID = 1; private static int _nextID = 1;
private static readonly List<StringProto> StringsToAdd = new(); private static readonly List<StringProto> StringsToAdd = [];
public static void Add(string key, string enus, string zhcn = null, string frfr = null) public static void Add(string key, string enus, string zhcn = null, string frfr = null)
{ {
var strProto = new StringProto var strProto = new StringProto

View File

@@ -139,7 +139,7 @@ public static class DysonSpherePatch
private static void SetNodeForAbsorb(int index, int layerId, int nodeId, bool canAbsorb) private static void SetNodeForAbsorb(int index, int layerId, int nodeId, bool canAbsorb)
{ {
ref var comp = ref _nodeForAbsorb[index]; ref var comp = ref _nodeForAbsorb[index];
comp ??= new HashSet<int>(); comp ??= [];
var idx = nodeId * 10 + layerId; var idx = nodeId * 10 + layerId;
if (canAbsorb) if (canAbsorb)
comp.Add(idx); comp.Add(idx);
@@ -241,7 +241,7 @@ public static class DysonSpherePatch
new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(DysonNode), nameof(DysonNode.sp))) new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(DysonNode), nameof(DysonNode.sp)))
).Advance(1); ).Advance(1);
var labels = matcher.Labels; var labels = matcher.Labels;
matcher.Labels = new List<Label>(); matcher.Labels = [];
matcher.Insert( matcher.Insert(
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels), new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(StopEjectOnNodeComplete), nameof(StopEjectOnNodeComplete.UpdateNodeForAbsorbOnSpChange))) new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(StopEjectOnNodeComplete), nameof(StopEjectOnNodeComplete.UpdateNodeForAbsorbOnSpChange)))

View File

@@ -326,7 +326,7 @@ public static class FactoryPatch
); );
var jumpPos = matcher.InstructionAt(3).operand; var jumpPos = matcher.InstructionAt(3).operand;
var labels = matcher.Labels; var labels = matcher.Labels;
matcher.Labels = new List<Label>(); matcher.Labels = [];
/* Insert: br 2358 (1C12) ldloc.s V_8 (8) /* Insert: br 2358 (1C12) ldloc.s V_8 (8)
*/ */
matcher.Insert(new CodeInstruction(OpCodes.Br, jumpPos).WithLabels(labels)); matcher.Insert(new CodeInstruction(OpCodes.Br, jumpPos).WithLabels(labels));
@@ -360,7 +360,7 @@ public static class FactoryPatch
{ {
// Remove 7 instructions, if the following instruction is br/br.s, remove it as well // Remove 7 instructions, if the following instruction is br/br.s, remove it as well
var labels = matcher.Labels; var labels = matcher.Labels;
matcher.Labels = new List<Label>(); matcher.Labels = [];
matcher.RemoveInstructions(7); matcher.RemoveInstructions(7);
var opcode = matcher.Opcode; var opcode = matcher.Opcode;
if (opcode == OpCodes.Br || opcode == OpCodes.Br_S) if (opcode == OpCodes.Br || opcode == OpCodes.Br_S)
@@ -384,7 +384,7 @@ public static class FactoryPatch
matcher.Repeat(codeMatcher => matcher.Repeat(codeMatcher =>
{ {
var labels = codeMatcher.Labels; var labels = codeMatcher.Labels;
codeMatcher.Labels = new List<Label>(); codeMatcher.Labels = [];
codeMatcher.RemoveInstructions(3); codeMatcher.RemoveInstructions(3);
var opcode = codeMatcher.Opcode; var opcode = codeMatcher.Opcode;
if (opcode == OpCodes.Br || opcode == OpCodes.Br_S) if (opcode == OpCodes.Br || opcode == OpCodes.Br_S)

View File

@@ -178,7 +178,6 @@ public static class PlanetFunctions
{ {
if (prebuildPool[i].id != i) continue; if (prebuildPool[i].id != i) continue;
pos = prebuildPool[i].pos; pos = prebuildPool[i].pos;
found = true;
break; break;
} }
} }

View File

@@ -51,7 +51,7 @@ public static class PlanetPatch
matcher.Repeat(codeMatcher => matcher.Repeat(codeMatcher =>
{ {
var labels = codeMatcher.Labels; var labels = codeMatcher.Labels;
codeMatcher.Labels = new List<Label>(); codeMatcher.Labels = [];
codeMatcher.RemoveInstructions(3).Labels.AddRange(labels); codeMatcher.RemoveInstructions(3).Labels.AddRange(labels);
}); });
return matcher.InstructionEnumeration(); return matcher.InstructionEnumeration();
@@ -82,7 +82,7 @@ public static class PlanetPatch
new CodeMatch(OpCodes.Stloc_1) new CodeMatch(OpCodes.Stloc_1)
); );
var labels = matcher.Labels; var labels = matcher.Labels;
matcher.Labels = new List<Label>(); matcher.Labels = [];
matcher.InsertAndAdvance( matcher.InsertAndAdvance(
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(UIGame), nameof(UIGame.viewMode))).WithLabels(labels), new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(UIGame), nameof(UIGame.viewMode))).WithLabels(labels),
new CodeInstruction(OpCodes.Ldc_I4_3), new CodeInstruction(OpCodes.Ldc_I4_3),

View File

@@ -121,8 +121,8 @@ public class MyKeyBinder : MonoBehaviour
} }
} }
public bool TrySetValue() private bool TrySetValue()
{ {
if (Input.GetKey(KeyCode.Escape)) if (Input.GetKey(KeyCode.Escape))
{ {
@@ -155,7 +155,7 @@ public class MyKeyBinder : MonoBehaviour
KeyCode.LeftCommand, KeyCode.LeftApple, KeyCode.LeftWindows, KeyCode.LeftCommand, KeyCode.LeftApple, KeyCode.LeftWindows,
KeyCode.RightCommand, KeyCode.RightApple, KeyCode.RightWindows }; KeyCode.RightCommand, KeyCode.RightApple, KeyCode.RightWindows };
public string GetPressedKey() private string GetPressedKey()
{ {
var key = _lastKey.ToString(); var key = _lastKey.ToString();
if (string.IsNullOrEmpty(key)) if (string.IsNullOrEmpty(key))
@@ -179,7 +179,7 @@ public class MyKeyBinder : MonoBehaviour
} }
//通常キーが押されているかチェック _lastKey に保存 //通常キーが押されているかチェック _lastKey に保存
public bool GetIunptKeys() private bool GetIunptKeys()
{ {
var anyKey = false; var anyKey = false;

View File

@@ -4,6 +4,7 @@ using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using UnityEngine.Events; using UnityEngine.Events;
using UnityEngine.UI; using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace UXAssist.UI; namespace UXAssist.UI;
@@ -133,14 +134,13 @@ public class MyWindow: ManualBehaviour
if (t != null) if (t != null)
{ {
t.text = text.Translate(); t.text = text.Translate();
t.fontSize = fontSize;
} }
t.fontSize = fontSize;
btn.button.onClick.RemoveAllListeners(); btn.button.onClick.RemoveAllListeners();
_buttons[btn] = onClick; _buttons[btn] = onClick;
if (EventRegistered) if (EventRegistered && onClick != null)
{ {
if (onClick != null) btn.button.onClick.AddListener(onClick);
btn.button.onClick.AddListener(onClick);
} }
return btn; return btn;
} }
@@ -215,7 +215,7 @@ public class MyWindow: ManualBehaviour
public class MyWindowWithTabs : MyWindow public class MyWindowWithTabs : MyWindow
{ {
private readonly List<Tuple<RectTransform, UIButton>> _tabs = new(); private readonly List<Tuple<RectTransform, UIButton>> _tabs = [];
private float _tabY = 54f; private float _tabY = 54f;
public override void TryClose() public override void TryClose()
{ {
@@ -347,10 +347,10 @@ public static class MyWindowManager
{ {
var srcWin = UIRoot.instance.uiGame.tankWindow; var srcWin = UIRoot.instance.uiGame.tankWindow;
var src = srcWin.gameObject; var src = srcWin.gameObject;
var go = GameObject.Instantiate(src, UIRoot.instance.uiGame.transform.parent); var go = Object.Instantiate(src, UIRoot.instance.uiGame.transform.parent);
go.name = name; go.name = name;
go.SetActive(false); go.SetActive(false);
GameObject.Destroy(go.GetComponent<UITankWindow>()); Object.Destroy(go.GetComponent<UITankWindow>());
var win = go.AddComponent<T>() as MyWindow; var win = go.AddComponent<T>() as MyWindow;
if (win == null) if (win == null)
return null; return null;
@@ -369,7 +369,7 @@ public static class MyWindowManager
} }
else if (child.name != "shadow" && child.name != "panel-bg") else if (child.name != "shadow" && child.name != "panel-bg")
{ {
GameObject.Destroy(child); Object.Destroy(child);
} }
} }

View File

@@ -86,17 +86,17 @@ public static class UIConfigWindow
x = 400f; x = 400f;
y = 10f; y = 10f;
wnd.AddButton(x, y, tab2, "Initialize This Planet", 16, "button-init-planet", () => wnd.AddButton(x, y, tab2, "Initialize This Planet", 16, "button-init-planet", () =>
UIMessageBox.Show("Initialize This Planet".Translate(), "Initialize This Planet Confirm".Translate(), "取消".Translate(), "确定".Translate(), 2, null, new UIMessageBox.Response(() => UIMessageBox.Show("Initialize This Planet".Translate(), "Initialize This Planet Confirm".Translate(), "取消".Translate(), "确定".Translate(), 2, null, () =>
{ {
PlanetFunctions.RecreatePlanet(true); PlanetFunctions.RecreatePlanet(true);
})) })
); );
y += 36f; y += 36f;
wnd.AddButton(x, y, tab2, "Dismantle All Buildings", 16, "button-dismantle-all", () => wnd.AddButton(x, y, tab2, "Dismantle All Buildings", 16, "button-dismantle-all", () =>
UIMessageBox.Show("Dismantle All Buildings".Translate(), "Dismantle All Buildings Confirm".Translate(), "取消".Translate(), "确定".Translate(), 2, null, new UIMessageBox.Response(() => UIMessageBox.Show("Dismantle All Buildings".Translate(), "Dismantle All Buildings Confirm".Translate(), "取消".Translate(), "确定".Translate(), 2, null, () =>
{ {
PlanetFunctions.DismantleAll(false); PlanetFunctions.DismantleAll(false);
})) })
); );
y += 72f; y += 72f;
@@ -128,10 +128,10 @@ public static class UIConfigWindow
x = 400f; x = 400f;
y = 10f; y = 10f;
wnd.AddButton(x, y, tab3, "Initialize Dyson Sphere", 16, "init-dyson-sphere", () => wnd.AddButton(x, y, tab3, "Initialize Dyson Sphere", 16, "init-dyson-sphere", () =>
UIMessageBox.Show("Initialize Dyson Sphere".Translate(), "Initialize Dyson Sphere Confirm".Translate(), "取消".Translate(), "确定".Translate(), 2, null, new UIMessageBox.Response(() => UIMessageBox.Show("Initialize Dyson Sphere".Translate(), "Initialize Dyson Sphere Confirm".Translate(), "取消".Translate(), "确定".Translate(), 2, null, () =>
{ {
DysonSpherePatch.InitCurrentDysonSphere(-1); DysonSpherePatch.InitCurrentDysonSphere(-1);
})) })
); );
y += 36f; y += 36f;
MyWindow.AddText(x, y, tab3, "Click to dismantle selected layer", 16, "text-dismantle-layer"); MyWindow.AddText(x, y, tab3, "Click to dismantle selected layer", 16, "text-dismantle-layer");
@@ -140,10 +140,10 @@ public static class UIConfigWindow
{ {
var id = i + 1; var id = i + 1;
var btn = wnd.AddFlatButton(x, y, tab3, id.ToString(), 12, "dismantle-layer-" + id, () => var btn = wnd.AddFlatButton(x, y, tab3, id.ToString(), 12, "dismantle-layer-" + id, () =>
UIMessageBox.Show("Dismantle selected layer".Translate(), "Dismantle selected layer Confirm".Translate(), "取消".Translate(), "确定".Translate(), 2, null, new UIMessageBox.Response(() => UIMessageBox.Show("Dismantle selected layer".Translate(), "Dismantle selected layer Confirm".Translate(), "取消".Translate(), "确定".Translate(), 2, null, () =>
{ {
DysonSpherePatch.InitCurrentDysonSphere(id); DysonSpherePatch.InitCurrentDysonSphere(id);
})) })
); );
((RectTransform)btn.transform).sizeDelta = new Vector2(40f, 20f); ((RectTransform)btn.transform).sizeDelta = new Vector2(40f, 20f);
DysonLayerBtn[i] = btn; DysonLayerBtn[i] = btn;

View File

@@ -114,8 +114,8 @@ public static class BirthPlanetPatch
theme.VeinOpacity[3] = 1f; theme.VeinOpacity[3] = 1f;
} }
List<int> veins = new(); List<int> veins = [];
List<float> settings = new(); List<float> settings = [];
if (FireIceOnBirthPlanet.Value) if (FireIceOnBirthPlanet.Value)
{ {
veins.Add(8); veins.Add(8);