From 283783954f7d69909c5c5d6e0a9317a490feb768 Mon Sep 17 00:00:00 2001 From: PopSlime Date: Sat, 21 Jun 2025 01:22:02 +0800 Subject: [PATCH] refactor: Update Unity to 2022.3.62 --- Assets/Cryville/Common/AsyncDelivery.cs | 4 +- Assets/Cryville/Common/BinderAttribute.cs | 4 +- Assets/Cryville/Common/Coroutine.cs | 2 +- Assets/Cryville/Common/Font/FontFile.cs | 16 +- Assets/Cryville/Common/Font/FontManager.cs | 3 +- Assets/Cryville/Common/Font/FontMatcher.cs | 5 +- Assets/Cryville/Common/Font/FontTable.cs | 22 +-- Assets/Cryville/Common/IOExtensions.cs | 4 +- Assets/Cryville/Common/Identifier.cs | 16 +- Assets/Cryville/Common/Math/ColumnVector.cs | 4 +- .../Common/Network/Http11/Http11Client.cs | 3 +- .../Common/Network/Http11/Http11Response.cs | 2 +- .../Network/Http11/Http11ResponseStream.cs | 5 +- .../Cryville/Common/Pdt/PdtEvaluatorBase.cs | 15 +- Assets/Cryville/Common/Pdt/PdtExpression.cs | 13 +- Assets/Cryville/Common/Pdt/PdtInterpreter.cs | 41 ++-- Assets/Cryville/Common/Pdt/PdtOperator.cs | 12 +- .../Cryville/Common/Pdt/PdtVariableMemory.cs | 26 +-- Assets/Cryville/Common/Qualified.cs | 8 +- Assets/Cryville/Common/Shared.cs | 2 +- Assets/Cryville/Common/StringUtils.cs | 6 +- .../Common/Unity/NetworkTaskWorker.cs | 2 +- Assets/Cryville/Common/Unity/StateTweener.cs | 20 +- .../Common/Unity/UI/ScrollableItemGrid.cs | 2 +- .../Cryville/Common/Unity/UI/TMPAutoFont.cs | 3 +- Assets/Cryville/Crtr/BeatTime.cs | 8 +- .../Crtr/Browsing/Actions/ActionManager.cs | 17 +- .../Crtr/Browsing/Actions/OpenConfigAction.cs | 8 +- .../Crtr/Browsing/Actions/ResourceAction.cs | 8 +- .../Crtr/Browsing/ExtensionManager.cs | 10 +- .../Browsing/FileSystemResourceManager.cs | 5 +- .../Browsing/Legacy/LegacyResourceManager.cs | 4 +- .../Browsing/Legacy/LegacyResourceStore.cs | 6 +- .../Crtr/Browsing/UI/BrowserItemTile.cs | 2 +- .../Crtr/Browsing/UI/BrowserTabLayout.cs | 3 +- .../Cryville/Crtr/Browsing/UI/DetailPanel.cs | 2 +- .../Crtr/Browsing/UI/PathedResourceBrowser.cs | 8 +- .../Crtr/Browsing/UI/ResourceBrowserMaster.cs | 7 +- .../Crtr/Browsing/UI/RulesetConfigBrowser.cs | 22 +-- Assets/Cryville/Crtr/BuiltinResources.cs | 8 +- Assets/Cryville/Crtr/Chart.cs | 88 ++++----- .../Crtr/ChartCompatibilityHandler.cs | 20 +- Assets/Cryville/Crtr/ChartPlayer.cs | 187 +++++++++--------- .../Crtr/Config/IPropertyMasterAdapter.cs | 3 +- Assets/Cryville/Crtr/Config/RulesetConfig.cs | 6 +- .../Config/RulesetConfigPropertyAdapter.cs | 14 +- .../Crtr/Config/RulesetConfigStore.cs | 4 +- .../Crtr/Config/UI/InputConfigPanel.cs | 2 +- Assets/Cryville/Crtr/Config/UI/InputDialog.cs | 7 +- .../Crtr/Config/UI/InputDialogEntry.cs | 3 +- .../Cryville/Crtr/Config/UI/PVPNumberBase.cs | 6 +- .../Crtr/Config/UI/PropertyMasterPanel.cs | 5 +- Assets/Cryville/Crtr/Event/ChartHandler.cs | 5 +- .../Cryville/Crtr/Event/ContainerHandler.cs | 25 ++- Assets/Cryville/Crtr/Event/ContainerState.cs | 45 ++--- Assets/Cryville/Crtr/Event/EventBatch.cs | 2 +- Assets/Cryville/Crtr/Event/EventBatcher.cs | 30 ++- Assets/Cryville/Crtr/Event/EventBus.cs | 10 +- Assets/Cryville/Crtr/Event/GroupHandler.cs | 2 +- Assets/Cryville/Crtr/Event/MotionCache.cs | 5 +- Assets/Cryville/Crtr/Event/NoteHandler.cs | 11 +- .../Crtr/Event/RealtimeMotionValue.cs | 12 +- .../Cryville/Crtr/Event/TransformHandler.cs | 2 +- .../Crtr/Extensions/ExtensionImporter.cs | 5 +- .../Extensions/Umg/ChartResourceImporter.cs | 16 +- .../Extensions/Umg/RulesetResourceImporter.cs | 14 +- .../Extensions/Umg/SkinResourceImporter.cs | 20 +- Assets/Cryville/Crtr/Game.cs | 37 ++-- Assets/Cryville/Crtr/JsonPdtExpConverter.cs | 2 +- Assets/Cryville/Crtr/Motion.cs | 17 +- Assets/Cryville/Crtr/Network/UpdateChecker.cs | 24 +-- .../Cryville/Crtr/NetworkTaskWorkerTicker.cs | 8 +- Assets/Cryville/Crtr/PdtBinder.cs | 9 +- Assets/Cryville/Crtr/PdtEvaluator.cs | 112 +++++------ Assets/Cryville/Crtr/PropOp.cs | 7 +- Assets/Cryville/Crtr/Ruleset/InputProxy.cs | 55 +++--- Assets/Cryville/Crtr/Ruleset/Judge.cs | 68 +++---- Assets/Cryville/Crtr/Ruleset/JudgeAction.cs | 2 +- .../Crtr/Ruleset/RulesetDefinition.cs | 36 ++-- .../Crtr/Ruleset/RulesetInterpreter.cs | 4 +- .../Cryville/Crtr/Ruleset/RulesetSelectors.cs | 9 +- .../Crtr/Ruleset/VirtualPlayerStrategy.cs | 11 +- Assets/Cryville/Crtr/Settings.cs | 2 +- .../Cryville/Crtr/Skin/Components/MeshBase.cs | 2 +- .../Crtr/Skin/Components/PolygonSGO.cs | 20 +- .../Crtr/Skin/Components/SkinAnimation.cs | 3 +- .../Crtr/Skin/Components/SpritePlane.cs | 16 +- .../Crtr/Skin/Components/SpriteScale3.cs | 16 +- .../Crtr/Skin/Components/SpriteText.cs | 18 +- .../Crtr/Skin/Components/TrackLine.cs | 2 +- Assets/Cryville/Crtr/Skin/EffectGroup.cs | 9 +- Assets/Cryville/Crtr/Skin/EffectInstance.cs | 2 +- Assets/Cryville/Crtr/Skin/EffectManager.cs | 5 +- Assets/Cryville/Crtr/Skin/SkinContainer.cs | 12 +- Assets/Cryville/Crtr/Skin/SkinDefinition.cs | 51 +++-- Assets/Cryville/Crtr/Skin/SkinInterpreter.cs | 6 +- Assets/Cryville/Crtr/Skin/SkinPropertyKey.cs | 12 +- Assets/Cryville/Crtr/Skin/SkinSelectors.cs | 5 +- Assets/Cryville/Crtr/SpriteFrame.cs | 16 +- Assets/Cryville/Crtr/UI/Dialog.cs | 22 +-- Assets/Cryville/Crtr/UI/Menu.cs | 2 +- Assets/Cryville/GlobalSuppressions.cs | 4 +- .../StandaloneInputModule.cs | 8 +- .../Scripts/Editor/TMP_BaseEditorPanel.cs | 8 +- .../Scripts/Runtime/TMP_Settings.cs | 4 +- .../TextMesh Pro/Scripts/Runtime/TMP_Text.cs | 98 ++++----- .../Scripts/Runtime/TMPro_Private.cs | 12 +- .../Scripts/Runtime/TMPro_UGUI_Private.cs | 12 +- Packages/manifest.json | 2 +- Packages/packages-lock.json | 4 +- ProjectSettings/ProjectVersion.txt | 4 +- ProjectSettings/boot.config | 0 112 files changed, 778 insertions(+), 907 deletions(-) delete mode 100644 ProjectSettings/boot.config diff --git a/Assets/Cryville/Common/AsyncDelivery.cs b/Assets/Cryville/Common/AsyncDelivery.cs index 8663745..4772a20 100644 --- a/Assets/Cryville/Common/AsyncDelivery.cs +++ b/Assets/Cryville/Common/AsyncDelivery.cs @@ -20,13 +20,13 @@ namespace Cryville.Common { /// Whether the task has succeeded. /// The result. public void Deliver(bool succeeded, T result) { - if (Destination != null) Destination(succeeded, result); + Destination?.Invoke(succeeded, result); } /// /// Cancels the task. /// public void Cancel() { - if (CancelSource != null) CancelSource(); + CancelSource?.Invoke(); } } } diff --git a/Assets/Cryville/Common/BinderAttribute.cs b/Assets/Cryville/Common/BinderAttribute.cs index 7330dc5..406939f 100644 --- a/Assets/Cryville/Common/BinderAttribute.cs +++ b/Assets/Cryville/Common/BinderAttribute.cs @@ -35,8 +35,8 @@ namespace Cryville.Common { return null; else if (type.IsAssignableFrom(value.GetType())) return value; - else if (type.IsEnum && value is string) { - return Enum.Parse(type, (string)value); + else if (type.IsEnum && value is string strValue) { + return Enum.Parse(type, strValue); } throw new InvalidCastException(string.Format("Cannot cast {0} to {1}", value.GetType(), type)); } diff --git a/Assets/Cryville/Common/Coroutine.cs b/Assets/Cryville/Common/Coroutine.cs index 6a58281..dd18dc5 100644 --- a/Assets/Cryville/Common/Coroutine.cs +++ b/Assets/Cryville/Common/Coroutine.cs @@ -4,7 +4,7 @@ using System.Diagnostics; namespace Cryville.Common { public class Coroutine { readonly IEnumerator _enumerator; - readonly Stopwatch _stopwatch = new Stopwatch(); + readonly Stopwatch _stopwatch = new(); public float Progress { get; private set; } public Coroutine(IEnumerator enumerator) { _enumerator = enumerator; diff --git a/Assets/Cryville/Common/Font/FontFile.cs b/Assets/Cryville/Common/Font/FontFile.cs index 0e2ac51..a4f5e1f 100644 --- a/Assets/Cryville/Common/Font/FontFile.cs +++ b/Assets/Cryville/Common/Font/FontFile.cs @@ -16,13 +16,11 @@ namespace Cryville.Common.Font { } public void Close() { Reader.Close(); } - public static FontFile Create(FileInfo file) { - switch (file.Extension) { - case ".ttf": case ".otf": return new FontFileTTF(file); - case ".ttc": case ".otc": return new FontFileTTC(file); - default: return null; - } - } + public static FontFile Create(FileInfo file) => file.Extension switch { + ".ttf" or ".otf" => new FontFileTTF(file), + ".ttc" or ".otc" => new FontFileTTC(file), + _ => null, + }; public Enumerator GetEnumerator() { return new Enumerator(this); @@ -42,7 +40,7 @@ namespace Cryville.Common.Font { _index = -1; } - public Typeface Current { + public readonly Typeface Current { get { if (_index < 0) throw new InvalidOperationException(_index == -1 ? "Enum not started" : "Enum ended"); @@ -50,7 +48,7 @@ namespace Cryville.Common.Font { } } - object IEnumerator.Current { get { return Current; } } + readonly object IEnumerator.Current => Current; public void Dispose() { _index = -2; diff --git a/Assets/Cryville/Common/Font/FontManager.cs b/Assets/Cryville/Common/Font/FontManager.cs index e421c56..61d24e3 100644 --- a/Assets/Cryville/Common/Font/FontManager.cs +++ b/Assets/Cryville/Common/Font/FontManager.cs @@ -17,8 +17,7 @@ namespace Cryville.Common.Font { Shared.Logger.Log(3, "UI", "Discarding a font with a duplicate full name {0}", f.FullName); continue; } - List set2; - if (!map2.TryGetValue(f.FamilyName, out set2)) { + if (!map2.TryGetValue(f.FamilyName, out List set2)) { map2.Add(f.FamilyName, set2 = new List()); } set2.Add(f); diff --git a/Assets/Cryville/Common/Font/FontMatcher.cs b/Assets/Cryville/Common/Font/FontMatcher.cs index d6d02fb..e738eff 100644 --- a/Assets/Cryville/Common/Font/FontMatcher.cs +++ b/Assets/Cryville/Common/Font/FontMatcher.cs @@ -12,7 +12,7 @@ namespace Cryville.Common.Font { public class FallbackListFontMatcher : FontMatcher { readonly LanguageMatching _matcher; static readonly string UltimateFallbackScript = "zzzz"; - public Dictionary> MapScriptToTypefaces = new Dictionary>(); + public Dictionary> MapScriptToTypefaces = new(); public static Dictionary> GetDefaultWindowsFallbackMap() { var map = new Dictionary>(StringComparer.OrdinalIgnoreCase); FillKeysWithScripts(map, () => new List()); @@ -333,8 +333,7 @@ namespace Cryville.Common.Font { yield return typeface1; } if (distinctFamily) continue; - IReadOnlyCollection typefaces2; - if (Manager.MapNameToTypefaces.TryGetValue(candidate, out typefaces2)) { + if (Manager.MapNameToTypefaces.TryGetValue(candidate, out IReadOnlyCollection typefaces2)) { foreach (var typeface in typefaces2) { if (typeface1 == typeface) continue; yield return typeface; diff --git a/Assets/Cryville/Common/Font/FontTable.cs b/Assets/Cryville/Common/Font/FontTable.cs index af359cc..954c0ec 100644 --- a/Assets/Cryville/Common/Font/FontTable.cs +++ b/Assets/Cryville/Common/Font/FontTable.cs @@ -25,7 +25,7 @@ namespace Cryville.Common.Font { readonly UInt16 majorVersion; readonly UInt16 minorVersion; readonly UInt32 numFonts; - readonly List tableDirectoryOffsets = new List(); + readonly List tableDirectoryOffsets = new(); #pragma warning disable IDE0052 // Reserved readonly String dsigTag; readonly UInt32 dsigLength; @@ -61,7 +61,7 @@ namespace Cryville.Common.Font { readonly UInt16 entrySelector; readonly UInt16 rangeShift; #pragma warning restore IDE0052 // Reserved - readonly List tableRecords = new List(); + readonly List tableRecords = new(); public TableDirectory(BinaryReader reader, UInt32 offset) : base(reader, offset) { sfntVersion = reader.ReadUInt32(); if (sfntVersion != 0x00010000 && sfntVersion != 0x4F54544F && @@ -81,13 +81,11 @@ namespace Cryville.Common.Font { public override IReadOnlyList GetItems() { return tableRecords; } - public override object GetSubTable(TableRecord item) { - switch (item.tableTag) { - case "name": return new NameTable(Reader, item.offset); - case "meta": return new MetaTable(Reader, item.offset); - default: throw new NotImplementedException(); - } - } + public override object GetSubTable(TableRecord item) => item.tableTag switch { + "name" => new NameTable(Reader, item.offset), + "meta" => new MetaTable(Reader, item.offset), + _ => throw new NotImplementedException(), + }; } public struct TableRecord { public string tableTag; @@ -99,9 +97,9 @@ namespace Cryville.Common.Font { readonly UInt16 version; readonly UInt16 count; readonly UInt16 storageOffset; - readonly List nameRecord = new List(); + readonly List nameRecord = new(); readonly UInt16 langTagCount; - readonly List langTagRecord = new List(); + readonly List langTagRecord = new(); public NameTable(BinaryReader reader, UInt32 offset) : base(reader, offset) { version = reader.ReadUInt16(); count = reader.ReadUInt16(); @@ -213,7 +211,7 @@ namespace Cryville.Common.Font { readonly UInt32 flags; #pragma warning restore IDE0052 // Reserved readonly UInt32 dataMapCount; - readonly List dataMaps = new List(); + readonly List dataMaps = new(); public MetaTable(BinaryReader reader, UInt32 offset) : base(reader, offset) { version = reader.ReadUInt32(); if (version != 1) throw new NotSupportedException(); diff --git a/Assets/Cryville/Common/IOExtensions.cs b/Assets/Cryville/Common/IOExtensions.cs index 1ec8857..9089948 100644 --- a/Assets/Cryville/Common/IOExtensions.cs +++ b/Assets/Cryville/Common/IOExtensions.cs @@ -25,7 +25,7 @@ namespace Cryville.Common { /// The encoding of the string. /// The string read from the reader. public static string ReadUInt16String(this BinaryReader reader, Encoding encoding = null) { - if (encoding == null) encoding = Encoding.UTF8; + encoding ??= Encoding.UTF8; var len = reader.ReadUInt16(); byte[] buffer = reader.ReadBytes(len); return encoding.GetString(buffer); @@ -38,7 +38,7 @@ namespace Cryville.Common { /// The string to write by the writer. /// The encoding of the string. public static void WriteUInt16String(this BinaryWriter writer, string value, Encoding encoding = null) { - if (encoding == null) encoding = Encoding.UTF8; + encoding ??= Encoding.UTF8; byte[] buffer = encoding.GetBytes(value); writer.Write((ushort)buffer.Length); writer.Write(buffer); diff --git a/Assets/Cryville/Common/Identifier.cs b/Assets/Cryville/Common/Identifier.cs index 1127c87..e3fd0e1 100644 --- a/Assets/Cryville/Common/Identifier.cs +++ b/Assets/Cryville/Common/Identifier.cs @@ -2,26 +2,26 @@ using System; namespace Cryville.Common { public struct Identifier : IEquatable { - public static Identifier Empty = new Identifier(0); + public static Identifier Empty = new(0); public int Key { get; private set; } - public object Name { get { return IdentifierManager.Shared.Retrieve(Key); } } + public readonly object Name => IdentifierManager.Shared.Retrieve(Key); public Identifier(int key) { Key = key; } public Identifier(object name) { Key = IdentifierManager.Shared.Request(name); } - public override bool Equals(object obj) { - if (obj == null || !(obj is Identifier)) return false; - return Equals((Identifier)obj); + public override readonly bool Equals(object obj) { + if (obj == null || obj is not Identifier other) return false; + return Equals(other); } - public bool Equals(Identifier other) { + public readonly bool Equals(Identifier other) { return Key == other.Key; } - public override int GetHashCode() { + public override readonly int GetHashCode() { return Key; } - public override string ToString() { + public override readonly string ToString() { if (Key == 0) return ""; return Name.ToString(); } diff --git a/Assets/Cryville/Common/Math/ColumnVector.cs b/Assets/Cryville/Common/Math/ColumnVector.cs index 6517667..d8e4b13 100644 --- a/Assets/Cryville/Common/Math/ColumnVector.cs +++ b/Assets/Cryville/Common/Math/ColumnVector.cs @@ -42,13 +42,13 @@ namespace Cryville.Common.Math { } } /// - /// Performs dot operation with a column vector. + /// Performs dot operation with a column vector. /// /// The lefthand column vector. /// The vector operator. /// The result of the dot operation. public T Dot(ColumnVector lhs, IVectorOperator o) { - T res = default(T); + T res = default; for (var i = 0; i < Size; i++) res = o.Add(res, o.ScalarMultiply(lhs[i], content[i])); return res; diff --git a/Assets/Cryville/Common/Network/Http11/Http11Client.cs b/Assets/Cryville/Common/Network/Http11/Http11Client.cs index d59df8e..0373453 100644 --- a/Assets/Cryville/Common/Network/Http11/Http11Client.cs +++ b/Assets/Cryville/Common/Network/Http11/Http11Client.cs @@ -71,8 +71,7 @@ namespace Cryville.Common.Network.Http11 { headers["Host"] = _baseUri.Host; byte[] payload = null; if (body != null) { - if (encoding == null) - encoding = Encoding.UTF8; + encoding ??= Encoding.UTF8; payload = encoding.GetBytes(body); headers.Add("Content-Encoding", encoding.EncodingName); headers.Add("Content-Length", payload.Length.ToString(CultureInfo.InvariantCulture)); diff --git a/Assets/Cryville/Common/Network/Http11/Http11Response.cs b/Assets/Cryville/Common/Network/Http11/Http11Response.cs index 94a56d8..7d8d74b 100644 --- a/Assets/Cryville/Common/Network/Http11/Http11Response.cs +++ b/Assets/Cryville/Common/Network/Http11/Http11Response.cs @@ -56,7 +56,7 @@ namespace Cryville.Common.Network.Http11 { } internal static string ReadLine(BinaryReader reader) { - StringBuilder result = new StringBuilder(); + StringBuilder result = new(); char c; while (true) { c = reader.ReadChar(); diff --git a/Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs b/Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs index 6753b53..8d61bd9 100644 --- a/Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs +++ b/Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs @@ -72,8 +72,7 @@ namespace Cryville.Common.Network.Http11 { public void ReadChunk() { if (_chunk != null && _chunk.Length == 0) return; string[] chunkHeader = Http11Response.ReadLine(_reader).Split(';'); - int chunkSize; - if (!int.TryParse(chunkHeader[0], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out chunkSize)) + if (!int.TryParse(chunkHeader[0], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int chunkSize)) throw new IOException("Corrupted chunk received"); if (chunkSize == 0) { _chunk = new byte[0]; @@ -106,7 +105,7 @@ namespace Cryville.Common.Network.Http11 { } public override byte[] ReadToEnd() { if (_chunk.Length == 0) return new byte[0]; - List segs = new List(); + List segs = new(); while (true) { if (_pos != 0) { var buffer = new byte[_chunk.Length - _pos]; diff --git a/Assets/Cryville/Common/Pdt/PdtEvaluatorBase.cs b/Assets/Cryville/Common/Pdt/PdtEvaluatorBase.cs index fb71f3b..0fa5890 100644 --- a/Assets/Cryville/Common/Pdt/PdtEvaluatorBase.cs +++ b/Assets/Cryville/Common/Pdt/PdtEvaluatorBase.cs @@ -56,9 +56,9 @@ namespace Cryville.Common.Pdt { while (ip != null) { bool nextFlag = false; var i = ip.Value; - if (i is PdtInstruction.Operate) { + if (i is PdtInstruction.Operate iop) { int fc0 = _framecount; - int fc1 = ((PdtInstruction.Operate)i).Signature.ParamCount; + int fc1 = iop.Signature.ParamCount; try { i.Execute(this, ref ip); } catch (Exception) { } if (fc0 - _framecount == fc1) { unsafe { @@ -77,8 +77,7 @@ namespace Cryville.Common.Pdt { } } } - else if (i is PdtInstruction.Collapse) { - var t = (PdtInstruction.Collapse)i; + else if (i is PdtInstruction.Collapse t) { try { var pins = ip; i.Execute(this, ref ip); @@ -133,15 +132,14 @@ namespace Cryville.Common.Pdt { exp.IsConstant = true; exp.IsPotentialConstant = true; for (var ins = il.First; ins != null; ins = ins.Next) { - if (!(ins.Value is PdtInstruction.PushConstant)) { + if (ins.Value is not PdtInstruction.PushConstant) { exp.IsConstant = false; break; } } } void ReplaceIP(LinkedList il, ref LinkedListNode ip, PdtInstruction ins, Dictionary, List> cols) { - List cins; - if (cols.TryGetValue(ip, out cins)) cols.Remove(ip); + if (cols.TryGetValue(ip, out List cins)) cols.Remove(ip); ip = il.AddAfter(ip, ins); il.Remove(ip.Previous); if (cins != null) cols.Add(ip, cins); @@ -163,8 +161,7 @@ namespace Cryville.Common.Pdt { } internal unsafe void PushVariable(int name, bool forced) { fixed (StackFrame* frame = &_stack[_framecount++]) { - byte[] value; - GetVariable(name, forced, out frame->Type, out value); + GetVariable(name, forced, out frame->Type, out byte[] value); frame->Offset = _goffset; frame->Length = value.Length; Array.Copy(value, 0, _mem, _goffset, value.Length); diff --git a/Assets/Cryville/Common/Pdt/PdtExpression.cs b/Assets/Cryville/Common/Pdt/PdtExpression.cs index b25cda5..99452a6 100644 --- a/Assets/Cryville/Common/Pdt/PdtExpression.cs +++ b/Assets/Cryville/Common/Pdt/PdtExpression.cs @@ -114,7 +114,7 @@ namespace Cryville.Common.Pdt { } } public partial class PdtInterpreter { - static readonly Dictionary OP_PRIORITY = new Dictionary { + static readonly Dictionary OP_PRIORITY = new() { { '@', 7 }, { '*', 6 }, { '/', 6 }, { '%', 6 }, { '+', 5 }, { '-', 5 }, @@ -125,7 +125,7 @@ namespace Cryville.Common.Pdt { { ',', 0 }, { '$', -1 }, }; - static readonly Dictionary OP_TYPE = new Dictionary { + static readonly Dictionary OP_TYPE = new() { { '@', 0 }, { '*', 0 }, { '/', 0 }, { '%', 0 }, { '+', 0 }, { '-', 0 }, @@ -153,10 +153,10 @@ namespace Cryville.Common.Pdt { private struct PdtExpToken { public CharCategory Type { get; set; } public string Value { get; set; } - public override string ToString() { + public override readonly string ToString() { return string.Format("0x{0:x4}: {1}", Type, Value); } - public static readonly PdtExpToken EmptyOperator = new PdtExpToken { + public static readonly PdtExpToken EmptyOperator = new() { Type = CharCategory.Operator, Value = "$", }; @@ -249,13 +249,12 @@ namespace Cryville.Common.Pdt { PdtExpToken? buf = null; while (true) { if (buf != null && t.Type != CharCategory.OpeningBracket) { - PdtExpression def; - if (defs.TryGetValue(buf.Value.Value, out def)) { + if (defs.TryGetValue(buf.Value.Value, out PdtExpression def)) { foreach (var i in def.Instructions) ins.AddLast(i); } else { var name = buf.Value.Value; - if (name[0] == '?') ins.AddLast(new PdtInstruction.PushVariable(name.Substring(1), true)); + if (name[0] == '?') ins.AddLast(new PdtInstruction.PushVariable(name[1..], true)); else ins.AddLast(new PdtInstruction.PushVariable(name)); } buf = null; diff --git a/Assets/Cryville/Common/Pdt/PdtInterpreter.cs b/Assets/Cryville/Common/Pdt/PdtInterpreter.cs index 958035b..907bfd0 100644 --- a/Assets/Cryville/Common/Pdt/PdtInterpreter.cs +++ b/Assets/Cryville/Common/Pdt/PdtInterpreter.cs @@ -65,7 +65,7 @@ namespace Cryville.Common.Pdt { /// public int Position { get; protected set; } - readonly StringBuilder _sb = new StringBuilder(); + readonly StringBuilder _sb = new(); #pragma warning disable IDE1006 /// /// The character at the current position. @@ -86,7 +86,7 @@ namespace Cryville.Common.Pdt { protected string tokenb(CharCategory flag) { int sp = Position; while ((ct & flag) == 0) Position++; - return Source.Substring(sp, Position - sp); + return Source[sp..Position]; } /// /// Reads a token until a character that is not of type is met. @@ -97,7 +97,7 @@ namespace Cryville.Common.Pdt { protected string tokenw(CharCategory flag) { int sp = Position; while ((ct & flag) != 0) Position++; - return Source.Substring(sp, Position - sp); + return Source[sp..Position]; } /// /// Skips over whitespaces. @@ -163,7 +163,7 @@ namespace Cryville.Common.Pdt { return new PdtExpression(ins); } - readonly Dictionary defs = new Dictionary(); + readonly Dictionary defs = new(); /// /// Creates an instance of the class. /// @@ -186,8 +186,7 @@ namespace Cryville.Common.Pdt { public object Interpret(Type type) { try { if (m_formatVersion == null) InterpretDirectives(); - if (_binder == null) - _binder = BinderAttribute.CreateBinderOfType(type); + _binder ??= BinderAttribute.CreateBinderOfType(type); return InterpretObject(type); } catch (Exception ex) { @@ -256,18 +255,17 @@ namespace Cryville.Common.Pdt { } void InterpretObjectInternal(bool pcflag, Type type, object pkey, object result, Func vfunc) where T : Attribute { if (pcflag) { - using (var collection = new PairCollection(result)) { - var ktype = type.GetGenericArguments()[0]; - var ptype = type.GetGenericArguments()[1]; - object key = _binder.ChangeType(pkey, ktype, null); - object value = vfunc(ptype); - collection.Add(key, value); - } + using var collection = new PairCollection(result); + var ktype = type.GetGenericArguments()[0]; + var ptype = type.GetGenericArguments()[1]; + object key = _binder.ChangeType(pkey, ktype, null); + object value = vfunc(ptype); + collection.Add(key, value); } else { MemberInfo prop = null; bool flag = false; - if (pkey is string) prop = FieldLikeHelper.GetMember(type, (string)pkey); + if (pkey is string pname) prop = FieldLikeHelper.GetMember(type, pname); if (prop == null) { prop = FieldLikeHelper.FindMemberWithAttribute(type); flag = true; @@ -279,13 +277,12 @@ namespace Cryville.Common.Pdt { if (origCollection == null) { FieldLikeHelper.SetValue(prop, result, origCollection = Activator.CreateInstance(ptype)); } - using (var collection = new PairCollection(origCollection)) { - var ktype = ptype.GetGenericArguments()[0]; - var vtype = ptype.GetGenericArguments()[1]; - object key = _binder.ChangeType(pkey, ktype, null); - object value = vfunc(vtype); - collection.Add(key, value); - } + using var collection = new PairCollection(origCollection); + var ktype = ptype.GetGenericArguments()[0]; + var vtype = ptype.GetGenericArguments()[1]; + object key = _binder.ChangeType(pkey, ktype, null); + object value = vfunc(vtype); + collection.Add(key, value); } else FieldLikeHelper.SetValue(prop, result, vfunc(ptype), _binder); } @@ -326,7 +323,7 @@ namespace Cryville.Common.Pdt { src.Take(interpreter.Position).Count(c => c == '\n') + 1, pos - lineStartPos + 1, innerException == null ? "Unknown error" : innerException.Message, - src.Substring(previewStartPos, previewEndPos - previewStartPos) + src[previewStartPos..previewEndPos] ); } } diff --git a/Assets/Cryville/Common/Pdt/PdtOperator.cs b/Assets/Cryville/Common/Pdt/PdtOperator.cs index 4ec0446..e7f119c 100644 --- a/Assets/Cryville/Common/Pdt/PdtOperator.cs +++ b/Assets/Cryville/Common/Pdt/PdtOperator.cs @@ -102,17 +102,17 @@ namespace Cryville.Common.Pdt { ParamCount = paramCount; _hash = Name ^ ((ParamCount << 16) | (ParamCount >> 16)); } - public override bool Equals(object obj) { - if (!(obj is PdtOperatorSignature)) return false; - return Equals((PdtOperatorSignature)obj); + public override readonly bool Equals(object obj) { + if (obj is not PdtOperatorSignature other) return false; + return Equals(other); } - public bool Equals(PdtOperatorSignature other) { + public readonly bool Equals(PdtOperatorSignature other) { return Name == other.Name && ParamCount == other.ParamCount; } - public override int GetHashCode() { + public override readonly int GetHashCode() { return _hash; } - public override string ToString() { + public override readonly string ToString() { return string.Format("{0}({1})", IdentifierManager.Shared.Retrieve(Name), ParamCount); } } diff --git a/Assets/Cryville/Common/Pdt/PdtVariableMemory.cs b/Assets/Cryville/Common/Pdt/PdtVariableMemory.cs index 19ee6c6..a898683 100644 --- a/Assets/Cryville/Common/Pdt/PdtVariableMemory.cs +++ b/Assets/Cryville/Common/Pdt/PdtVariableMemory.cs @@ -24,7 +24,7 @@ namespace Cryville.Common.Pdt { /// Copies the memory in the span to another span. /// /// The destination span. - public void CopyTo(PdtVariableMemory dest) { + public readonly void CopyTo(PdtVariableMemory dest) { CopyTo(dest._ptr, 0, Length); } /// @@ -32,7 +32,7 @@ namespace Cryville.Common.Pdt { /// /// The destination buffer. /// The offset on the destination buffer to start copying to. - public void CopyTo(byte[] dest, int destOffset) { + public readonly void CopyTo(byte[] dest, int destOffset) { fixed (byte* ptr = dest) { CopyTo(ptr, destOffset, Length); } @@ -44,13 +44,13 @@ namespace Cryville.Common.Pdt { /// The offset on the destination buffer to start copying to. /// The length to copy. /// is greater than the length of the span. - public void CopyTo(byte* dest, int destOffset, int length) { + public readonly void CopyTo(byte* dest, int destOffset, int length) { if (length > Length) throw new ArgumentOutOfRangeException("length"); for (int i = 0; i < length; i++) dest[destOffset + i] = _ptr[i]; } /// - public bool Equals(PdtVariableMemory obj) { + public readonly bool Equals(PdtVariableMemory obj) { if (Type != obj.Type || Length != obj.Length) return false; for (int i = 0; i < Length; i++) { if (*(_ptr + i) != *(obj._ptr + i)) return false; @@ -63,7 +63,7 @@ namespace Cryville.Common.Pdt { /// The offset on the span to start reading from. /// A number. /// The span at the offset does not represent a number. - public float AsNumber(int offset = 0) { + public readonly float AsNumber(int offset = 0) { if (Type != PdtInternalType.Number && Type != PdtInternalType.Vector) throw new InvalidCastException("Not a number"); float value; @@ -79,7 +79,7 @@ namespace Cryville.Common.Pdt { /// The offset from the start of the span. /// The span at the offset does not represent a number. /// The length of the span is not sufficient. - public void SetNumber(float value, int offset = 0) { + public readonly void SetNumber(float value, int offset = 0) { if (Type != PdtInternalType.Number && Type != PdtInternalType.Vector) throw new InvalidCastException("Not a number"); if (Length < sizeof(float) + offset) @@ -94,7 +94,7 @@ namespace Cryville.Common.Pdt { /// The offset on the span to start reading from. /// A string. /// The span at the offset does not represent a string. - public string AsString(int offset = 0) { + public readonly string AsString(int offset = 0) { if (Type != PdtInternalType.String && Type != PdtInternalType.Array) throw new InvalidCastException("Not a string"); var len = *(int*)(_ptr + offset); @@ -107,7 +107,7 @@ namespace Cryville.Common.Pdt { /// The offset from the start of the span. /// The span at the offset does not represent a string. /// The length of the span is not sufficient. - public void SetString(string value, int offset = 0) { + public readonly void SetString(string value, int offset = 0) { if (Type != PdtInternalType.String && Type != PdtInternalType.Array) throw new InvalidCastException("Not a string"); int strlen = value.Length; @@ -124,7 +124,7 @@ namespace Cryville.Common.Pdt { /// The offset on the span to start reading from. /// The name of an undefined identifier. /// The span does not represent an undefined identifier. - public int AsIdentifier(int offset = 0) { + public readonly int AsIdentifier(int offset = 0) { if (Type != PdtInternalType.Undefined && Type != PdtInternalType.Array) throw new InvalidCastException("Not an identifier"); return *(int*)(_ptr + offset); @@ -140,7 +140,7 @@ namespace Cryville.Common.Pdt { /// /// Use instead while reading an unaligned number. /// - public T As(int offset = 0) { + public readonly T As(int offset = 0) { var len = Unsafe.SizeOf(); if (offset >= Length) throw new ArgumentOutOfRangeException("offset"); @@ -159,7 +159,7 @@ namespace Cryville.Common.Pdt { /// /// Use instead while writing an unaligned number. /// - public void Set(T value, int offset = 0) { + public readonly void Set(T value, int offset = 0) { var len = Unsafe.SizeOf(); if (offset >= Length) throw new ArgumentOutOfRangeException("offset"); @@ -173,7 +173,7 @@ namespace Cryville.Common.Pdt { /// The type of the array. /// The item count of the array. /// The span does not represent an array. - public void GetArraySuffix(out int arrtype, out int pc) { + public readonly void GetArraySuffix(out int arrtype, out int pc) { if (Type != PdtInternalType.Vector && Type != PdtInternalType.Array) throw new InvalidCastException("Not an array or vector"); arrtype = *(int*)(_ptr + Length - sizeof(int)); @@ -186,7 +186,7 @@ namespace Cryville.Common.Pdt { /// The type of the array. /// The item count of the array. /// The span does not represent an array. - public void SetArraySuffix(int arrtype, int pc = 0) { + public readonly void SetArraySuffix(int arrtype, int pc = 0) { if (Type != PdtInternalType.Vector && Type != PdtInternalType.Array) throw new InvalidCastException("Not an array or vector"); *(int*)(_ptr + Length - sizeof(int)) = arrtype; diff --git a/Assets/Cryville/Common/Qualified.cs b/Assets/Cryville/Common/Qualified.cs index 6ac769a..2ab8e3d 100644 --- a/Assets/Cryville/Common/Qualified.cs +++ b/Assets/Cryville/Common/Qualified.cs @@ -6,15 +6,15 @@ namespace Cryville.Common { public T Value { get; set; } public string Unit { get; set; } - public Qualified(string unit) : this(default(T), unit) { } + public Qualified(string unit) : this(default, unit) { } public Qualified(T value, string unit) { Value = value; Unit = unit; } - public override string ToString() { return ToString("G3"); } - public string ToString(string format) { return ToString(format, null); } - public string ToString(string format, IFormatProvider formatProvider) { + public override readonly string ToString() { return ToString("G3"); } + public readonly string ToString(string format) { return ToString(format, null); } + public readonly string ToString(string format, IFormatProvider formatProvider) { double value = Value.ToDouble(formatProvider); int expIndex = (int)System.Math.Log10(value) / 3; if (expIndex == 0) { diff --git a/Assets/Cryville/Common/Shared.cs b/Assets/Cryville/Common/Shared.cs index 58597d9..5aec54e 100644 --- a/Assets/Cryville/Common/Shared.cs +++ b/Assets/Cryville/Common/Shared.cs @@ -2,6 +2,6 @@ using Cryville.Common.Logging; namespace Cryville.Common { public static class Shared { - public static readonly Logger Logger = new Logger(); + public static readonly Logger Logger = new(); } } diff --git a/Assets/Cryville/Common/StringUtils.cs b/Assets/Cryville/Common/StringUtils.cs index 32dc129..a6d469f 100644 --- a/Assets/Cryville/Common/StringUtils.cs +++ b/Assets/Cryville/Common/StringUtils.cs @@ -13,7 +13,7 @@ namespace Cryville.Common { /// The file name or file path. /// The file name or file path with the extension removed. public static string TrimExt(string s) { - return s.Substring(0, s.LastIndexOf(".")); + return s[..s.LastIndexOf(".")]; } /// /// Converts the value of a to a human-readable string. @@ -52,12 +52,12 @@ namespace Cryville.Common { public static string GetProcessPathFromCommand(string command) { command = command.Trim(); if (command[0] == '"') { - return command.Substring(1, command.IndexOf('"', 1) - 1); + return command[1..command.IndexOf('"', 1)]; } else { int e = command.IndexOf(' '); if (e == -1) return command; - else return command.Substring(0, e); + else return command[..e]; } } } diff --git a/Assets/Cryville/Common/Unity/NetworkTaskWorker.cs b/Assets/Cryville/Common/Unity/NetworkTaskWorker.cs index 5c8576c..9db712f 100644 --- a/Assets/Cryville/Common/Unity/NetworkTaskWorker.cs +++ b/Assets/Cryville/Common/Unity/NetworkTaskWorker.cs @@ -16,7 +16,7 @@ namespace Cryville.Common.Unity { public class NetworkTaskWorker { bool suspended; NetworkTask currentNetworkTask; - readonly Queue networkTasks = new Queue(); + readonly Queue networkTasks = new(); /// /// Current queued task count. diff --git a/Assets/Cryville/Common/Unity/StateTweener.cs b/Assets/Cryville/Common/Unity/StateTweener.cs index c75af96..f0da9c2 100644 --- a/Assets/Cryville/Common/Unity/StateTweener.cs +++ b/Assets/Cryville/Common/Unity/StateTweener.cs @@ -30,13 +30,13 @@ namespace Cryville.Common.Unity { [SerializeField] public string Attribute; - public bool Equals(AttributeBinding other) { + public readonly bool Equals(AttributeBinding other) { return Component.Equals(other.Component) && Attribute.Equals(other.Attribute); } - public override bool Equals(object obj) { - return obj is AttributeBinding && Equals((AttributeBinding)obj); + public override readonly bool Equals(object obj) { + return obj is AttributeBinding other && Equals(other); } - public override int GetHashCode() { + public override readonly int GetHashCode() { return Component.GetHashCode() ^ Attribute.GetHashCode(); } } @@ -44,10 +44,10 @@ namespace Cryville.Common.Unity { [SerializeField] StateTweener[] m_children; - readonly List _statePriority = new List(); - readonly Dictionary _defaults = new Dictionary(); - readonly Dictionary> _tweeners = new Dictionary>(); - readonly Dictionary> _runtimeStates = new Dictionary>(); + readonly List _statePriority = new(); + readonly Dictionary _defaults = new(); + readonly Dictionary> _tweeners = new(); + readonly Dictionary> _runtimeStates = new(); void Awake() { var types = new Dictionary(); @@ -130,7 +130,7 @@ namespace Cryville.Common.Unity { foreach (var tweener in _tweeners) tweener.Value.Advance(Time.deltaTime); } - readonly List m_cState = new List(); + readonly List m_cState = new(); public IReadOnlyList CurrentState => m_cState; public void ClearState(float transitionDuration = float.Epsilon) { foreach (var child in m_children) child.ClearState(transitionDuration); @@ -161,7 +161,7 @@ namespace Cryville.Common.Unity { if (index < 0) return; m_cState.RemoveAt(index); if (index < m_cState.Count) return; - var attrs = m_cState.Count == 0 ? _defaults : _runtimeStates[m_cState[m_cState.Count - 1]]; + var attrs = m_cState.Count == 0 ? _defaults : _runtimeStates[m_cState[^1]]; foreach (var tweener in _tweeners) { tweener.Value.Start(attrs[tweener.Key], transitionDuration); } diff --git a/Assets/Cryville/Common/Unity/UI/ScrollableItemGrid.cs b/Assets/Cryville/Common/Unity/UI/ScrollableItemGrid.cs index 48dae17..b45c4d3 100644 --- a/Assets/Cryville/Common/Unity/UI/ScrollableItemGrid.cs +++ b/Assets/Cryville/Common/Unity/UI/ScrollableItemGrid.cs @@ -113,7 +113,7 @@ namespace Cryville.Common.Unity.UI { private bool initialized; private GameObject[][] lines; private int[] refl; - Vector2 cpos = new Vector2(0, 1); + Vector2 cpos = new(0, 1); Vector2 pprectsize; #pragma warning disable IDE0051 diff --git a/Assets/Cryville/Common/Unity/UI/TMPAutoFont.cs b/Assets/Cryville/Common/Unity/UI/TMPAutoFont.cs index 1c6ae0b..b2e2553 100644 --- a/Assets/Cryville/Common/Unity/UI/TMPAutoFont.cs +++ b/Assets/Cryville/Common/Unity/UI/TMPAutoFont.cs @@ -35,8 +35,7 @@ namespace Cryville.Common.Unity.UI { if (MaxFallbackCount <= 0) break; } else { - if (_font.fallbackFontAssetTable == null) - _font.fallbackFontAssetTable = new List(); + _font.fallbackFontAssetTable ??= new List(); _font.fallbackFontAssetTable.Add(ifont); Shared.Logger.Log(1, "UI", "Using fallback font #{0}: {1}", _font.fallbackFontAssetTable.Count, typeface.FullName); if (_font.fallbackFontAssetTable.Count >= MaxFallbackCount) break; diff --git a/Assets/Cryville/Crtr/BeatTime.cs b/Assets/Cryville/Crtr/BeatTime.cs index fdee411..4e2b518 100644 --- a/Assets/Cryville/Crtr/BeatTime.cs +++ b/Assets/Cryville/Crtr/BeatTime.cs @@ -25,7 +25,7 @@ namespace Cryville.Crtr { public int d; [JsonIgnore] - public double Decimal { get { return b + (double)n / d; } } + public readonly double Decimal { get { return b + (double)n / d; } } public int CompareTo(BeatTime other) { var c = b.CompareTo(other.b); @@ -34,15 +34,15 @@ namespace Cryville.Crtr { } public override bool Equals(object obj) { - if (!(obj is BeatTime)) return false; - return Equals((BeatTime)obj); + if (obj is not BeatTime other) return false; + return Equals(other); } public bool Equals(BeatTime other) { return b.Equals(other.b) && ((double)n / d).Equals((double)other.n / other.d); } - public override int GetHashCode() { + public override readonly int GetHashCode() { return Decimal.GetHashCode(); } diff --git a/Assets/Cryville/Crtr/Browsing/Actions/ActionManager.cs b/Assets/Cryville/Crtr/Browsing/Actions/ActionManager.cs index d3f58cf..b419b4a 100644 --- a/Assets/Cryville/Crtr/Browsing/Actions/ActionManager.cs +++ b/Assets/Cryville/Crtr/Browsing/Actions/ActionManager.cs @@ -4,28 +4,27 @@ using System.Linq; namespace Cryville.Crtr.Browsing.Actions { public class ActionManager { - readonly Dictionary> _actions = new Dictionary>(); - readonly Dictionary _refCounts = new Dictionary(); + readonly Dictionary> _actions = new(); + readonly Dictionary _refCounts = new(); public event Action Changed; class ActionPriorityComparer : IComparer { - public static readonly ActionPriorityComparer Instance = new ActionPriorityComparer(); + public static readonly ActionPriorityComparer Instance = new(); public int Compare(IResourceAction x, IResourceAction y) { return x.Priority.CompareTo(y.Priority); } } void Register(Type type, IResourceAction action) { - List actions; - if (!_actions.TryGetValue(type, out actions)) { + if (!_actions.TryGetValue(type, out List actions)) { _actions.Add(type, actions = new List()); } int index = actions.BinarySearch(action, ActionPriorityComparer.Instance); if (index < 0) index = ~index; actions.Insert(index, action); if (_refCounts.ContainsKey(action)) _refCounts[action]++; - else _refCounts[action] = 0; + else _refCounts[action] = 1; Changed?.Invoke(); } public void Register(IResourceAction action) { @@ -36,8 +35,7 @@ namespace Cryville.Crtr.Browsing.Actions { } public void Unregister(Type type, IResourceAction action) { - List actions; - if (!_actions.TryGetValue(type, out actions)) return; + if (!_actions.TryGetValue(type, out List actions)) return; if (--_refCounts[action] > 0) return; actions.Remove(action); Changed?.Invoke(); @@ -54,9 +52,8 @@ namespace Cryville.Crtr.Browsing.Actions { } IEnumerable GetActions(Uri uri, IResourceMeta res, Type type) { if (type == null) return Enumerable.Empty(); - List actions; IEnumerable result; - if (_actions.TryGetValue(type, out actions)) + if (_actions.TryGetValue(type, out List actions)) result = actions.Where(i => i.CanInvoke(uri, res)); else result = Enumerable.Empty(); diff --git a/Assets/Cryville/Crtr/Browsing/Actions/OpenConfigAction.cs b/Assets/Cryville/Crtr/Browsing/Actions/OpenConfigAction.cs index 592092f..52eb840 100644 --- a/Assets/Cryville/Crtr/Browsing/Actions/OpenConfigAction.cs +++ b/Assets/Cryville/Crtr/Browsing/Actions/OpenConfigAction.cs @@ -10,7 +10,7 @@ namespace Cryville.Crtr.Browsing.Actions { public override int Priority { get { return -50; } } - static readonly Dictionary _rulesetTabs = new Dictionary(); + static readonly Dictionary _rulesetTabs = new(); public override bool CanInvoke(Uri uri, IChartDetail resource) { return true; @@ -20,15 +20,13 @@ namespace Cryville.Crtr.Browsing.Actions { } public static bool HasTab(string ruleset) { - int tabId; var master = ResourceBrowserMaster.Instance; if (master == null) return false; - return _rulesetTabs.TryGetValue(ruleset, out tabId) && master.HasTab(tabId); + return _rulesetTabs.TryGetValue(ruleset, out int tabId) && master.HasTab(tabId); } public static void Invoke(string ruleset, Action overrides = null) { var master = ResourceBrowserMaster.Instance; - int tabId; - if (_rulesetTabs.TryGetValue(ruleset, out tabId) && master.TryOpenTab(tabId)) + if (_rulesetTabs.TryGetValue(ruleset, out int tabId) && master.TryOpenTab(tabId)) return; var browser = Object.Instantiate(master.m_configBrowserPrefab).GetComponent(); try { diff --git a/Assets/Cryville/Crtr/Browsing/Actions/ResourceAction.cs b/Assets/Cryville/Crtr/Browsing/Actions/ResourceAction.cs index 3a29476..df02f29 100644 --- a/Assets/Cryville/Crtr/Browsing/Actions/ResourceAction.cs +++ b/Assets/Cryville/Crtr/Browsing/Actions/ResourceAction.cs @@ -8,15 +8,15 @@ namespace Cryville.Crtr.Browsing.Actions { public abstract bool CanInvoke(Uri uri, T resource); public bool CanInvoke(Uri uri, IResourceMeta resource) { if (resource == null) throw new ArgumentNullException("resource"); - if (!(resource is T)) throw new ArgumentException("Mismatched resource type."); - return CanInvoke(uri, (T)resource); + if (resource is not T res) throw new ArgumentException("Mismatched resource type."); + return CanInvoke(uri, res); } public abstract void Invoke(Uri uri, T resource); public void Invoke(Uri uri, IResourceMeta resource) { if (resource == null) throw new ArgumentNullException("resource"); - if (!(resource is T)) throw new ArgumentException("Mismatched resource type."); - Invoke(uri, (T)resource); + if (resource is not T res) throw new ArgumentException("Mismatched resource type."); + Invoke(uri, res); } } } diff --git a/Assets/Cryville/Crtr/Browsing/ExtensionManager.cs b/Assets/Cryville/Crtr/Browsing/ExtensionManager.cs index db8b284..9a70d1e 100644 --- a/Assets/Cryville/Crtr/Browsing/ExtensionManager.cs +++ b/Assets/Cryville/Crtr/Browsing/ExtensionManager.cs @@ -10,18 +10,17 @@ namespace Cryville.Crtr.Browsing { internal static class ExtensionManager { static bool _init; static readonly Dictionary> _converters - = new Dictionary>(); + = new(); public static ISet GetSupportedFormats() { return new HashSet(_converters.Keys); } public static bool TryGetConverters(string extension, out IEnumerable converters) { - List outResult; - bool result = _converters.TryGetValue(extension, out outResult); + bool result = _converters.TryGetValue(extension, out List outResult); converters = outResult; return result; } static readonly Dictionary _localRes - = new Dictionary(); + = new(); public static IReadOnlyDictionary GetLocalResourcePaths() { return _localRes; } @@ -62,8 +61,7 @@ namespace Cryville.Crtr.Browsing { stream.Seek(0, SeekOrigin.Begin); var buf = new byte[stream.Length]; stream.Read(buf, 0, buf.Length); - var asm = Assembly.Load(buf); - if (asm == null) throw new TypeLoadException("Failed to load the module"); + var asm = Assembly.Load(buf) ?? throw new TypeLoadException("Failed to load the module"); asms.Add(asm.GetName().Name); foreach (var type in asm.GetTypes()) { if (typeof(ExtensionInterface).IsAssignableFrom(type)) { diff --git a/Assets/Cryville/Crtr/Browsing/FileSystemResourceManager.cs b/Assets/Cryville/Crtr/Browsing/FileSystemResourceManager.cs index 1043df8..9b77ad3 100644 --- a/Assets/Cryville/Crtr/Browsing/FileSystemResourceManager.cs +++ b/Assets/Cryville/Crtr/Browsing/FileSystemResourceManager.cs @@ -17,7 +17,7 @@ namespace Cryville.Crtr.Browsing { public FileSystemEntry this[int index] { get { return _filteredItems[index]; } } IResourceMeta IResourceManager.this[int index] { get { return this[index]; } } - readonly List _dirParts = new List(); + readonly List _dirParts = new(); readonly IList m_dirParts; public IList CurrentDirectory { get { return m_dirParts; } } public int Count { get { return _filteredItems.Length; } } @@ -136,8 +136,7 @@ namespace Cryville.Crtr.Browsing { public IEnumerable Properties { get { yield return new MetaProperty("Name", _name); - if (FileSystemInfo is FileInfo) { - var file = (FileInfo)FileSystemInfo; + if (FileSystemInfo is FileInfo file) { yield return new MetaProperty("Size", new Qualified(file.Length, "B")); } yield return new MetaProperty("Write.Time", FileSystemInfo.LastWriteTime); diff --git a/Assets/Cryville/Crtr/Browsing/Legacy/LegacyResourceManager.cs b/Assets/Cryville/Crtr/Browsing/Legacy/LegacyResourceManager.cs index 8bd9980..205318a 100644 --- a/Assets/Cryville/Crtr/Browsing/Legacy/LegacyResourceManager.cs +++ b/Assets/Cryville/Crtr/Browsing/Legacy/LegacyResourceManager.cs @@ -10,11 +10,11 @@ namespace Cryville.Crtr.Browsing.Legacy { internal abstract class LegacyResourceManager : IPathedResourceManager where T : IResourceMeta { protected readonly LegacyResourceStore _store; DirectoryInfo _cd; - readonly FileSystemWatcher _watcher = new FileSystemWatcher(); + readonly FileSystemWatcher _watcher = new(); DirectoryInfo[] _items = new DirectoryInfo[0]; DirectoryInfo[] _filteredItems = new DirectoryInfo[0]; string _filter = string.Empty; - readonly List _dirParts = new List(); + readonly List _dirParts = new(); readonly IList m_dirParts; public IList CurrentDirectory { get { return m_dirParts; } } public int Count { get { return _filteredItems.Length; } } diff --git a/Assets/Cryville/Crtr/Browsing/Legacy/LegacyResourceStore.cs b/Assets/Cryville/Crtr/Browsing/Legacy/LegacyResourceStore.cs index 3cf7012..0b12818 100644 --- a/Assets/Cryville/Crtr/Browsing/Legacy/LegacyResourceStore.cs +++ b/Assets/Cryville/Crtr/Browsing/Legacy/LegacyResourceStore.cs @@ -34,8 +34,7 @@ namespace Cryville.Crtr.Browsing.Legacy { } public bool ImportFrom(Uri uri) { var file = new FileInfo(uri.LocalPath); - IEnumerable converters; - if (!ExtensionManager.TryGetConverters(file.Extension, out converters)) return false; + if (!ExtensionManager.TryGetConverters(file.Extension, out IEnumerable converters)) return false; foreach (var converter in converters) { var resources = new List(); var ses = new ConversionSession { @@ -69,8 +68,7 @@ namespace Cryville.Crtr.Browsing.Legacy { coverFile.CopyTo(Path.Combine(dir.FullName, tres.Meta.cover), true); } } - else if (res is FileResource) { - var tres = (FileResource)res; + else if (res is FileResource tres) { DirectoryInfo dest; bool singleFileFlag = false; if (res is ChartResource) diff --git a/Assets/Cryville/Crtr/Browsing/UI/BrowserItemTile.cs b/Assets/Cryville/Crtr/Browsing/UI/BrowserItemTile.cs index 0b52b03..fcabaac 100644 --- a/Assets/Cryville/Crtr/Browsing/UI/BrowserItemTile.cs +++ b/Assets/Cryville/Crtr/Browsing/UI/BrowserItemTile.cs @@ -31,7 +31,7 @@ namespace Cryville.Crtr.Browsing.UI { OnReset(); } protected override void OnReset() { - if (_cover != null) _cover.Cancel(); + _cover?.Cancel(); if (m_icon.sprite != null && m_icon.sprite != m_iconPlaceholder) { Destroy(m_icon.sprite.texture); Destroy(m_icon.sprite); diff --git a/Assets/Cryville/Crtr/Browsing/UI/BrowserTabLayout.cs b/Assets/Cryville/Crtr/Browsing/UI/BrowserTabLayout.cs index ba52a4c..a1098d5 100644 --- a/Assets/Cryville/Crtr/Browsing/UI/BrowserTabLayout.cs +++ b/Assets/Cryville/Crtr/Browsing/UI/BrowserTabLayout.cs @@ -79,8 +79,7 @@ namespace Cryville.Crtr.Browsing.UI { protected override void OnEnable() { base.OnEnable(); m_layoutMinWidth = GetTargetLayoutMinWidth(); - if (_tweener == null) - _tweener = new PropertyTweener( + _tweener ??= new PropertyTweener( () => m_layoutMinWidth, v => UpdateLayoutMinWidth(v), Tweeners.Float.With(EasingFunctions.OutQuad) diff --git a/Assets/Cryville/Crtr/Browsing/UI/DetailPanel.cs b/Assets/Cryville/Crtr/Browsing/UI/DetailPanel.cs index b665b9d..e7fcf7e 100644 --- a/Assets/Cryville/Crtr/Browsing/UI/DetailPanel.cs +++ b/Assets/Cryville/Crtr/Browsing/UI/DetailPanel.cs @@ -72,7 +72,7 @@ namespace Cryville.Crtr.Browsing.UI { } void DestroyDynamicResources() { - if (_image != null) _image.Cancel(); + _image?.Cancel(); if (m_cover.sprite != null && m_cover.sprite != m_coverPlaceholder) { Destroy(m_cover.sprite.texture); Destroy(m_cover.sprite); diff --git a/Assets/Cryville/Crtr/Browsing/UI/PathedResourceBrowser.cs b/Assets/Cryville/Crtr/Browsing/UI/PathedResourceBrowser.cs index b90feeb..5d371e8 100644 --- a/Assets/Cryville/Crtr/Browsing/UI/PathedResourceBrowser.cs +++ b/Assets/Cryville/Crtr/Browsing/UI/PathedResourceBrowser.cs @@ -34,8 +34,8 @@ namespace Cryville.Crtr.Browsing.UI { IResourceAction _importAction; readonly IResourceAction[] _importActionArray = new IResourceAction[1]; - readonly HashSet _selectedItems = new HashSet(); - readonly Dictionary _items = new Dictionary(); + readonly HashSet _selectedItems = new(); + readonly Dictionary _items = new(); bool _destroyed; protected virtual void Start() { @@ -52,10 +52,10 @@ namespace Cryville.Crtr.Browsing.UI { } void OnEnable() { - if (_manager != null) _manager.Activate(); + _manager?.Activate(); } void OnDisable() { - if (_manager != null) _manager.Deactivate(); + _manager?.Deactivate(); } public void Init(IPathedResourceManager manager) { diff --git a/Assets/Cryville/Crtr/Browsing/UI/ResourceBrowserMaster.cs b/Assets/Cryville/Crtr/Browsing/UI/ResourceBrowserMaster.cs index 366c066..2cd17d0 100644 --- a/Assets/Cryville/Crtr/Browsing/UI/ResourceBrowserMaster.cs +++ b/Assets/Cryville/Crtr/Browsing/UI/ResourceBrowserMaster.cs @@ -21,8 +21,8 @@ namespace Cryville.Crtr.Browsing.UI { internal GameObject m_configBrowserPrefab; BrowserTab _currentTab; - readonly Dictionary _tabMap = new Dictionary(); - readonly Dictionary _tabs = new Dictionary(); + readonly Dictionary _tabMap = new(); + readonly Dictionary _tabs = new(); public ActionManager Actions { get; private set; } @@ -77,8 +77,7 @@ namespace Cryville.Crtr.Browsing.UI { return _tabMap.ContainsKey(id); } public bool TryOpenTab(int id) { - BrowserTab tab; - if (_tabMap.TryGetValue(id, out tab)) { + if (_tabMap.TryGetValue(id, out BrowserTab tab)) { OnTabClicked(tab); return true; } diff --git a/Assets/Cryville/Crtr/Browsing/UI/RulesetConfigBrowser.cs b/Assets/Cryville/Crtr/Browsing/UI/RulesetConfigBrowser.cs index c40d9ef..e262a3f 100644 --- a/Assets/Cryville/Crtr/Browsing/UI/RulesetConfigBrowser.cs +++ b/Assets/Cryville/Crtr/Browsing/UI/RulesetConfigBrowser.cs @@ -31,21 +31,21 @@ namespace Cryville.Crtr.Browsing.UI { public void Load(string rulesetName, Action overrides = null) { RulesetName = rulesetName; - FileInfo file = new FileInfo(Path.Combine( + FileInfo file = new(Path.Combine( Game.GameDataPath, "rulesets", rulesetName, ".umgr" )); if (!file.Exists) { throw new FileNotFoundException("Ruleset for the resource not found\nMake sure you have imported the ruleset"); } DirectoryInfo dir = file.Directory; - using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) { + using (StreamReader reader = new(file.FullName, Encoding.UTF8)) { _ruleset = JsonConvert.DeserializeObject(reader.ReadToEnd(), new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error }); if (_ruleset.format != RulesetDefinition.CURRENT_FORMAT) throw new FormatException("Invalid ruleset file version"); _ruleset.LoadPdt(dir); } - FileInfo cfgfile = new FileInfo(Path.Combine( + FileInfo cfgfile = new(Path.Combine( Game.GameDataPath, "config", "rulesets", rulesetName + ".json" )); if (!cfgfile.Exists) { @@ -53,11 +53,10 @@ namespace Cryville.Crtr.Browsing.UI { _rscfg = new RulesetConfig(); } else { - using (StreamReader cfgreader = new StreamReader(cfgfile.FullName, Encoding.UTF8)) { - _rscfg = JsonConvert.DeserializeObject(cfgreader.ReadToEnd(), new JsonSerializerSettings() { - MissingMemberHandling = MissingMemberHandling.Error - }); - } + using StreamReader cfgreader = new(cfgfile.FullName, Encoding.UTF8); + _rscfg = JsonConvert.DeserializeObject(cfgreader.ReadToEnd(), new JsonSerializerSettings() { + MissingMemberHandling = MissingMemberHandling.Error + }); } overrides?.Invoke(_rscfg); @@ -92,12 +91,11 @@ namespace Cryville.Crtr.Browsing.UI { void OnDisable() { if (_loaded) { m_inputConfigPanel.SaveTo(_rscfg.inputs); - FileInfo cfgFile = new FileInfo(Path.Combine( + FileInfo cfgFile = new(Path.Combine( Game.GameDataPath, "config", "rulesets", RulesetName + ".json" )); - using (StreamWriter cfgWriter = new StreamWriter(cfgFile.FullName, false, Encoding.UTF8)) { - cfgWriter.Write(JsonConvert.SerializeObject(_rscfg, Game.GlobalJsonSerializerSettings)); - } + using StreamWriter cfgWriter = new(cfgFile.FullName, false, Encoding.UTF8); + cfgWriter.Write(JsonConvert.SerializeObject(_rscfg, Game.GlobalJsonSerializerSettings)); } } diff --git a/Assets/Cryville/Crtr/BuiltinResources.cs b/Assets/Cryville/Crtr/BuiltinResources.cs index d4f8016..1c0f6c8 100644 --- a/Assets/Cryville/Crtr/BuiltinResources.cs +++ b/Assets/Cryville/Crtr/BuiltinResources.cs @@ -6,13 +6,13 @@ using UnityEngine; namespace Cryville.Crtr { public static class BuiltinResources { public static Dictionary Components - = new Dictionary(); + = new(); public static Dictionary Shaders - = new Dictionary(); + = new(); public static Dictionary Meshes - = new Dictionary(); + = new(); public static Dictionary Materials - = new Dictionary(); + = new(); static bool loaded; diff --git a/Assets/Cryville/Crtr/Chart.cs b/Assets/Cryville/Crtr/Chart.cs index 4077987..525ba99 100644 --- a/Assets/Cryville/Crtr/Chart.cs +++ b/Assets/Cryville/Crtr/Chart.cs @@ -18,7 +18,7 @@ namespace Cryville.Crtr { } public abstract class ChartEvent { public BeatTime? time; - + [JsonIgnore] public float BeatPosition { get { @@ -27,7 +27,7 @@ namespace Cryville.Crtr { } public BeatTime? endtime; - + [JsonIgnore] public float EndBeatPosition { get { @@ -35,10 +35,10 @@ namespace Cryville.Crtr { return (float)endtime.Value.Decimal + BeatOffset; } } - + [JsonIgnore] public float BeatOffset; - + [JsonIgnore] public abstract int Priority { get; } @@ -66,8 +66,7 @@ namespace Cryville.Crtr { [JsonIgnore] public ReleaseEvent ReleaseEvent { get { - if (relev == null) relev = new ReleaseEvent(this); - return relev; + return relev ??= new ReleaseEvent(this); } } @@ -96,15 +95,15 @@ namespace Cryville.Crtr { SubmitPropOp("endtime", new PropOp.BeatTime(v => endtime = v)); } } - + public class ReleaseEvent : ChartEvent { public readonly ChartEvent Original; - + public ReleaseEvent(ChartEvent orig) { Original = orig; time = orig.endtime; } - + public override int Priority { get { return Original.Priority + 1; @@ -112,7 +111,7 @@ namespace Cryville.Crtr { } } public abstract class EventContainer : ChartEvent { - public List motions = new List(); + public List motions = new(); [JsonIgnore] public Clip Clip { get; private set; } @@ -120,7 +119,7 @@ namespace Cryville.Crtr { public EventContainer() { SubmitPropOp("clip", new PropOp.Clip(v => Clip = v)); } - + [JsonIgnore] public virtual IEnumerable Events { get { @@ -128,12 +127,10 @@ namespace Cryville.Crtr { } } - public virtual EventList GetEventsOfType(string type) { - switch (type) { - case "motions": return new EventList(motions); - default: throw new ArgumentException(string.Format("Unknown event type \"{0}\"", type)); - } - } + public virtual EventList GetEventsOfType(string type) => type switch { + "motions" => new EventList(motions), + _ => throw new ArgumentException(string.Format("Unknown event type \"{0}\"", type)), + }; } public abstract class EventList : ChartEvent { public IList Events { get; private set; } @@ -178,8 +175,8 @@ namespace Cryville.Crtr { public string ruleset; - public List groups = new List(); - + public List groups = new(); + public override IEnumerable Events { get { return base.Events @@ -189,33 +186,29 @@ namespace Cryville.Crtr { } } - public override EventList GetEventsOfType(string type) { - switch (type) { - case "groups": return new EventList(groups); - default: return base.GetEventsOfType(type); - } - } + public override EventList GetEventsOfType(string type) => type switch { + "groups" => new EventList(groups), + _ => base.GetEventsOfType(type), + }; public override int Priority { get { return 10; } } public class Group : EventContainer { - public List tracks = new List(); - public List notes = new List(); + public List tracks = new(); + public List notes = new(); public override IEnumerable Events { get { - return base.Events + return base.Events .Concat(notes.Cast() .Concat(tracks.Cast() )); } } - public override EventList GetEventsOfType(string type) { - switch (type) { - case "tracks": return new EventList(tracks); - case "notes": return new EventList(notes); - default: return base.GetEventsOfType(type); - } - } + public override EventList GetEventsOfType(string type) => type switch { + "tracks" => new EventList(tracks), + "notes" => new EventList(notes), + _ => base.GetEventsOfType(type), + }; public override int Priority { get { return 12; } } } @@ -228,8 +221,8 @@ namespace Cryville.Crtr { string m_motion; [JsonRequired] public string motion { - get { return m_motion == null ? ToString() : m_motion; } - set { LoadFromString(value); } + get => m_motion ?? ToString(); + set => LoadFromString(value); } #pragma warning restore IDE1006 private void LoadFromString(string s) { @@ -264,12 +257,11 @@ namespace Cryville.Crtr { [JsonIgnore] public Identifier Name { get { - if (name == default(Identifier)) throw new InvalidOperationException("Motion name not set"); + if (name == default) throw new InvalidOperationException("Motion name not set"); return name; } private set { - MotionRegistry reg; - if (!ChartPlayer.motionRegistry.TryGetValue(value, out reg)) + if (!ChartPlayer.motionRegistry.TryGetValue(value, out MotionRegistry reg)) throw new ArgumentException("Invalid motion name"); Node = new MotionNode { Value = reg.InitValue }; name = value; @@ -293,7 +285,7 @@ namespace Cryville.Crtr { SubmitPropOp("name", new PropOp.Identifier(v => { var n = new Identifier(v); if (name == n) { } - else if (name == default(Identifier)) Name = n; + else if (name == default) Name = n; else throw new RulesetViolationException(string.Format( "Motion name not matched, expected {0}, got {1}", n, Name )); @@ -306,7 +298,7 @@ namespace Cryville.Crtr { } public class Note : EventContainer { - public List judges = new List(); + public List judges = new(); public override IEnumerable Events { get { return base.Events @@ -315,12 +307,10 @@ namespace Cryville.Crtr { } } - public override EventList GetEventsOfType(string type) { - switch (type) { - case "judges": return new EventList(judges); - default: return base.GetEventsOfType(type); - } - } + public override EventList GetEventsOfType(string type) => type switch { + "judges" => new EventList(judges), + _ => base.GetEventsOfType(type), + }; public override int Priority { get { return 20; } } } @@ -345,7 +335,7 @@ namespace Cryville.Crtr { // TODO [Obsolete] public List sigs; // Signatures - // TODO [Obsolete] + // TODO [Obsolete] public class Signature : ChartEvent { public float? tempo; diff --git a/Assets/Cryville/Crtr/ChartCompatibilityHandler.cs b/Assets/Cryville/Crtr/ChartCompatibilityHandler.cs index c8ff8cb..eaa3bac 100644 --- a/Assets/Cryville/Crtr/ChartCompatibilityHandler.cs +++ b/Assets/Cryville/Crtr/ChartCompatibilityHandler.cs @@ -11,11 +11,11 @@ namespace Cryville.Crtr { public static IMotionStringParser MotionStringParser { get; private set; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var obj = JToken.ReadFrom(reader); - switch (obj["format"].ToObject()) { - case 2: MotionStringParser = MotionStringParser2.Instance; break; - case 3: MotionStringParser = MotionStringParser3.Instance; break; - default: throw new FormatException("Unsupported chart format"); - } + MotionStringParser = obj["format"].ToObject() switch { + 2 => MotionStringParser2.Instance, + 3 => MotionStringParser3.Instance, + _ => throw new FormatException("Unsupported chart format"), + }; return base.ReadJson(obj.CreateReader(), objectType, existingValue, serializer); } public override Chart Create(Type objectType) { @@ -28,12 +28,11 @@ namespace Cryville.Crtr { static MotionStringParser2 _instance; public static MotionStringParser2 Instance { get { - if (_instance == null) - _instance = new MotionStringParser2(); + _instance ??= new MotionStringParser2(); return _instance; } } - static readonly PdtFragmentInterpreter _itor = new PdtFragmentInterpreter(); + static readonly PdtFragmentInterpreter _itor = new(); static readonly PropOp _vecop = new VectorOp(v => _vecbuf = v); static float[] _vecbuf; public void Parse(string str, out Identifier name, out MotionNode node) { @@ -74,12 +73,11 @@ namespace Cryville.Crtr { static MotionStringParser3 _instance; public static MotionStringParser3 Instance { get { - if (_instance == null) - _instance = new MotionStringParser3(); + _instance ??= new MotionStringParser3(); return _instance; } } - static readonly PdtFragmentInterpreter _itor = new PdtFragmentInterpreter(); + static readonly PdtFragmentInterpreter _itor = new(); static readonly PropOp _vecop = new VectorOp(v => _vecbuf = v); static float[] _vecbuf; public void Parse(string str, out Identifier name, out MotionNode node) { diff --git a/Assets/Cryville/Crtr/ChartPlayer.cs b/Assets/Cryville/Crtr/ChartPlayer.cs index d239af3..c0b7b55 100644 --- a/Assets/Cryville/Crtr/ChartPlayer.cs +++ b/Assets/Cryville/Crtr/ChartPlayer.cs @@ -97,12 +97,12 @@ namespace Cryville.Crtr { } void OnDestroy() { - if (cbus != null) cbus.Dispose(); - if (bbus != null) bbus.Dispose(); - if (tbus != null) tbus.Dispose(); - if (nbus != null) nbus.Dispose(); - if (loadThread != null) loadThread.Abort(); - if (inputProxy != null) inputProxy.Dispose(); + cbus?.Dispose(); + bbus?.Dispose(); + tbus?.Dispose(); + nbus?.Dispose(); + loadThread?.Abort(); + inputProxy?.Dispose(); if (texs != null) foreach (var t in texs) Texture.Destroy(t.Value); Game.MainLogger.RemoveListener(loggerListener); loggerListener.Dispose(); @@ -200,24 +200,22 @@ namespace Cryville.Crtr { } } } - readonly TargetString statusstr = new TargetString(); - readonly StringBuffer statusbuf = new StringBuffer(); - readonly TargetString logsstr = new TargetString(); - readonly StringBuffer logsbuf = new StringBuffer(); - readonly List logEntries = new List(); + readonly StringBuffer statusbuf = new(); + readonly StringBuffer logsbuf = new(); + readonly List logEntries = new(); + readonly ArrayPool logBufferPool = new(); int logsLength = 0; LogHandler d_addLogEntry; void AddLogEntry(int level, string module, string msg) { - string color; - switch (level) { - case 0: color = "#888888"; break; - case 1: color = "#bbbbbb"; break; - case 2: color = "#0088ff"; break; - case 3: color = "#ffff00"; break; - case 4: color = "#ff0000"; break; - case 5: color = "#bb0000"; break; - default: color = "#ff00ff"; break; - } + string color = level switch { + 0 => "#888888", + 1 => "#bbbbbb", + 2 => "#0088ff", + 3 => "#ffff00", + 4 => "#ff0000", + 5 => "#bb0000", + _ => "#ff00ff", + }; var l = string.Format( "\n<{2}> {3}", DateTime.UtcNow.ToString("s"), color, module, msg @@ -235,10 +233,10 @@ namespace Cryville.Crtr { foreach (var l in logEntries) { logsbuf.Append(l); } - logsstr.Length = logsbuf.Count; - var larr = logsstr.TrustedAsArray(); - logsbuf.CopyTo(0, larr, 0, logsbuf.Count); - logs.SetText(larr, 0, logsbuf.Count); + var lbuf = logBufferPool.Rent(logsbuf.Count); + logsbuf.CopyTo(0, lbuf, 0, logsbuf.Count); + logs.SetText(lbuf, 0, logsbuf.Count); + logBufferPool.Return(lbuf); statusbuf.Clear(); statusbuf.AppendFormat( @@ -286,14 +284,15 @@ namespace Cryville.Crtr { ); if (judge != null) { statusbuf.Append("\n== Scores ==\n"); - var fullScoreStr = judge.GetFullFormattedScoreString(); - statusbuf.Append(fullScoreStr.TrustedAsArray(), 0, fullScoreStr.Length); + var fullScoreStrLen = judge.GetFullFormattedScoreString(logBufferPool, out char[] fullScoreStr); + statusbuf.Append(fullScoreStr, 0, fullScoreStrLen); + logBufferPool.Return(fullScoreStr); } } - statusstr.Length = statusbuf.Count; - var sarr = statusstr.TrustedAsArray(); - statusbuf.CopyTo(0, sarr, 0, statusbuf.Count); - status.SetText(sarr, 0, statusbuf.Count); + var buf = logBufferPool.Rent(statusbuf.Count); + statusbuf.CopyTo(0, buf, 0, statusbuf.Count); + status.SetText(buf, 0, statusbuf.Count); + logBufferPool.Return(buf); } #endregion @@ -386,8 +385,7 @@ namespace Cryville.Crtr { var hitPlane = new Plane(Vector3.forward, Vector3.zero); var r0 = Camera.main.ViewportPointToRay(new Vector3(0, 0, 1)); - float dist; - hitPlane.Raycast(r0, out dist); + hitPlane.Raycast(r0, out float dist); var p0 = r0.GetPoint(dist); var r1 = Camera.main.ViewportPointToRay(new Vector3(1, 1, 1)); hitPlane.Raycast(r1, out dist); @@ -397,18 +395,18 @@ namespace Cryville.Crtr { screenSize = new Vector2(Screen.width, Screen.height); frustumPlanes = GeometryUtility.CalculateFrustumPlanes(Camera.main); - FileInfo chartFile = new FileInfo(Settings.Default.LoadChart); + FileInfo chartFile = new(Settings.Default.LoadChart); - FileInfo rulesetFile = new FileInfo(Path.Combine( + FileInfo rulesetFile = new(Path.Combine( Game.GameDataPath, "rulesets", Settings.Default.LoadRuleset )); if (!rulesetFile.Exists) throw new FileNotFoundException("Ruleset for the chart not found\nMake sure you have imported the ruleset"); - FileInfo rulesetConfigFile = new FileInfo(Path.Combine( + FileInfo rulesetConfigFile = new(Path.Combine( Game.GameDataPath, "config", "rulesets", Settings.Default.LoadRulesetConfig )); if (!rulesetConfigFile.Exists) throw new FileNotFoundException("Ruleset config not found\nPlease open the config to generate"); - using (StreamReader cfgreader = new StreamReader(rulesetConfigFile.FullName, Encoding.UTF8)) { + using (StreamReader cfgreader = new(rulesetConfigFile.FullName, Encoding.UTF8)) { _rscfg = JsonConvert.DeserializeObject(cfgreader.ReadToEnd(), new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error }); @@ -416,11 +414,11 @@ namespace Cryville.Crtr { sv = _rscfg.generic.ScrollVelocity; soundOffset += _rscfg.generic.SoundOffset; - FileInfo skinFile = new FileInfo(Path.Combine( + FileInfo skinFile = new(Path.Combine( Game.GameDataPath, "skins", rulesetFile.Directory.Name, _rscfg.generic.Skin, ".umgs" )); if (!skinFile.Exists) throw new FileNotFoundException("Skin not found\nPlease specify an available skin in the config"); - using (StreamReader reader = new StreamReader(skinFile.FullName, Encoding.UTF8)) { + using (StreamReader reader = new(skinFile.FullName, Encoding.UTF8)) { skin = JsonConvert.DeserializeObject(reader.ReadToEnd(), new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error }); @@ -446,7 +444,7 @@ namespace Cryville.Crtr { } IEnumerator LoadTextures(List queue) { - Stopwatch stopwatch = new Stopwatch(); + Stopwatch stopwatch = new(); stopwatch.Start(); #if UNITY_5_4_OR_NEWER DownloadHandlerTexture texHandler = null; @@ -499,7 +497,7 @@ namespace Cryville.Crtr { } IEnumerator Prehandle() { - Stopwatch timer = new Stopwatch(); + Stopwatch timer = new(); timer.Reset(); timer.Start(); Game.MainLogger.Log(0, "Load/Prehandle", "Prehandling (iteration 2)"); yield return 0; cbus.BroadcastPreInit(); @@ -618,73 +616,72 @@ namespace Cryville.Crtr { { new Identifier("track") , new MotionRegistry(typeof(Vec1)) }, }; - using (StreamReader reader = new StreamReader(info.chartFile.FullName, Encoding.UTF8)) { - PdtEvaluator.Instance.Reset(); + using StreamReader reader = new(info.chartFile.FullName, Encoding.UTF8); + PdtEvaluator.Instance.Reset(); - LoadRuleset(info.rulesetFile); loadPregress = .05f; + LoadRuleset(info.rulesetFile); loadPregress = .05f; - chart = JsonConvert.DeserializeObject(reader.ReadToEnd(), new JsonSerializerSettings() { - MissingMemberHandling = MissingMemberHandling.Error - }); + chart = JsonConvert.DeserializeObject(reader.ReadToEnd(), new JsonSerializerSettings() { + MissingMemberHandling = MissingMemberHandling.Error + }); - Game.MainLogger.Log(0, "Load/WorkerThread", "Applying ruleset (iteration 1)"); loadPregress = .10f; - pruleset.PrePatch(chart); + Game.MainLogger.Log(0, "Load/WorkerThread", "Applying ruleset (iteration 1)"); loadPregress = .10f; + pruleset.PrePatch(chart); - Game.MainLogger.Log(0, "Load/WorkerThread", "Batching events"); loadPregress = .20f; - var batcher = new EventBatcher(chart); - batcher.Forward(); - cbus = batcher.Batch(); loadPregress = .30f; + Game.MainLogger.Log(0, "Load/WorkerThread", "Batching events"); loadPregress = .20f; + var batcher = new EventBatcher(chart); + batcher.Forward(); + cbus = batcher.Batch(); loadPregress = .30f; - LoadSkin(info.skinFile); + LoadSkin(info.skinFile); - Game.MainLogger.Log(0, "Load/WorkerThread", "Initializing judge and input"); loadPregress = .35f; - judge = new Judge(this, pruleset); - PdtEvaluator.Instance.ContextJudge = judge; + Game.MainLogger.Log(0, "Load/WorkerThread", "Initializing judge and input"); loadPregress = .35f; + judge = new Judge(this, pruleset); + PdtEvaluator.Instance.ContextJudge = judge; - inputProxy = new InputProxy(pruleset, judge, screenSize); - inputProxy.LoadFrom(_rscfg.inputs); - if (!inputProxy.IsCompleted()) { - Game.MainLogger.Log(2, "Game", "Input config not completed. Input disabled"); - inputProxy.Clear(); - } - - Game.MainLogger.Log(0, "Load/WorkerThread", "Attaching handlers"); loadPregress = .40f; - var ch = new ChartHandler(chart); - cbus.RootState.AttachHandler(ch); - foreach (var gs in cbus.RootState.Children) { - var gh = new GroupHandler((Chart.Group)gs.Key, ch); - gs.Value.AttachHandler(gh); - foreach (var ts in gs.Value.Children) { - ContainerHandler th; - if (ts.Key is Chart.Note) { - th = new NoteHandler((Chart.Note)ts.Key, gh); - } - else { - th = new TrackHandler((Chart.Track)ts.Key, gh); - } - ts.Value.AttachHandler(th); - } - } - cbus.AttachSystems(pskin, judge); - Game.MainLogger.Log(0, "Load/WorkerThread", "Prehandling (iteration 1)"); loadPregress = .60f; - using (var pbus = cbus.Clone(16)) { - pbus.Forward(); - } - - Game.MainLogger.Log(0, "Load/WorkerThread", "Cloning states (type 1)"); loadPregress = .70f; - bbus = cbus.Clone(1, -clippingDist); - Game.MainLogger.Log(0, "Load/WorkerThread", "Cloning states (type 2)"); loadPregress = .80f; - tbus = bbus.Clone(2); - Game.MainLogger.Log(0, "Load/WorkerThread", "Cloning states (type 3)"); loadPregress = .90f; - nbus = bbus.Clone(3); - loadPregress = 1; + inputProxy = new InputProxy(pruleset, judge, screenSize); + inputProxy.LoadFrom(_rscfg.inputs); + if (!inputProxy.IsCompleted()) { + Game.MainLogger.Log(2, "Game", "Input config not completed. Input disabled"); + inputProxy.Clear(); } + + Game.MainLogger.Log(0, "Load/WorkerThread", "Attaching handlers"); loadPregress = .40f; + var ch = new ChartHandler(chart); + cbus.RootState.AttachHandler(ch); + foreach (var gs in cbus.RootState.Children) { + var gh = new GroupHandler((Chart.Group)gs.Key, ch); + gs.Value.AttachHandler(gh); + foreach (var ts in gs.Value.Children) { + ContainerHandler th; + if (ts.Key is Chart.Note) { + th = new NoteHandler((Chart.Note)ts.Key, gh); + } + else { + th = new TrackHandler((Chart.Track)ts.Key, gh); + } + ts.Value.AttachHandler(th); + } + } + cbus.AttachSystems(pskin, judge); + Game.MainLogger.Log(0, "Load/WorkerThread", "Prehandling (iteration 1)"); loadPregress = .60f; + using (var pbus = cbus.Clone(16)) { + pbus.Forward(); + } + + Game.MainLogger.Log(0, "Load/WorkerThread", "Cloning states (type 1)"); loadPregress = .70f; + bbus = cbus.Clone(1, -clippingDist); + Game.MainLogger.Log(0, "Load/WorkerThread", "Cloning states (type 2)"); loadPregress = .80f; + tbus = bbus.Clone(2); + Game.MainLogger.Log(0, "Load/WorkerThread", "Cloning states (type 3)"); loadPregress = .90f; + nbus = bbus.Clone(3); + loadPregress = 1; } void LoadRuleset(FileInfo file) { DirectoryInfo dir = file.Directory; Game.MainLogger.Log(0, "Load/WorkerThread", "Loading ruleset: {0}", file); - using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) { + using (StreamReader reader = new(file.FullName, Encoding.UTF8)) { ruleset = JsonConvert.DeserializeObject(reader.ReadToEnd(), new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error }); diff --git a/Assets/Cryville/Crtr/Config/IPropertyMasterAdapter.cs b/Assets/Cryville/Crtr/Config/IPropertyMasterAdapter.cs index c1559de..f0a60bb 100644 --- a/Assets/Cryville/Crtr/Config/IPropertyMasterAdapter.cs +++ b/Assets/Cryville/Crtr/Config/IPropertyMasterAdapter.cs @@ -12,8 +12,7 @@ namespace Cryville.Crtr.Config { readonly object _target; public DefaultPropertyMasterAdapter(object target) { - if (target == null) throw new ArgumentNullException("target"); - _target = target; + _target = target ?? throw new ArgumentNullException("target"); } public string DefaultCategory { get { return "miscellaneous"; } } diff --git a/Assets/Cryville/Crtr/Config/RulesetConfig.cs b/Assets/Cryville/Crtr/Config/RulesetConfig.cs index c973f5c..93bc437 100644 --- a/Assets/Cryville/Crtr/Config/RulesetConfig.cs +++ b/Assets/Cryville/Crtr/Config/RulesetConfig.cs @@ -6,7 +6,7 @@ using System.ComponentModel; namespace Cryville.Crtr.Config { public class RulesetConfig { - public Generic generic = new Generic(); + public Generic generic = new(); public class Generic { [Category("basic")] [JsonProperty("skin")] @@ -30,9 +30,9 @@ namespace Cryville.Crtr.Config { } } public Dictionary configs - = new Dictionary(); + = new(); public Dictionary inputs - = new Dictionary(); + = new(); public class InputEntry { public string handler; public int type; diff --git a/Assets/Cryville/Crtr/Config/RulesetConfigPropertyAdapter.cs b/Assets/Cryville/Crtr/Config/RulesetConfigPropertyAdapter.cs index edfe107..4e60db4 100644 --- a/Assets/Cryville/Crtr/Config/RulesetConfigPropertyAdapter.cs +++ b/Assets/Cryville/Crtr/Config/RulesetConfigPropertyAdapter.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; namespace Cryville.Crtr.Config { internal class RulesetConfigPropertyMasterAdapter : IPropertyMasterAdapter { - readonly List _props = new List(); + readonly List _props = new(); readonly RulesetConfigStore _store; public PdtEvaluator Evaluator { get; private set; } @@ -43,11 +43,11 @@ namespace Cryville.Crtr.Config { _master = master; _def = def; Name = (string)key.Name; - switch (_def.type) { - case ConfigType.number: Type = PropertyType.Number; break; - case ConfigType.number_stepped: Type = PropertyType.NumberStepped; break; - default: Type = PropertyType.Unknown; break; - } + Type = _def.type switch { + ConfigType.number => PropertyType.Number, + ConfigType.number_stepped => PropertyType.NumberStepped, + _ => PropertyType.Unknown, + }; _rangeOp = new PropOp.Clip(v => { m_range[0] = (double)v.Behind; m_range[1] = (double)v.Ahead; @@ -85,7 +85,7 @@ namespace Cryville.Crtr.Config { public bool SetMapped { get { return false; } } - readonly PropStores.Float _numst = new PropStores.Float(); + readonly PropStores.Float _numst = new(); public object MapValue(object value) { _numst.Value = (float)(double)value; if (_def.value == null) return _numst.Value; diff --git a/Assets/Cryville/Crtr/Config/RulesetConfigStore.cs b/Assets/Cryville/Crtr/Config/RulesetConfigStore.cs index 7302e93..7af7640 100644 --- a/Assets/Cryville/Crtr/Config/RulesetConfigStore.cs +++ b/Assets/Cryville/Crtr/Config/RulesetConfigStore.cs @@ -6,8 +6,8 @@ using System.Collections.Generic; namespace Cryville.Crtr.Config { public class RulesetConfigStore { - readonly IntKeyedDictionary _srcs = new IntKeyedDictionary(); - readonly Dictionary _revMap = new Dictionary(); + readonly IntKeyedDictionary _srcs = new(); + readonly Dictionary _revMap = new(); readonly Dictionary _values; public RulesetConfigStore(Dictionary defs, Dictionary values) { _values = values; diff --git a/Assets/Cryville/Crtr/Config/UI/InputConfigPanel.cs b/Assets/Cryville/Crtr/Config/UI/InputConfigPanel.cs index 59c5303..984aac6 100644 --- a/Assets/Cryville/Crtr/Config/UI/InputConfigPanel.cs +++ b/Assets/Cryville/Crtr/Config/UI/InputConfigPanel.cs @@ -15,7 +15,7 @@ namespace Cryville.Crtr.Config.UI { PdtRuleset _ruleset; InputProxy _proxy; - readonly Dictionary _entries = new Dictionary(); + readonly Dictionary _entries = new(); public void Load(PdtRuleset ruleset, RulesetConfig rulesetConfig) { _ruleset = ruleset; diff --git a/Assets/Cryville/Crtr/Config/UI/InputDialog.cs b/Assets/Cryville/Crtr/Config/UI/InputDialog.cs index cb3eaca..2f2011d 100644 --- a/Assets/Cryville/Crtr/Config/UI/InputDialog.cs +++ b/Assets/Cryville/Crtr/Config/UI/InputDialog.cs @@ -29,7 +29,7 @@ namespace Cryville.Crtr.Config.UI { int _targetDim; PhysicalDimension? _targetPDim; bool _targetNotNull; - readonly Dictionary _recvsrcs = new Dictionary(); + readonly Dictionary _recvsrcs = new(); void ShowInternal(Action callback, string message, InputDefinition def, InputProxy proxy) { _active = true; _callback = callback; @@ -56,7 +56,7 @@ namespace Cryville.Crtr.Config.UI { var result = new PhysicalDimension(); foreach (var comp in comps) { int dim = 1; - if (comp.Length > 1) dim = int.Parse(comp.Substring(1)); + if (comp.Length > 1) dim = int.Parse(comp[1..]); switch (comp[0]) { case 'T': result.Time += dim; break; case 'L': result.Length += dim; break; @@ -98,8 +98,7 @@ namespace Cryville.Crtr.Config.UI { Action _d_HandleInputEvent; void HandleInputEvent(InputEvent ev) { InputSource src = ev.Identifier.Source; - InputDialogEntry entry; - if (!_recvsrcs.TryGetValue(src, out entry)) { + if (!_recvsrcs.TryGetValue(src, out InputDialogEntry entry)) { _recvsrcs.Add(src, entry = AddSourceItem(src)); if (_proxy.IsUsed(src)) { entry.Status |= InputDeviceStatus.Used; diff --git a/Assets/Cryville/Crtr/Config/UI/InputDialogEntry.cs b/Assets/Cryville/Crtr/Config/UI/InputDialogEntry.cs index ba401b2..daf6f5e 100644 --- a/Assets/Cryville/Crtr/Config/UI/InputDialogEntry.cs +++ b/Assets/Cryville/Crtr/Config/UI/InputDialogEntry.cs @@ -74,8 +74,7 @@ namespace Cryville.Crtr.Config.UI { Dictionary _activeInputs; public void OnInputEvent(InputEvent ev) { var id = ev.Identifier.Id; - InputVector lastVec; - if (!_activeInputs.TryGetValue(id, out lastVec)) { + if (!_activeInputs.TryGetValue(id, out InputVector lastVec)) { if (ev.To.IsNull) return; _activeInputs.Add(id, lastVec = ev.To.Vector); } diff --git a/Assets/Cryville/Crtr/Config/UI/PVPNumberBase.cs b/Assets/Cryville/Crtr/Config/UI/PVPNumberBase.cs index 76cda50..241e78d 100644 --- a/Assets/Cryville/Crtr/Config/UI/PVPNumberBase.cs +++ b/Assets/Cryville/Crtr/Config/UI/PVPNumberBase.cs @@ -111,9 +111,8 @@ namespace Cryville.Crtr.Config.UI { } float GetRatioFromPos(Vector2 pos) { - Vector2 lp; RectTransform handleArea = parent.m_handleArea; - if (RectTransformUtility.ScreenPointToLocalPointInRectangle(handleArea, pos, cam, out lp)) { + if (RectTransformUtility.ScreenPointToLocalPointInRectangle(handleArea, pos, cam, out Vector2 lp)) { lp -= handleArea.rect.position; return Mathf.Clamp01(lp.x / handleArea.rect.width); } @@ -121,8 +120,7 @@ namespace Cryville.Crtr.Config.UI { } void SetValueFromPos(Vector2 pos) { - double min, max; - parent.GetRange(out min, out max); + parent.GetRange(out double min, out double max); double ratio = GetRatioFromPos(pos); double result = parent.GetValue(ratio, Time.deltaTime, min, max); if (result < min) result = min; diff --git a/Assets/Cryville/Crtr/Config/UI/PropertyMasterPanel.cs b/Assets/Cryville/Crtr/Config/UI/PropertyMasterPanel.cs index 2c3ce45..b0531af 100644 --- a/Assets/Cryville/Crtr/Config/UI/PropertyMasterPanel.cs +++ b/Assets/Cryville/Crtr/Config/UI/PropertyMasterPanel.cs @@ -34,14 +34,13 @@ namespace Cryville.Crtr.Config.UI { } } - readonly Dictionary> _categories = new Dictionary>(); + readonly Dictionary> _categories = new(); public void LoadProperties() { _categories.Clear(); _invalidated = false; if (Adapter == null) return; foreach (var p in Adapter.GetProperties()) { - string category = p.Category; - if (category == null) category = Adapter.DefaultCategory; + string category = p.Category ?? Adapter.DefaultCategory; if (!_categories.ContainsKey(category)) _categories.Add(category, new List()); _categories[category].Add(p); diff --git a/Assets/Cryville/Crtr/Event/ChartHandler.cs b/Assets/Cryville/Crtr/Event/ChartHandler.cs index 9d3808b..492adee 100644 --- a/Assets/Cryville/Crtr/Event/ChartHandler.cs +++ b/Assets/Cryville/Crtr/Event/ChartHandler.cs @@ -8,7 +8,7 @@ namespace Cryville.Crtr.Event { protected override TransformHandler Parent { get { return null; } } readonly Chart chart; - readonly List sounds = new List(); + readonly List sounds = new(); public ChartHandler(Chart _chart) { chart = _chart; @@ -25,8 +25,7 @@ namespace Cryville.Crtr.Event { if (s.CloneType == 16) { if (ev == null) { } else if (ev.Unstamped == null) { } - else if (ev.Unstamped is Chart.Sound) { - Chart.Sound tev = (Chart.Sound)ev.Unstamped; + else if (ev.Unstamped is Chart.Sound tev) { var dir = new DirectoryInfo(Path.Combine(Game.GameDataPath, "songs", StringUtils.EscapeFileName(tev.id))); var files = dir.GetFiles(); var source = new LibavFileAudioSource(files[0].FullName); diff --git a/Assets/Cryville/Crtr/Event/ContainerHandler.cs b/Assets/Cryville/Crtr/Event/ContainerHandler.cs index fe19a34..969a171 100644 --- a/Assets/Cryville/Crtr/Event/ContainerHandler.cs +++ b/Assets/Cryville/Crtr/Event/ContainerHandler.cs @@ -41,7 +41,7 @@ namespace Cryville.Crtr.Event { protected Transform RootTransform; - readonly List _comps = new List(); + readonly List _comps = new(); protected IEnumerable Components { get { return _comps; } } public Vector3 Position { get; protected set; } @@ -68,7 +68,7 @@ namespace Cryville.Crtr.Event { static readonly int _var_current_time = IdentifierManager.Shared.Request("current_time"); static readonly int _var_invisible_bounds = IdentifierManager.Shared.Request("invisible_bounds"); - public readonly IntKeyedDictionary PropSrcs = new IntKeyedDictionary(); + public readonly IntKeyedDictionary PropSrcs = new(); SkinContainer skinContainer; protected Judge judge; public void AttachSystems(PdtSkin skin, Judge judge) { @@ -76,9 +76,9 @@ namespace Cryville.Crtr.Event { this.judge = judge; } - public readonly IntKeyedDictionary> Anchors = new IntKeyedDictionary>(); - public readonly IntKeyedDictionary DynamicAnchors = new IntKeyedDictionary(); - public readonly IntKeyedDictionary DynamicAnchorSetTime = new IntKeyedDictionary(); + public readonly IntKeyedDictionary> Anchors = new(); + public readonly IntKeyedDictionary DynamicAnchors = new(); + public readonly IntKeyedDictionary DynamicAnchorSetTime = new(); Anchor a_cur; Anchor a_head; Anchor a_tail; @@ -98,8 +98,7 @@ namespace Cryville.Crtr.Event { DynamicAnchors.Add(name, result); DynamicAnchorSetTime.Add(name, double.NaN); } - List list; - if (!Anchors.TryGetValue(name, out list)) + if (!Anchors.TryGetValue(name, out List list)) Anchors.Add(name, list = new List()); list.Add(result); return result; @@ -158,8 +157,7 @@ namespace Cryville.Crtr.Event { } #endregion public virtual void Update(ContainerState s, StampedEvent ev) { - if (ev is StampedEvent.Anchor) { - var tev = (StampedEvent.Anchor)ev; + if (ev is StampedEvent.Anchor tev) { if (tev.Target == a_head) { if (s.CloneType == 2) SetGraphicalActive(true, s); else SetPreGraphicalActive(true, s); @@ -234,7 +232,7 @@ namespace Cryville.Crtr.Event { } } static readonly SimpleObjectPool anchorEvPool - = new SimpleObjectPool(1024); + = new(1024); void PushAnchorEvent(ContainerState state, double time, Anchor anchor, int priority = 0, bool forced = false) { var tev = anchorEvPool.Rent(); tev.Time = time; @@ -245,8 +243,8 @@ namespace Cryville.Crtr.Event { state.Bus.PushTempEvent(tev); } public virtual void Discard(ContainerState s, StampedEvent ev) { - if (ev is StampedEvent.Anchor) { - ReturnAnchorEvent((StampedEvent.Anchor)ev); + if (ev is StampedEvent.Anchor anchor) { + ReturnAnchorEvent(anchor); } } void ReturnAnchorEvent(StampedEvent.Anchor ev) { @@ -264,8 +262,7 @@ namespace Cryville.Crtr.Event { Anchor _openedAnchor; public int OpenedAnchorName { get { return _openedAnchor == null ? 0 : _openedAnchor.Name; } } public bool TryGetAnchorsByName(int name, out IReadOnlyCollection result) { - List anchors; - var ret = Anchors.TryGetValue(name, out anchors); + var ret = Anchors.TryGetValue(name, out List anchors); result = anchors; return ret; } diff --git a/Assets/Cryville/Crtr/Event/ContainerState.cs b/Assets/Cryville/Crtr/Event/ContainerState.cs index 15c46db..287532c 100644 --- a/Assets/Cryville/Crtr/Event/ContainerState.cs +++ b/Assets/Cryville/Crtr/Event/ContainerState.cs @@ -19,11 +19,11 @@ namespace Cryville.Crtr.Event { public ushort Depth; public Dictionary Children - = new Dictionary(); + = new(); HashSet ActiveChildren - = new HashSet(); + = new(); public Dictionary> TypedChildren - = new Dictionary>(); + = new(); public ContainerState GetChild(int index, Type handlerType) { var list = TypedChildren[handlerType]; @@ -110,8 +110,7 @@ namespace Cryville.Crtr.Event { void AddChild(EventContainer c, ContainerState parent) { parent.Children.Add(c, this); Type t = c.GetType(); - List tc; - if (!parent.TypedChildren.TryGetValue(t, out tc)) + if (!parent.TypedChildren.TryGetValue(t, out List tc)) parent.TypedChildren.Add(t, tc = new List()); tc.Add(this); } @@ -159,15 +158,13 @@ namespace Cryville.Crtr.Event { if (dest.m_active) dest.Bus.NotifyActiveChanged(dest); foreach (var mv in Values) { - RealtimeMotionValue dv; - if (dest.Values.TryGetValue(mv.Key, out dv)) mv.Value.CopyTo(dv, false); + if (dest.Values.TryGetValue(mv.Key, out RealtimeMotionValue dv)) mv.Value.CopyTo(dv, false); else dest.Values.Add(mv.Key, mv.Value.Clone()); } foreach (var cv in dest.CachedValues) cv.Value.Valid = false; foreach (var cv in CachedValues) { - MotionCache dv; - if (!dest.CachedValues.TryGetValue(cv.Key, out dv)) { + if (!dest.CachedValues.TryGetValue(cv.Key, out MotionCache dv)) { dest.CachedValues.Add(cv.Key, dv = dest._mcpa.Rent(cv.Key)); } cv.Value.CopyTo(dv); @@ -229,13 +226,12 @@ namespace Cryville.Crtr.Event { #region Motion readonly CategorizedPoolAccessor _rmvpa; readonly CategorizedPoolAccessor _mcpa; - Dictionary PlayingMotions = new Dictionary(4); + Dictionary PlayingMotions = new(4); IntKeyedDictionary Values; IntKeyedDictionary CachedValues; void InvalidateMotion(int name) { - MotionCache cache; - if (!CachedValues.TryGetValue(name, out cache)) + if (!CachedValues.TryGetValue(name, out MotionCache cache)) CachedValues.Add(name, cache = _mcpa.Rent(name)); cache.Valid = false; foreach (var c in ActiveChildren) @@ -243,8 +239,7 @@ namespace Cryville.Crtr.Event { } public Vector GetComputedValue(int key) { - MotionCache tr; - if (!CachedValues.TryGetValue(key, out tr)) + if (!CachedValues.TryGetValue(key, out MotionCache tr)) CachedValues.Add(key, tr = _mcpa.Rent(key)); Vector r = tr.Value; if (tr.Valid) return r; @@ -322,8 +317,8 @@ namespace Cryville.Crtr.Event { public void Discard(StampedEvent ev) { Handler.Discard(this, ev); - if (ev is StampedEvent.RelativeMotion) { - ReturnRelativeMotionEvent((StampedEvent.RelativeMotion)ev); + if (ev is StampedEvent.RelativeMotion motion) { + ReturnRelativeMotionEvent(motion); } else if (ev.Origin is StampedEvent.RelativeMotion) { ReturnEndRelativeMotionEvent((StampedEvent.Temporary)ev); @@ -345,8 +340,7 @@ namespace Cryville.Crtr.Event { _rmvpa.Return(mv); } } - else if (ev is StampedEvent.RelativeMotion) { - var tev = (StampedEvent.RelativeMotion)ev; + else if (ev is StampedEvent.RelativeMotion tev) { var mv = _rmvpa.Rent(tev.Name); mv.CloneTypeFlag = CloneType; Values[tev.Name].CopyTo(mv, true); @@ -369,13 +363,13 @@ namespace Cryville.Crtr.Event { } else if (ev.Origin != null) { var oev = ev.Origin; - if (oev is StampedEvent.RelativeMotion) { + if (oev is StampedEvent.RelativeMotion motion) { Update(ev); var mv = PlayingMotions[oev]; if (mv.CloneTypeFlag == CloneType) _rmvpa.Return(mv); PlayingMotions.Remove(oev); ReturnEndRelativeMotionEvent((StampedEvent.Temporary)ev); - ReturnRelativeMotionEvent((StampedEvent.RelativeMotion)oev); + ReturnRelativeMotionEvent(motion); } else { var nev = oev.Unstamped; @@ -385,8 +379,7 @@ namespace Cryville.Crtr.Event { if (mv.CloneTypeFlag == CloneType) _rmvpa.Return(mv); PlayingMotions.Remove(oev); } - else if (nev is EventContainer) { - var cev = (EventContainer)nev; + else if (nev is EventContainer cev) { var ccs = Children[cev]; UpdateMotions(); ccs.LogicalActive = false; @@ -455,8 +448,8 @@ namespace Cryville.Crtr.Event { } } } - static readonly PropStores.Float _ttimest = new PropStores.Float(); - static readonly PropStores.Vector4 _transst = new PropStores.Vector4(); + static readonly PropStores.Float _ttimest = new(); + static readonly PropStores.Vector4 _transst = new(); Vector4 GetTransition(float time, PdtExpression transition) { if (time >= 1) return Vector4.one; if (transition == null) return new Vector4(time, time, time, time); @@ -495,9 +488,9 @@ namespace Cryville.Crtr.Event { } static readonly SimpleObjectPool relmEvPool - = new SimpleObjectPool(1024); + = new(1024); static readonly SimpleObjectPool erelmEvPool - = new SimpleObjectPool(1024); + = new(1024); public void PreAnchor() { PushRelativeMotions(Handler.ns.Bus); Handler.PreAnchor(); diff --git a/Assets/Cryville/Crtr/Event/EventBatch.cs b/Assets/Cryville/Crtr/Event/EventBatch.cs index 10faa6c..cf532d8 100644 --- a/Assets/Cryville/Crtr/Event/EventBatch.cs +++ b/Assets/Cryville/Crtr/Event/EventBatch.cs @@ -9,7 +9,7 @@ namespace Cryville.Crtr.Event { private set; } - readonly List queue = new List(); + readonly List queue = new(); public int Count { get { return queue.Count; } } diff --git a/Assets/Cryville/Crtr/Event/EventBatcher.cs b/Assets/Cryville/Crtr/Event/EventBatcher.cs index 92d502f..251dbc1 100644 --- a/Assets/Cryville/Crtr/Event/EventBatcher.cs +++ b/Assets/Cryville/Crtr/Event/EventBatcher.cs @@ -12,16 +12,16 @@ namespace Cryville.Crtr.Event { readonly Chart chart; ContainerState rootState; readonly Dictionary containerMap - = new Dictionary(); + = new(); readonly Dictionary stateMap - = new Dictionary(); + = new(); readonly Dictionary map - = new Dictionary(); + = new(); readonly Dictionary> coeventMap - = new Dictionary>(); - readonly HashSet coevents = new HashSet(); - readonly List stampedEvents = new List(); - readonly List batches = new List(); + = new(); + readonly HashSet coevents = new(); + readonly List stampedEvents = new(); + readonly List batches = new(); double beat; float tempo; @@ -58,8 +58,8 @@ namespace Cryville.Crtr.Event { } Events.Add(ev); containerMap.Add(ev, cs); - if (ev is EventContainer) - AddEventContainer((EventContainer)ev, cs); + if (ev is EventContainer container) + AddEventContainer(container, cs); } } @@ -104,17 +104,16 @@ namespace Cryville.Crtr.Event { var pev = map[oev]; pev.ReleaseEvent = sev; sev.Origin = pev; - if (oev is EventContainer) { + if (oev is EventContainer container) { stampedEvents.Add(new StampedEvent.ClipAhead { Container = con, Origin = pev, - Time = etime + ((EventContainer)oev).Clip.Ahead, + Time = etime + container.Clip.Ahead, }); } } if (con != null && coevents.Contains(ev)) { - List cevs; - if (!coeventMap.TryGetValue(con, out cevs)) { + if (!coeventMap.TryGetValue(con, out List cevs)) { coeventMap.Add(con, cevs = new List()); } cevs.Add(sev); @@ -168,9 +167,8 @@ namespace Cryville.Crtr.Event { } void BatchCoevents(StampedEvent ev, List ocevs = null) { - if (!(ev.Unstamped is EventContainer)) return; - List cevs; - if (coeventMap.TryGetValue((EventContainer)ev.Unstamped, out cevs)) { + if (ev.Unstamped is not EventContainer container) return; + if (coeventMap.TryGetValue(container, out List cevs)) { var rootFlag = ocevs == null; if (rootFlag) ev.Coevents = ocevs = new List(); foreach (var cev in cevs) { diff --git a/Assets/Cryville/Crtr/Event/EventBus.cs b/Assets/Cryville/Crtr/Event/EventBus.cs index f67e31b..db8708f 100644 --- a/Assets/Cryville/Crtr/Event/EventBus.cs +++ b/Assets/Cryville/Crtr/Event/EventBus.cs @@ -12,11 +12,11 @@ namespace Cryville.Crtr.Event { } Dictionary states - = new Dictionary(); + = new(); HashSet activeStates - = new HashSet(); + = new(); HashSet invalidatedStates - = new HashSet(); + = new(); public int ActiveStateCount { get { return activeStates.Count; } } public EventBus(ContainerState root, List b) : base(b) { @@ -84,14 +84,14 @@ namespace Cryville.Crtr.Event { s.Value.AttachSystems(skin, judge); } - List tempEvents = new List(); + List tempEvents = new(); public void PushTempEvent(StampedEvent.Temporary ev) { var index = tempEvents.BinarySearch(ev); if (index < 0) index = ~index; tempEvents.Insert(index, ev); } - readonly StampedEvent.Temporary _dummyEvent = new StampedEvent.Temporary(); + readonly StampedEvent.Temporary _dummyEvent = new(); public void StripTempEvents() { _dummyEvent.Time = Time; var index = tempEvents.BinarySearch(_dummyEvent); diff --git a/Assets/Cryville/Crtr/Event/GroupHandler.cs b/Assets/Cryville/Crtr/Event/GroupHandler.cs index a170ed0..1107cc6 100644 --- a/Assets/Cryville/Crtr/Event/GroupHandler.cs +++ b/Assets/Cryville/Crtr/Event/GroupHandler.cs @@ -39,7 +39,7 @@ namespace Cryville.Crtr.Event { } class Vector3Operator : IVectorOperator { - public static Vector3Operator Instance = new Vector3Operator(); + public static Vector3Operator Instance = new(); public Vector3 Add(Vector3 lhs, Vector3 rhs) { return lhs + rhs; diff --git a/Assets/Cryville/Crtr/Event/MotionCache.cs b/Assets/Cryville/Crtr/Event/MotionCache.cs index b9c2562..62f709f 100644 --- a/Assets/Cryville/Crtr/Event/MotionCache.cs +++ b/Assets/Cryville/Crtr/Event/MotionCache.cs @@ -21,8 +21,9 @@ namespace Cryville.Crtr.Event { _reg = ChartPlayer.motionRegistry[name]; } protected override MotionCache Construct() { - var result = new MotionCache(); - result.Value = (Vector)Activator.CreateInstance(_reg.Type); + var result = new MotionCache { + Value = (Vector)Activator.CreateInstance(_reg.Type) + }; return result; } protected override void Reset(MotionCache obj) { diff --git a/Assets/Cryville/Crtr/Event/NoteHandler.cs b/Assets/Cryville/Crtr/Event/NoteHandler.cs index ed77eec..e21b06f 100644 --- a/Assets/Cryville/Crtr/Event/NoteHandler.cs +++ b/Assets/Cryville/Crtr/Event/NoteHandler.cs @@ -17,15 +17,15 @@ namespace Cryville.Crtr.Event { public override string TypeName { get { return "note"; } } SectionalGameObject[] sgos; - readonly Dictionary judges = new Dictionary(); + readonly Dictionary judges = new(); class JudgeState { static readonly int _var_judge_result = IdentifierManager.Shared.Request("judge_result"); static readonly int _var_judge_time_absolute = IdentifierManager.Shared.Request("judge_time_absolute"); static readonly int _var_judge_time_relative = IdentifierManager.Shared.Request("judge_time_relative"); public Anchor StaticAnchor { get; private set; } - readonly PropStores.Float _jtabsst = new PropStores.Float(); - readonly PropStores.Float _jtrelst = new PropStores.Float(); - readonly PropStores.Identifier _resultst = new PropStores.Identifier(); + readonly PropStores.Float _jtabsst = new(); + readonly PropStores.Float _jtrelst = new(); + readonly PropStores.Identifier _resultst = new(); public JudgeState(NoteHandler handler, int name) { StaticAnchor = handler.RegisterAnchor(handler.judge.judgeMap[name], false, 3); } @@ -147,8 +147,7 @@ namespace Cryville.Crtr.Event { } internal void ReportJudge(JudgeEvent ev, float time, Identifier result) { - JudgeState state; - if (!judges.TryGetValue(ev.BaseEvent, out state)) return; + if (!judges.TryGetValue(ev.BaseEvent, out JudgeState state)) return; state.MarkJudged(time, (float)(ev.StartTime - time), result.Key); } } diff --git a/Assets/Cryville/Crtr/Event/RealtimeMotionValue.cs b/Assets/Cryville/Crtr/Event/RealtimeMotionValue.cs index 8e9f591..0fc2302 100644 --- a/Assets/Cryville/Crtr/Event/RealtimeMotionValue.cs +++ b/Assets/Cryville/Crtr/Event/RealtimeMotionValue.cs @@ -48,21 +48,19 @@ namespace Cryville.Crtr.Event { } public MotionNode GetRelativeNode(short id) { - MotionNode result; - RelativeNodes.TryGetValue(id, out result); + RelativeNodes.TryGetValue(id, out MotionNode result); return result; } public void SetRelativeNode(MotionNode node) { - MotionNode cnode; - if (!RelativeNodes.TryGetValue(node.Id, out cnode)) { + if (!RelativeNodes.TryGetValue(node.Id, out MotionNode cnode)) { cnode = MotionNodePool.Shared.Rent(_type); cnode.Id = node.Id; RelativeNodes.Add(node.Id, cnode); } - if (node.Time != null) node.Time.CopyTo(cnode.Time); - if (node.EndTime != null) node.EndTime.CopyTo(cnode.EndTime); - if (node.Value != null) node.Value.CopyTo(cnode.Value); + node.Time?.CopyTo(cnode.Time); + node.EndTime?.CopyTo(cnode.EndTime); + node.Value?.CopyTo(cnode.Value); } /// diff --git a/Assets/Cryville/Crtr/Event/TransformHandler.cs b/Assets/Cryville/Crtr/Event/TransformHandler.cs index 10ba7dc..a54b9e7 100644 --- a/Assets/Cryville/Crtr/Event/TransformHandler.cs +++ b/Assets/Cryville/Crtr/Event/TransformHandler.cs @@ -7,7 +7,7 @@ namespace Cryville.Crtr.Event { protected abstract TransformHandler Parent { get; } public override void Init() { base.Init(); - sgos = Components.Where(c => c is SectionalGameObject).Cast().ToArray(); + sgos = Components.OfType().ToArray(); } SectionalGameObject[] sgos; diff --git a/Assets/Cryville/Crtr/Extensions/ExtensionImporter.cs b/Assets/Cryville/Crtr/Extensions/ExtensionImporter.cs index 7f2d0d2..28f9913 100644 --- a/Assets/Cryville/Crtr/Extensions/ExtensionImporter.cs +++ b/Assets/Cryville/Crtr/Extensions/ExtensionImporter.cs @@ -12,9 +12,8 @@ namespace Cryville.Crtr.Extensions { public override void Convert(FileInfo file, ConversionSession ses) { try { - using (var stream = file.OpenRead()) { - ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate)); - } + using var stream = file.OpenRead(); + ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate)); } catch (BadImageFormatException ex) { throw new FormatException("Invalid extension.", ex); diff --git a/Assets/Cryville/Crtr/Extensions/Umg/ChartResourceImporter.cs b/Assets/Cryville/Crtr/Extensions/Umg/ChartResourceImporter.cs index 28f8240..5e6d89f 100644 --- a/Assets/Cryville/Crtr/Extensions/Umg/ChartResourceImporter.cs +++ b/Assets/Cryville/Crtr/Extensions/Umg/ChartResourceImporter.cs @@ -13,19 +13,17 @@ namespace Cryville.Crtr.Extensions.Umg { public override void Convert(FileInfo file, ConversionSession ses) { var meta = Path.Combine(file.Directory.FullName, "meta.json"); if (!File.Exists(meta)) throw new FileNotFoundException("Meta file for the chart not found"); - using (StreamReader reader = new StreamReader(meta, Encoding.UTF8)) { - var data = JsonConvert.DeserializeObject(reader.ReadToEnd()); - ses.AddResource(new ChartResource(data.name, file)); - } + using StreamReader reader = new(meta, Encoding.UTF8); + var data = JsonConvert.DeserializeObject(reader.ReadToEnd()); + ses.AddResource(new ChartResource(data.name, file)); } } public class ChartResource : FileResource { public ChartResource(string name, FileInfo master) : base(name, master) { - using (var reader = new StreamReader(master.FullName)) { - var meta = JsonConvert.DeserializeObject(reader.ReadToEnd()); - Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".json"))); - if (meta.cover != null) Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.cover))); - } + using var reader = new StreamReader(master.FullName); + var meta = JsonConvert.DeserializeObject(reader.ReadToEnd()); + Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".json"))); + if (meta.cover != null) Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.cover))); } } } diff --git a/Assets/Cryville/Crtr/Extensions/Umg/RulesetResourceImporter.cs b/Assets/Cryville/Crtr/Extensions/Umg/RulesetResourceImporter.cs index d89b86e..eef6068 100644 --- a/Assets/Cryville/Crtr/Extensions/Umg/RulesetResourceImporter.cs +++ b/Assets/Cryville/Crtr/Extensions/Umg/RulesetResourceImporter.cs @@ -12,18 +12,16 @@ namespace Cryville.Crtr.Extensions.Umg { } public override void Convert(FileInfo file, ConversionSession ses) { - using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) { - var data = JsonConvert.DeserializeObject(reader.ReadToEnd()); - ses.AddResource(new RulesetResource(data.name, file)); - } + using StreamReader reader = new(file.FullName, Encoding.UTF8); + var data = JsonConvert.DeserializeObject(reader.ReadToEnd()); + ses.AddResource(new RulesetResource(data.name, file)); } } public class RulesetResource : FileResource { public RulesetResource(string name, FileInfo master) : base(name, master) { - using (var reader = new StreamReader(master.FullName)) { - var meta = JsonConvert.DeserializeObject(reader.ReadToEnd()); - Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".pdt"))); - } + using var reader = new StreamReader(master.FullName); + var meta = JsonConvert.DeserializeObject(reader.ReadToEnd()); + Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".pdt"))); } } } diff --git a/Assets/Cryville/Crtr/Extensions/Umg/SkinResourceImporter.cs b/Assets/Cryville/Crtr/Extensions/Umg/SkinResourceImporter.cs index 61fb189..eabc78a 100644 --- a/Assets/Cryville/Crtr/Extensions/Umg/SkinResourceImporter.cs +++ b/Assets/Cryville/Crtr/Extensions/Umg/SkinResourceImporter.cs @@ -12,22 +12,20 @@ namespace Cryville.Crtr.Extensions.Umg { } public override void Convert(FileInfo file, ConversionSession ses) { - using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) { - var data = JsonConvert.DeserializeObject(reader.ReadToEnd()); - ses.AddResource(new SkinResource(data.name, file)); - } + using StreamReader reader = new(file.FullName, Encoding.UTF8); + var data = JsonConvert.DeserializeObject(reader.ReadToEnd()); + ses.AddResource(new SkinResource(data.name, file)); } } public class SkinResource : FileResource { public string RulesetName { get; private set; } public SkinResource(string name, FileInfo master) : base(name, master) { - using (var reader = new StreamReader(master.FullName)) { - var meta = JsonConvert.DeserializeObject(reader.ReadToEnd()); - RulesetName = meta.ruleset; - Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".pdt"))); - foreach (var frame in meta.frames) { - Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, frame))); - } + using var reader = new StreamReader(master.FullName); + var meta = JsonConvert.DeserializeObject(reader.ReadToEnd()); + RulesetName = meta.ruleset; + Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".pdt"))); + foreach (var frame in meta.frames) { + Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, frame))); } } } diff --git a/Assets/Cryville/Crtr/Game.cs b/Assets/Cryville/Crtr/Game.cs index 9310657..8b74bec 100644 --- a/Assets/Cryville/Crtr/Game.cs +++ b/Assets/Cryville/Crtr/Game.cs @@ -36,10 +36,10 @@ namespace Cryville.Crtr { public static SimpleSequencerSource AudioSequencer; public static SimpleSequencerSession AudioSession; public static InputManager InputManager; - public static readonly NetworkTaskWorker NetworkTaskWorker = new NetworkTaskWorker(); + public static readonly NetworkTaskWorker NetworkTaskWorker = new(); public static readonly JsonSerializerSettings GlobalJsonSerializerSettings - = new JsonSerializerSettings() { + = new() { DefaultValueHandling = DefaultValueHandling.Ignore, }; @@ -168,10 +168,9 @@ namespace Cryville.Crtr { if (!dir.Exists || Settings.Default.LastRunVersion != Application.version) { Directory.CreateDirectory(dir.FullName); var defaultData = Resources.Load("default"); - using (var zip = ZipFile.Read(defaultData.bytes)) { - zip.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently; - zip.ExtractAll(Settings.Default.GameDataPath); - } + using var zip = ZipFile.Read(defaultData.bytes); + zip.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently; + zip.ExtractAll(Settings.Default.GameDataPath); } Settings.Default.LastRunVersion = Application.version; @@ -193,18 +192,16 @@ namespace Cryville.Crtr { } static readonly Encoding _encoding = new UTF8Encoding(false, true); - static readonly XmlReaderSettings _xmlSettings = new XmlReaderSettings { + static readonly XmlReaderSettings _xmlSettings = new() { DtdProcessing = DtdProcessing.Ignore, }; static XDocument LoadXmlDocument(string path) { return LoadXmlDocument(Resources.Load(path)); } static XDocument LoadXmlDocument(TextAsset asset) { - using (var stream = new MemoryStream(_encoding.GetBytes(asset.text))) { - using (var reader = XmlReader.Create(stream, _xmlSettings)) { - return XDocument.Load(reader); - } - } + using var stream = new MemoryStream(_encoding.GetBytes(asset.text)); + using var reader = XmlReader.Create(stream, _xmlSettings); + return XDocument.Load(reader); } static bool _shutdown; @@ -233,15 +230,13 @@ namespace Cryville.Crtr { } static void OnInternalLog(string condition, string stackTrace, LogType type) { - int l; - switch (type) { - case LogType.Log: l = 1; break; - case LogType.Assert: l = 2; break; - case LogType.Warning: l = 3; break; - case LogType.Error: - case LogType.Exception: l = 4; break; - default: l = 1; break; - } + var l = type switch { + LogType.Log => 1, + LogType.Assert => 2, + LogType.Warning => 3, + LogType.Error or LogType.Exception => 4, + _ => 1, + }; MainLogger.Log(l, "Internal", "{0}\n{1}", condition, stackTrace); } diff --git a/Assets/Cryville/Crtr/JsonPdtExpConverter.cs b/Assets/Cryville/Crtr/JsonPdtExpConverter.cs index 795ee85..4990f8d 100644 --- a/Assets/Cryville/Crtr/JsonPdtExpConverter.cs +++ b/Assets/Cryville/Crtr/JsonPdtExpConverter.cs @@ -4,7 +4,7 @@ using System; namespace Cryville.Crtr { public class JsonPdtExpConverter : JsonConverter { - static readonly PdtFragmentInterpreter _itor = new PdtFragmentInterpreter(); + static readonly PdtFragmentInterpreter _itor = new(); public override PdtExpression ReadJson(JsonReader reader, Type objectType, PdtExpression existingValue, bool hasExistingValue, JsonSerializer serializer) { _itor.SetSource((string)reader.Value); return _itor.GetExp(); diff --git a/Assets/Cryville/Crtr/Motion.cs b/Assets/Cryville/Crtr/Motion.cs index cabb91e..854f776 100644 --- a/Assets/Cryville/Crtr/Motion.cs +++ b/Assets/Cryville/Crtr/Motion.cs @@ -6,19 +6,19 @@ using System.Globalization; using UnityEngine; namespace Cryville.Crtr { - public struct MotionRegistry { + public readonly struct MotionRegistry { readonly Type m_Type; - public Type Type { + public readonly Type Type { get { return m_Type; } } readonly Vector m_InitValue; - public Vector InitValue { + public readonly Vector InitValue { get { return m_InitValue.Clone(); } } readonly Vector m_GlobalInitValue; - public Vector GlobalInitValue { + public readonly Vector GlobalInitValue { get { return m_GlobalInitValue.Clone(); } } @@ -43,9 +43,9 @@ namespace Cryville.Crtr { public Vector Value; public void Init(Type type) { - if (Time == null) Time = new Vec1(float.NegativeInfinity); - if (EndTime == null) EndTime = new Vec1(float.NegativeInfinity); - if (Value == null) Value = (Vector)Activator.CreateInstance(type); + Time ??= new Vec1(float.NegativeInfinity); + EndTime ??= new Vec1(float.NegativeInfinity); + Value ??= (Vector)Activator.CreateInstance(type); } public void CopyTo(MotionNode dest) { @@ -407,8 +407,7 @@ namespace Cryville.Crtr { values = new float[] { op.AsNumber() }; } else if (op.Type == PdtInternalType.Vector) { - int type; - op.GetArraySuffix(out type, out _); + op.GetArraySuffix(out int type, out _); if (type != PdtInternalType.Number) throw new InvalidOperationException("Not a vector of numbers"); values = new float[(op.Length - sizeof(int)) / sizeof(float)]; diff --git a/Assets/Cryville/Crtr/Network/UpdateChecker.cs b/Assets/Cryville/Crtr/Network/UpdateChecker.cs index 89117f5..9dffd87 100644 --- a/Assets/Cryville/Crtr/Network/UpdateChecker.cs +++ b/Assets/Cryville/Crtr/Network/UpdateChecker.cs @@ -33,7 +33,7 @@ namespace Cryville.Crtr.Network { if (_shutdown) Application.Quit(); } } - static readonly Uri BaseUri = new Uri("https://www.cryville.world/api/crtr/index"); + static readonly Uri BaseUri = new("https://www.cryville.world/api/crtr/index"); List _versions; void ThreadLogic() { try { @@ -48,10 +48,9 @@ namespace Cryville.Crtr.Network { void CheckVersion() { using (var client = new Https11Client(BaseUri)) { client.Connect(); - using (var response = client.Request("GET", new Uri(BaseUri, "versions"))) { - var data = Encoding.UTF8.GetString(response.MessageBody.ReadToEnd()); - _versions = JsonConvert.DeserializeObject>(data, Game.GlobalJsonSerializerSettings); - } + using var response = client.Request("GET", new Uri(BaseUri, "versions")); + var data = Encoding.UTF8.GetString(response.MessageBody.ReadToEnd()); + _versions = JsonConvert.DeserializeObject>(data, Game.GlobalJsonSerializerSettings); } var availableVersions = _versions.Where(v => v.platforms.ContainsKey(PlatformConfig.Name)).ToArray(); var versionIndex = new Dictionary(availableVersions.Length); @@ -132,15 +131,12 @@ namespace Cryville.Crtr.Network { } void Download(VersionResourceInfo diff, string path) { var uri = new Uri(diff.url); - using (var client = new Https11Client(uri)) { - client.Connect(); - using (var response = client.Request("GET", uri)) { - var data = response.MessageBody.ReadToEnd(); - using (var file = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { - file.Write(data); - } - } - } + using var client = new Https11Client(uri); + client.Connect(); + using var response = client.Request("GET", uri); + var data = response.MessageBody.ReadToEnd(); + using var file = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); + file.Write(data); } void ExecuteUpdate(List diffPaths) { #if UNITY_EDITOR diff --git a/Assets/Cryville/Crtr/NetworkTaskWorkerTicker.cs b/Assets/Cryville/Crtr/NetworkTaskWorkerTicker.cs index 5f3a3e2..98453a9 100644 --- a/Assets/Cryville/Crtr/NetworkTaskWorkerTicker.cs +++ b/Assets/Cryville/Crtr/NetworkTaskWorkerTicker.cs @@ -10,10 +10,10 @@ namespace Cryville.Crtr { void Awake() { _image = GetComponent(); } - static Color _idleColor = new Color(1, 1, 1, .5f); - static Color _tickColor1 = new Color(1, 1, 1, 1); - static Color _tickColor2 = new Color(1, 1, 1, .8f); - static Color _suspendedColor = new Color(1, 0, 0, 1); + static Color _idleColor = new(1, 1, 1, .5f); + static Color _tickColor1 = new(1, 1, 1, 1); + static Color _tickColor2 = new(1, 1, 1, .8f); + static Color _suspendedColor = new(1, 0, 0, 1); void Update() { var status = Game.NetworkTaskWorker.TickBackgroundTasks(); if (_image == null) return; diff --git a/Assets/Cryville/Crtr/PdtBinder.cs b/Assets/Cryville/Crtr/PdtBinder.cs index b3f678d..1765733 100644 --- a/Assets/Cryville/Crtr/PdtBinder.cs +++ b/Assets/Cryville/Crtr/PdtBinder.cs @@ -26,7 +26,7 @@ namespace Cryville.Crtr { return result; } else if (type.Equals(typeof(string))) { - string result = default(string); + string result = default; PdtEvaluator.Instance.Evaluate(new PropOp.String(r => result = r), exp); return result; } @@ -36,12 +36,12 @@ namespace Cryville.Crtr { return result; } else if (type.Equals(typeof(Clip))) { - Clip result = default(Clip); + Clip result = default; PdtEvaluator.Instance.Evaluate(new PropOp.Clip(r => result = r), exp); return result; } else if (type.Equals(typeof(Identifier))) { - Identifier result = default(Identifier); + Identifier result = default; PdtEvaluator.Instance.Evaluate(new pop_identstr(r => result = r), exp); return result; } @@ -51,8 +51,7 @@ namespace Cryville.Crtr { return result; } } - else if (value is string) { - var exp = (string)value; + else if (value is string exp) { if (type.Equals(typeof(Identifier))) { return new Identifier(exp); } diff --git a/Assets/Cryville/Crtr/PdtEvaluator.cs b/Assets/Cryville/Crtr/PdtEvaluator.cs index af63f8f..961f052 100644 --- a/Assets/Cryville/Crtr/PdtEvaluator.cs +++ b/Assets/Cryville/Crtr/PdtEvaluator.cs @@ -16,13 +16,13 @@ namespace Cryville.Crtr { static PdtEvaluator m_instance; public static PdtEvaluator Instance { get { - if (m_instance == null) m_instance = new PdtEvaluator(); + m_instance ??= new PdtEvaluator(); return m_instance; } } - readonly Dictionary _shortops = new Dictionary(); - readonly IntKeyedDictionary _ctxops = new IntKeyedDictionary(); + readonly Dictionary _shortops = new(); + readonly IntKeyedDictionary _ctxops = new(); static readonly byte[] _nullbuf = new byte[0]; readonly byte[] _numbuf = new byte[4]; @@ -43,8 +43,7 @@ namespace Cryville.Crtr { else if (name == _var_false) { LoadNum(0); type = PdtInternalType.Number; value = _numbuf; } else if (name == _var_null) { LoadIdent(0); type = PdtInternalType.Undefined; value = _numbuf; } else { - PropSrc prop; PropStores.Float variable; - if (ContextEvent != null && ContextEvent.PropSrcs.TryGetValue(name, out prop)) { + if (ContextEvent != null && ContextEvent.PropSrcs.TryGetValue(name, out PropSrc prop)) { prop.Get(out type, out value); } else if (ContextState != null && ChartPlayer.motionRegistry.ContainsKey(new Identifier(name))) { @@ -57,7 +56,7 @@ namespace Cryville.Crtr { prop.Get(out type, out value); RevokePotentialConstant(); } - else if (ContextSkinContainer != null && ContextSkinContainer.Variables.TryGetValue(name, out variable)) { + else if (ContextSkinContainer != null && ContextSkinContainer.Variables.TryGetValue(name, out PropStores.Float variable)) { variable.Source.Get(out type, out value); } else if (ContextRulesetConfig != null && ContextRulesetConfig.TryGetMappedSource(name, out prop)) { @@ -94,8 +93,7 @@ namespace Cryville.Crtr { static readonly int _func_int_map = IdentifierManager.Shared.Request("int_map"); static readonly int _func_map = IdentifierManager.Shared.Request("map"); protected override PdtOperator GetOperator(PdtOperatorSignature sig) { - PdtOperator result; - if (_shortops.TryGetValue(sig, out result)) { + if (_shortops.TryGetValue(sig, out PdtOperator result)) { return result; } else if (_ctxops.TryGetValue(sig.Name, out result)) { @@ -135,7 +133,7 @@ namespace Cryville.Crtr { public Judge ContextJudge { get; set; } public PropSrc ContextSelfValue { get; set; } - readonly Stack ContextCascadeBlocks = new Stack(); + readonly Stack ContextCascadeBlocks = new(); public void ContextCascadeInsertBlock() { ContextCascadeBlocks.Push(_cascadeHeight); } @@ -155,10 +153,9 @@ namespace Cryville.Crtr { ContextCascade[_cascadeHeight - 1][key] = value; } public PropSrc ContextCascadeLookup(int name) { - PropSrc result; for (int i = _cascadeHeight - 1; i >= ContextCascadeBlocks.Peek(); i--) { var cas = ContextCascade[i]; - if (cas.TryGetValue(name, out result)) { + if (cas.TryGetValue(name, out PropSrc result)) { return result; } } @@ -226,13 +223,13 @@ namespace Cryville.Crtr { _ctxops.Add(IdentifierManager.Shared.Request("circle"), new func_sphere(() => ContextSelfValue)); _ctxops.Add(IdentifierManager.Shared.Request("sphere"), new func_sphere(() => ContextSelfValue)); - Func cccb = k => ContextCascadeLookup(k); + PropSrc cccb(int k) => ContextCascadeLookup(k); _ctxops.Add(IdentifierManager.Shared.Request("attack_timing"), new func_attack_timing(cccb)); _ctxops.Add(IdentifierManager.Shared.Request("release_timing"), new func_release_timing(cccb)); _ctxops.Add(IdentifierManager.Shared.Request("enter_timing"), new func_enter_timing(cccb)); _ctxops.Add(IdentifierManager.Shared.Request("leave_timing"), new func_leave_timing(cccb)); - Func jacb = k => ContextJudge._areaFuncs[new Identifier(k)]; + PdtExpression jacb(int k) => ContextJudge._areaFuncs[new Identifier(k)]; _ctxops.Add(IdentifierManager.Shared.Request("attack_timed_area"), new func_attack_timed_area(cccb, jacb, this)); _ctxops.Add(IdentifierManager.Shared.Request("release_timed_area"), new func_release_timed_area(cccb, jacb, this)); _ctxops.Add(IdentifierManager.Shared.Request("enter_timed_area"), new func_enter_or_leave_timed_area(cccb, jacb, this, true)); @@ -450,9 +447,8 @@ namespace Cryville.Crtr { } protected override unsafe void Execute() { var ctx = _ctxcb(); - float dist; var ray = new Ray(ctx.position, ctx.rotation * Vector3.forward); - ChartPlayer.frustumPlanes[(int)GetOperand(0).AsNumber()].Raycast(ray, out dist); + ChartPlayer.frustumPlanes[(int)GetOperand(0).AsNumber()].Raycast(ray, out float dist); var ret = GetReturnFrame(PdtInternalType.Vector, sizeof(Vector3) + sizeof(int)); ret.Set(ray.GetPoint(dist)); ret.SetArraySuffix(PdtInternalType.Number); @@ -465,12 +461,11 @@ namespace Cryville.Crtr { } protected override unsafe void Execute() { var ret = GetReturnFrame(PdtInternalType.Number, sizeof(float)); - float v; - switch (LoadedOperandCount) { - case 0: v = oputil.AsNumber(_ctxcb()); break; - case 1: v = GetOperand(0).AsNumber(); break; - default: throw new ArgumentException("Argument count not 0 or 1"); - } + var v = LoadedOperandCount switch { + 0 => oputil.AsNumber(_ctxcb()), + 1 => GetOperand(0).AsNumber(), + _ => throw new ArgumentException("Argument count not 0 or 1"), + }; ret.SetNumber(Mathf.Floor(v)); } } @@ -506,12 +501,11 @@ namespace Cryville.Crtr { protected override unsafe void Execute() { var ret = GetReturnFrame(PdtInternalType.Number, sizeof(float)); float a = GetOperand(0).AsNumber(); - float b; - switch (LoadedOperandCount) { - case 1: b = oputil.AsNumber(_ctxcb()); break; - case 2: b = GetOperand(1).AsNumber(); break; - default: throw new ArgumentException("Argument count not 2 or 3"); - } + var b = LoadedOperandCount switch { + 1 => oputil.AsNumber(_ctxcb()), + 2 => GetOperand(1).AsNumber(), + _ => throw new ArgumentException("Argument count not 2 or 3"), + }; ret.SetNumber(Mathf.Min(a, b)); } } @@ -523,12 +517,11 @@ namespace Cryville.Crtr { protected override unsafe void Execute() { var ret = GetReturnFrame(PdtInternalType.Number, sizeof(float)); var a = GetOperand(0).AsNumber(); - float b; - switch (LoadedOperandCount) { - case 1: b = oputil.AsNumber(_ctxcb()); break; - case 2: b = GetOperand(1).AsNumber(); break; - default: throw new ArgumentException("Argument count not 2 or 3"); - } + var b = LoadedOperandCount switch { + 1 => oputil.AsNumber(_ctxcb()), + 2 => GetOperand(1).AsNumber(), + _ => throw new ArgumentException("Argument count not 2 or 3"), + }; ret.SetNumber(Mathf.Max(a, b)); } } @@ -539,12 +532,11 @@ namespace Cryville.Crtr { } protected override unsafe void Execute() { var ret = GetReturnFrame(PdtInternalType.Number, sizeof(float)); - float arg; - switch (LoadedOperandCount) { - case 0: arg = oputil.AsNumber(_ctxcb()); break; - case 1: arg = GetOperand(0).AsNumber(); break; - default: throw new ArgumentException("Argument count not 0 or 1"); - } + var arg = LoadedOperandCount switch { + 0 => oputil.AsNumber(_ctxcb()), + 1 => GetOperand(0).AsNumber(), + _ => throw new ArgumentException("Argument count not 0 or 1"), + }; ret.SetNumber(Mathf.Abs(arg)); } } @@ -623,12 +615,11 @@ namespace Cryville.Crtr { protected override unsafe void Execute() { float x1 = GetOperand(0).AsNumber(), y1 = GetOperand(1).AsNumber(); float x2 = GetOperand(2).AsNumber(), y2 = GetOperand(3).AsNumber(); - float time; - switch (LoadedOperandCount) { - case 4: time = oputil.AsNumber(_ctxcb()); break; - case 5: time = GetOperand(4).AsNumber(); break; - default: throw new ArgumentException("Argument count not 4 or 5"); - } + var time = LoadedOperandCount switch { + 4 => oputil.AsNumber(_ctxcb()), + 5 => GetOperand(4).AsNumber(), + _ => throw new ArgumentException("Argument count not 4 or 5"), + }; GetReturnFrame(PdtInternalType.Number, sizeof(float)) .SetNumber(CubicBezier.Evaluate(time, x1, y1, x2, y2, 1e-3f)); } @@ -642,12 +633,11 @@ namespace Cryville.Crtr { _ctxcb = ctxcb; } protected override void Execute() { - float time; - switch (LoadedOperandCount) { - case 0: time = oputil.AsNumber(_ctxcb()); break; - case 1: time = GetOperand(0).AsNumber(); break; - default: throw new ArgumentException("Argument count not 0 or 1"); - } + var time = LoadedOperandCount switch { + 0 => oputil.AsNumber(_ctxcb()), + 1 => GetOperand(0).AsNumber(), + _ => throw new ArgumentException("Argument count not 0 or 1"), + }; GetReturnFrame(PdtInternalType.Number, sizeof(float)) .SetNumber(CubicBezier.Evaluate(time, x1, y1, x2, y2, 1e-3f)); } @@ -1003,8 +993,7 @@ namespace Cryville.Crtr { static unsafe class oputil { public static float AsNumber(PropSrc src) { if (src == null) throw new ArgumentNullException("src"); - int type; byte[] value; - src.Get(out type, out value); + src.Get(out int type, out byte[] value); if (type != PdtInternalType.Number && type != PdtInternalType.Vector) throw new ArgumentException("Not a number"); fixed (byte* ptr = value) { @@ -1013,8 +1002,7 @@ namespace Cryville.Crtr { } public static Vector4? AsVector(PropSrc src) { if (src == null) throw new ArgumentNullException("src"); - int type; byte[] value; - src.Get(out type, out value); + src.Get(out int type, out byte[] value); if (type == PdtInternalType.Vector) { fixed (byte* ptr = value) { return *(Vector4*)ptr; @@ -1032,13 +1020,13 @@ namespace Cryville.Crtr { } public static Vector4? AsVector(PdtVariableMemory op) { if (op.Type == PdtInternalType.Vector) { - switch ((op.Length - sizeof(int)) / sizeof(float)) { - case 0: return null; - case 1: return new Vector4(op.AsNumber(), 0, 0, 0); - case 2: return new Vector4(op.AsNumber(), op.AsNumber(sizeof(float)), 0, 0); - case 3: return new Vector4(op.AsNumber(), op.AsNumber(sizeof(float)), op.AsNumber(2 * sizeof(float)), 0); - default: return new Vector4(op.AsNumber(), op.AsNumber(sizeof(float)), op.AsNumber(2 * sizeof(float)), op.AsNumber(3 * sizeof(float))); - } + return ((op.Length - sizeof(int)) / sizeof(float)) switch { + 0 => null, + 1 => (Vector4?)new Vector4(op.AsNumber(), 0, 0, 0), + 2 => (Vector4?)new Vector4(op.AsNumber(), op.AsNumber(sizeof(float)), 0, 0), + 3 => (Vector4?)new Vector4(op.AsNumber(), op.AsNumber(sizeof(float)), op.AsNumber(2 * sizeof(float)), 0), + _ => (Vector4?)new Vector4(op.AsNumber(), op.AsNumber(sizeof(float)), op.AsNumber(2 * sizeof(float)), op.AsNumber(3 * sizeof(float))), + }; } else if (op.Type == PdtInternalType.Number) { return new Vector4(op.AsNumber(), 0, 0, 0); diff --git a/Assets/Cryville/Crtr/PropOp.cs b/Assets/Cryville/Crtr/PropOp.cs index be2bc60..cb3b7bd 100644 --- a/Assets/Cryville/Crtr/PropOp.cs +++ b/Assets/Cryville/Crtr/PropOp.cs @@ -65,8 +65,7 @@ namespace Cryville.Crtr { public StringArray(Action cb) : base(cb) { } protected override unsafe void Execute() { var op = GetOperand(0); - int arrtype; int len; - op.GetArraySuffix(out arrtype, out len); + op.GetArraySuffix(out int arrtype, out int len); if (arrtype != PdtInternalType.String) throw new InvalidCastException("Not an array of strings"); var result = new string[len]; int o = 0; @@ -100,7 +99,7 @@ namespace Cryville.Crtr { } public class Enum : Fixed { readonly Type _type; - readonly IntKeyedDictionary _cache = new IntKeyedDictionary(); + readonly IntKeyedDictionary _cache = new(); public Enum(Type type, Action cb) : base(cb) { if (!type.IsEnum) throw new ArgumentException("Type is not enum"); @@ -117,7 +116,7 @@ namespace Cryville.Crtr { } } public class Enum : Fixed { - static readonly IntKeyedDictionary _cache = new IntKeyedDictionary(); + static readonly IntKeyedDictionary _cache = new(); readonly Func _caster; static Enum() { if (!typeof(T).IsEnum) diff --git a/Assets/Cryville/Crtr/Ruleset/InputProxy.cs b/Assets/Cryville/Crtr/Ruleset/InputProxy.cs index ff3173f..64e8f2f 100644 --- a/Assets/Cryville/Crtr/Ruleset/InputProxy.cs +++ b/Assets/Cryville/Crtr/Ruleset/InputProxy.cs @@ -38,10 +38,10 @@ namespace Cryville.Crtr.Ruleset { } } #region Settings - readonly Dictionary _tproxies = new Dictionary(); - readonly Dictionary _sproxies = new Dictionary(); - readonly Dictionary _use = new Dictionary(); - readonly Dictionary> _rev = new Dictionary>(); + readonly Dictionary _tproxies = new(); + readonly Dictionary _sproxies = new(); + readonly Dictionary _use = new(); + readonly Dictionary> _rev = new(); public event EventHandler ProxyChanged; public void LoadFrom(Dictionary config) { foreach (var cfg in config) { @@ -140,8 +140,7 @@ namespace Cryville.Crtr.Ruleset { } } void BroadcastProxyChanged(Identifier name) { - var del = ProxyChanged; - if (del != null) del(this, this[name]); + ProxyChanged?.Invoke(this, this[name]); } public ProxyChangedEventArgs this[Identifier name] { get { @@ -230,8 +229,8 @@ namespace Cryville.Crtr.Ruleset { int dim; if (op.Type == PdtInternalType.Number) dim = 1; else if (op.Type == PdtInternalType.Vector) { - int arrtype, _; - op.GetArraySuffix(out arrtype, out _); + int _; + op.GetArraySuffix(out int arrtype, out _); if (arrtype != PdtInternalType.Number) throw new InvalidCastException("Not a vector of numbers"); dim = Math.Min(3, (op.Length - sizeof(int)) / sizeof(float)); @@ -245,10 +244,10 @@ namespace Cryville.Crtr.Ruleset { } } } - readonly Dictionary _timeOrigins = new Dictionary(); - readonly Dictionary _targetActiveCount = new Dictionary(); - readonly Dictionary _vect = new Dictionary(); - readonly Dictionary _vecs = new Dictionary(); + readonly Dictionary _timeOrigins = new(); + readonly Dictionary _targetActiveCount = new(); + readonly Dictionary _vect = new(); + readonly Dictionary _vecs = new(); double? _lockTime = null; unsafe void OnInput(InputIdentifier id, InputFrame frame) { var rc = id.Source.Handler.ReferenceCue; @@ -264,10 +263,9 @@ namespace Cryville.Crtr.Ruleset { Monitor.Enter(_etor); try { Profiler.BeginSample("InputProxy.OnInput"); - InputProxyEntry proxy; - if (_sproxies.TryGetValue(id.Source, out proxy)) { - float ft, tt = (float)GetSyncedTime(frame.Time, id.Source.Handler); - if (!_vect.TryGetValue(id, out ft)) ft = tt; + if (_sproxies.TryGetValue(id.Source, out InputProxyEntry proxy)) { + float tt = (float)GetSyncedTime(frame.Time, id.Source.Handler); + if (!_vect.TryGetValue(id, out float ft)) ft = tt; _etor.ContextCascadeInsert(); try { if (frame.IsNull) { @@ -293,7 +291,7 @@ namespace Cryville.Crtr.Ruleset { } static readonly int _var_fv = IdentifierManager.Shared.Request("input_vec_from"); static readonly int _var_tv = IdentifierManager.Shared.Request("input_vec_to"); - readonly InputVectorSrc _vecsrc = new InputVectorSrc(); + readonly InputVectorSrc _vecsrc = new(); unsafe void OnInput(InputIdentifier id, Identifier target, float ft, float tt, bool nullFlag, int depth = 0) { if (depth >= MAX_DEPTH) throw new InputProxyException("Input propagation limit reached\nThe ruleset has invalid input definitions"); var def = _ruleset.inputs[target]; @@ -318,8 +316,8 @@ namespace Cryville.Crtr.Ruleset { else { var pid = new ProxiedInputIdentifier { Source = id, Target = target }; PropSrc fv, tv = _etor.ContextCascadeLookup(_var_input_vec); - bool hfv; Vector4 ifv; - if (hfv = _vecs.TryGetValue(pid, out ifv)) { + bool hfv; + if (hfv = _vecs.TryGetValue(pid, out RVector4 ifv)) { _vecsrc.Set(ifv); fv = _vecsrc; } @@ -352,11 +350,10 @@ namespace Cryville.Crtr.Ruleset { lock (_etor) { foreach (var vec in _vecs) { if (vec.Key.Source.Source.Handler != handler) continue; - InputProxyEntry proxy; - if (!_sproxies.TryGetValue(vec.Key.Source.Source, out proxy)) continue; + if (!_sproxies.TryGetValue(vec.Key.Source.Source, out InputProxyEntry proxy)) continue; - float ft, tt = (float)GetSyncedTime(time, handler); - if (_vect.TryGetValue(vec.Key.Source, out ft) && ft < tt) { + float tt = (float)GetSyncedTime(time, handler); + if (_vect.TryGetValue(vec.Key.Source, out float ft) && ft < tt) { _etor.ContextCascadeInsert(); _vecsrcs[0].Set(vec.Value); _etor.ContextCascadeUpdate(_var_input_vec, _vecsrcs[0]); @@ -434,17 +431,17 @@ namespace Cryville.Crtr.Ruleset { public struct ProxiedInputIdentifier : IEquatable { public InputIdentifier Source { get; set; } public Identifier Target { get; set; } - public override bool Equals(object obj) { - if (obj == null || !(obj is ProxiedInputIdentifier)) return false; - return Equals((ProxiedInputIdentifier)obj); + public override readonly bool Equals(object obj) { + if (obj == null || obj is not ProxiedInputIdentifier other) return false; + return Equals(other); } - public bool Equals(ProxiedInputIdentifier other) { + public readonly bool Equals(ProxiedInputIdentifier other) { return Source == other.Source && Target == other.Target; } - public override int GetHashCode() { + public override readonly int GetHashCode() { return Source.GetHashCode() ^ Target.GetHashCode(); } - public override string ToString() { + public override readonly string ToString() { return string.Format("{0}->{1}", Source, Target); } public static bool operator ==(ProxiedInputIdentifier lhs, ProxiedInputIdentifier rhs) { diff --git a/Assets/Cryville/Crtr/Ruleset/Judge.cs b/Assets/Cryville/Crtr/Ruleset/Judge.cs index 3d5a847..867cbfa 100644 --- a/Assets/Cryville/Crtr/Ruleset/Judge.cs +++ b/Assets/Cryville/Crtr/Ruleset/Judge.cs @@ -45,10 +45,8 @@ namespace Cryville.Crtr.Ruleset { internal readonly PdtEvaluator _etor; readonly PdtRuleset _rs; internal Dictionary _areaFuncs; - readonly Dictionary> evs - = new Dictionary>(); - readonly Dictionary> activeEvs - = new Dictionary>(); + readonly Dictionary> evs = new(); + readonly Dictionary> activeEvs = new(); static readonly int _var_pause = IdentifierManager.Shared.Request("pause"); readonly JudgeDefinition _judgePause; static readonly IComparer _stcmp = new JudgeEventStartTimeComparer(); @@ -59,8 +57,9 @@ namespace Cryville.Crtr.Ruleset { } public Judge(ChartPlayer sys, PdtRuleset rs) { _sys = sys; - _etor = new PdtEvaluator(); - _etor.ContextJudge = this; + _etor = new PdtEvaluator { + ContextJudge = this + }; _rs = rs; _areaFuncs = rs.areas; _identop = new PropOp.Identifier(v => _identbuf = new Identifier(v)); @@ -88,10 +87,9 @@ namespace Cryville.Crtr.Ruleset { var tev = (Chart.Judge)sev.Unstamped; InsertEvent(tev, new Clip((float)sev.Time, (float)(sev.Time + sev.Duration)), tev.Id, handler); } - void InsertEvent(Chart.Judge ev, Clip clip, Identifier id, NoteHandler handler, JudgeCallContext call = default(JudgeCallContext)) { + void InsertEvent(Chart.Judge ev, Clip clip, Identifier id, NoteHandler handler, JudgeCallContext call = default) { if (id.Key == _var_pause) throw new InvalidOperationException("Cannot assign the special judge \"pause\" to notes"); - JudgeDefinition def; - if (!_rs.judges.TryGetValue(id, out def)) { + if (!_rs.judges.TryGetValue(id, out JudgeDefinition def)) { throw new ArgumentException(string.Format("The chart uses a judge named \"{0}\" that is undefined in the ruleset.", id)); } _etor.Evaluate(_identop, def.input); @@ -113,7 +111,7 @@ namespace Cryville.Crtr.Ruleset { } #endregion #region Judge - internal readonly IntKeyedDictionary judgeMap = new IntKeyedDictionary(); + internal readonly IntKeyedDictionary judgeMap = new(); void InitJudges() { foreach (var i in _rs.judges) { var id = i.Key; @@ -121,8 +119,8 @@ namespace Cryville.Crtr.Ruleset { } } static bool _flag; - static readonly PropOp.Boolean _flagop = new PropOp.Boolean(v => _flag = v); - static readonly HitOp _hitop = new HitOp(); + static readonly PropOp.Boolean _flagop = new(v => _flag = v); + static readonly HitOp _hitop = new(); class HitOp : PdtOperator { const int MAX_SORTS = 16; readonly float[] _buf = new float[MAX_SORTS]; @@ -171,18 +169,18 @@ namespace Cryville.Crtr.Ruleset { static readonly int _var_ft = IdentifierManager.Shared.Request("input_time_from"); static readonly int _var_tt = IdentifierManager.Shared.Request("input_time_to"); readonly PropStores.Float - _numst1 = new PropStores.Float(), - _numst2 = new PropStores.Float(), - _numst3 = new PropStores.Float(), - _numst4 = new PropStores.Float(); + _numst1 = new(), + _numst2 = new(), + _numst3 = new(), + _numst4 = new(); static readonly int _var_jt = IdentifierManager.Shared.Request("hit_time"); static readonly int _var_jdt = IdentifierManager.Shared.Request("hit_delta_time"); static readonly int _var_jv = IdentifierManager.Shared.Request("hit_vec"); readonly PropStores.Float - _jnumst = new PropStores.Float(), - _jdnumst = new PropStores.Float(); - readonly PropStores.Vector4 _jvecst = new PropStores.Vector4(); + _jnumst = new(), + _jdnumst = new(); + readonly PropStores.Vector4 _jvecst = new(); // Adopted from System.Collections.Generic.ArraySortHelper.InternalBinarySearch(T[] array, int index, int length, T value, IComparer comparer) int BinarySearch(List list, float time, int stack) { @@ -370,17 +368,16 @@ namespace Cryville.Crtr.Ruleset { } #endregion #region Score - readonly IntKeyedDictionary scoreStringKeys = new IntKeyedDictionary(); - readonly IntKeyedDictionary scoreStringKeysRev = new IntKeyedDictionary(); - readonly IntKeyedDictionary scoreSrcs = new IntKeyedDictionary(); - readonly IntKeyedDictionary scoreOps = new IntKeyedDictionary(); - readonly IntKeyedDictionary scoreDefs = new IntKeyedDictionary(); - readonly IntKeyedDictionary scores = new IntKeyedDictionary(); - readonly IntKeyedDictionary scoreStringCache = new IntKeyedDictionary(); - readonly ArrayPool scoreStringPool = new ArrayPool(); - readonly IntKeyedDictionary scoreFormatCache = new IntKeyedDictionary(); - readonly TargetString scoreFullStr = new TargetString(); - readonly StringBuffer scoreFullBuf = new StringBuffer(); + readonly IntKeyedDictionary scoreStringKeys = new(); + readonly IntKeyedDictionary scoreStringKeysRev = new(); + readonly IntKeyedDictionary scoreSrcs = new(); + readonly IntKeyedDictionary scoreOps = new(); + readonly IntKeyedDictionary scoreDefs = new(); + readonly IntKeyedDictionary scores = new(); + readonly IntKeyedDictionary scoreStringCache = new(); + readonly ArrayPool scoreStringPool = new(); + readonly IntKeyedDictionary scoreFormatCache = new(); + readonly StringBuffer scoreFullBuf = new(); void InitScores() { foreach (var s in _rs.scores) { var key = s.Key.Key; @@ -404,7 +401,7 @@ namespace Cryville.Crtr.Ruleset { public bool TryGetScoreSrc(int key, out PropSrc value) { return scoreSrcs.TryGetValue(key, out value); } - public TargetString GetFullFormattedScoreString() { + public int GetFullFormattedScoreString(ArrayPool bufferPool, out char[] result) { lock (_etor) { bool flag = false; scoreFullBuf.Clear(); @@ -414,17 +411,16 @@ namespace Cryville.Crtr.Ruleset { scoreFullBuf.AppendFormat(scoreFormatCache[id], scores[id]); flag = true; } - scoreFullStr.Length = scoreFullBuf.Count; - var arr = scoreFullStr.TrustedAsArray(); - scoreFullBuf.CopyTo(0, arr, 0, scoreFullBuf.Count); - return scoreFullStr; + result = bufferPool.Rent(scoreFullBuf.Count); + scoreFullBuf.CopyTo(0, result, 0, scoreFullBuf.Count); + return scoreFullBuf.Count; } } class ScoreStringSrc : PropSrc { readonly Func _cb; readonly string _format; readonly ArrayPool _pool; - readonly StringBuffer _buf = new StringBuffer() { Culture = CultureInfo.InvariantCulture }; + readonly StringBuffer _buf = new() { Culture = CultureInfo.InvariantCulture }; public ScoreStringSrc(ArrayPool pool, Func cb, string format) : base(PdtInternalType.String) { _pool = pool; diff --git a/Assets/Cryville/Crtr/Ruleset/JudgeAction.cs b/Assets/Cryville/Crtr/Ruleset/JudgeAction.cs index 3981d75..d5c5f30 100644 --- a/Assets/Cryville/Crtr/Ruleset/JudgeAction.cs +++ b/Assets/Cryville/Crtr/Ruleset/JudgeAction.cs @@ -60,7 +60,7 @@ namespace Cryville.Crtr.Ruleset { } public override void Optimize(PdtEvaluatorBase etor, PdtExpression value) { base.Optimize(etor, value); - if (_op.op != default(Identifier)) PdtExpression.PatchCompound(_op.name.Key, _op.op.Key, value); + if (_op.op != default) PdtExpression.PatchCompound(_op.name.Key, _op.op.Key, value); } internal override JudgeActionResult Execute(IJudge judge, JudgeEvent ev, float time, PdtExpression exp, bool onMiss, int depth, int index) { judge.UpdateScore(_op, exp); diff --git a/Assets/Cryville/Crtr/Ruleset/RulesetDefinition.cs b/Assets/Cryville/Crtr/Ruleset/RulesetDefinition.cs index c3229b0..848bca4 100644 --- a/Assets/Cryville/Crtr/Ruleset/RulesetDefinition.cs +++ b/Assets/Cryville/Crtr/Ruleset/RulesetDefinition.cs @@ -23,10 +23,9 @@ namespace Cryville.Crtr.Ruleset { public PdtRuleset Root { get; private set; } public void LoadPdt(DirectoryInfo dir) { - using (StreamReader pdtreader = new StreamReader(Path.Combine(dir.FullName, data + ".pdt"), Encoding.UTF8)) { - var src = pdtreader.ReadToEnd(); - Root = (PdtRuleset)new RulesetInterpreter(src, null).Interpret(typeof(PdtRuleset)); - } + using StreamReader pdtreader = new(Path.Combine(dir.FullName, data + ".pdt"), Encoding.UTF8); + var src = pdtreader.ReadToEnd(); + Root = (PdtRuleset)new RulesetInterpreter(src, null).Interpret(typeof(PdtRuleset)); } } @@ -99,7 +98,7 @@ namespace Cryville.Crtr.Ruleset { #pragma warning disable IDE1006 public PairList scores { set { - if (on_hit == null) on_hit = new PairList(); + on_hit ??= new PairList(); int i = 0; foreach (var s in value) { on_hit.Insert(i++, new JudgeAction.Score(s.Key), s.Value); @@ -108,13 +107,13 @@ namespace Cryville.Crtr.Ruleset { } public Identifier[] pass { set { - if (on_hit == null) on_hit = new PairList(); + on_hit ??= new PairList(); on_hit.Add(new JudgeAction.Pass(Enumerable.Empty(), value), PdtExpression.Empty); } } public Identifier[] miss { set { - if (on_miss == null) on_miss = new PairList(); + on_miss ??= new PairList(); on_miss.Add(new JudgeAction.Pass(Enumerable.Empty(), value), PdtExpression.Empty); } } @@ -134,7 +133,7 @@ namespace Cryville.Crtr.Ruleset { op = new Identifier(m.Groups[2].Value); } public override string ToString() { - if (op == default(Identifier)) return name.ToString(); + if (op == default) return name.ToString(); else return string.Format("{0} {1}", name, op); } } @@ -144,11 +143,11 @@ namespace Cryville.Crtr.Ruleset { public string format = ""; } public class Constraint { - static readonly PropOp.Arbitrary _arbop = new PropOp.Arbitrary(); + static readonly PropOp.Arbitrary _arbop = new(); [ElementList] - public PairList Elements = new PairList(); + public PairList Elements = new(); [PropertyList] - public PairList Properties = new PairList(); + public PairList Properties = new(); public void Optimize(PdtEvaluatorBase etor) { foreach (var e in Properties) { etor.Optimize(e.Value); @@ -160,14 +159,13 @@ namespace Cryville.Crtr.Ruleset { } public void PrePatch(ChartEvent ev) { var etor = PdtEvaluator.Instance; - PropSrc src; etor.ContextCascadeInsert(); etor.ContextEvent = ev; foreach (var prop in Properties) { var name = prop.Key.Name; switch (prop.Key.Type) { case ConstraintType.Property: - if (ev.PropSrcs.TryGetValue(name, out src)) + if (ev.PropSrcs.TryGetValue(name, out PropSrc src)) etor.ContextSelfValue = src; etor.Evaluate(ev.PropOps[name], prop.Value); etor.ContextSelfValue = null; @@ -196,13 +194,11 @@ namespace Cryville.Crtr.Ruleset { Type = type; Name = IdentifierManager.Shared.Request(name); } - public override string ToString() { - switch (Type) { - case ConstraintType.Property: return (string)IdentifierManager.Shared.Retrieve(Name); - case ConstraintType.Variable: return string.Format("@var {0}", IdentifierManager.Shared.Retrieve(Name)); - default: return string.Format("<{0}> {1}", Type, IdentifierManager.Shared.Retrieve(Name)); - } - } + public override string ToString() => Type switch { + ConstraintType.Property => (string)IdentifierManager.Shared.Retrieve(Name), + ConstraintType.Variable => string.Format("@var {0}", IdentifierManager.Shared.Retrieve(Name)), + _ => string.Format("<{0}> {1}", Type, IdentifierManager.Shared.Retrieve(Name)), + }; } public enum ConstraintType { Property, diff --git a/Assets/Cryville/Crtr/Ruleset/RulesetInterpreter.cs b/Assets/Cryville/Crtr/Ruleset/RulesetInterpreter.cs index 6d74dd2..f65bcb2 100644 --- a/Assets/Cryville/Crtr/Ruleset/RulesetInterpreter.cs +++ b/Assets/Cryville/Crtr/Ruleset/RulesetInterpreter.cs @@ -8,8 +8,8 @@ namespace Cryville.Crtr.Ruleset { internal class RulesetInterpreter : PdtInterpreter { public RulesetInterpreter(string src, Binder binder) : base(src, binder) { } - readonly List s = new List(); - readonly HashSet a = new HashSet(); + readonly List s = new(); + readonly HashSet a = new(); protected override object InterpretKey(Type type) { if (PairCollection.IsPairCollection(type)) return InterpretJudgeAction(); diff --git a/Assets/Cryville/Crtr/Ruleset/RulesetSelectors.cs b/Assets/Cryville/Crtr/Ruleset/RulesetSelectors.cs index f8da11c..a23afde 100644 --- a/Assets/Cryville/Crtr/Ruleset/RulesetSelectors.cs +++ b/Assets/Cryville/Crtr/Ruleset/RulesetSelectors.cs @@ -46,8 +46,7 @@ namespace Cryville.Crtr.Ruleset { return "$"; } public override IEnumerable Match(ChartEvent ev) { - if (!(ev is EventList)) throw new ArgumentException("Event is not event list"); - var tev = (EventList)ev; + if (ev is not EventList tev) throw new ArgumentException("Event is not event list"); var result = tev.Create(); tev.Events.Add(result); // TODO create at return new ChartEvent[] { result }; @@ -60,8 +59,7 @@ namespace Cryville.Crtr.Ruleset { return _type; } public override IEnumerable Match(ChartEvent ev) { - if (!(ev is EventContainer)) throw new ArgumentException("Event is not container"); - var tev = (EventContainer)ev; + if (ev is not EventContainer tev) throw new ArgumentException("Event is not container"); return new ChartEvent[] { tev.GetEventsOfType(_type) }; } } @@ -70,8 +68,7 @@ namespace Cryville.Crtr.Ruleset { return "#"; } public override IEnumerable Match(ChartEvent ev) { - if (!(ev is EventList)) throw new ArgumentException("Event is not event list"); - var tev = (EventList)ev; + if (ev is not EventList tev) throw new ArgumentException("Event is not event list"); return tev.Events; // TODO select at } } diff --git a/Assets/Cryville/Crtr/Ruleset/VirtualPlayerStrategy.cs b/Assets/Cryville/Crtr/Ruleset/VirtualPlayerStrategy.cs index ec2d574..c7da762 100644 --- a/Assets/Cryville/Crtr/Ruleset/VirtualPlayerStrategy.cs +++ b/Assets/Cryville/Crtr/Ruleset/VirtualPlayerStrategy.cs @@ -20,10 +20,9 @@ namespace Cryville.Crtr.Ruleset { public PdtVirtualPlayerStrategy Root { get; private set; } public void LoadPdt(DirectoryInfo dir) { - using (StreamReader pdtreader = new StreamReader(Path.Combine(dir.FullName, data + ".pdt"), Encoding.UTF8)) { - var src = pdtreader.ReadToEnd(); - Root = (PdtVirtualPlayerStrategy)new RulesetInterpreter(src, null).Interpret(typeof(PdtVirtualPlayerStrategy)); - } + using StreamReader pdtreader = new(Path.Combine(dir.FullName, data + ".pdt"), Encoding.UTF8); + var src = pdtreader.ReadToEnd(); + Root = (PdtVirtualPlayerStrategy)new RulesetInterpreter(src, null).Interpret(typeof(PdtVirtualPlayerStrategy)); } } @@ -39,8 +38,8 @@ namespace Cryville.Crtr.Ruleset { public class StrategyAction { [ElementList] - public PairList Elements = new PairList(); + public PairList Elements = new(); [PropertyList] - public PairList Properties = new PairList(); + public PairList Properties = new(); } } diff --git a/Assets/Cryville/Crtr/Settings.cs b/Assets/Cryville/Crtr/Settings.cs index 3c9c8f4..71b962a 100644 --- a/Assets/Cryville/Crtr/Settings.cs +++ b/Assets/Cryville/Crtr/Settings.cs @@ -5,7 +5,7 @@ using RangeAttribute = Cryville.Common.ComponentModel.RangeAttribute; namespace Cryville.Crtr { public class Settings { - static readonly Settings _default = new Settings(); + static readonly Settings _default = new(); [Browsable(false)] public static Settings Default { get { diff --git a/Assets/Cryville/Crtr/Skin/Components/MeshBase.cs b/Assets/Cryville/Crtr/Skin/Components/MeshBase.cs index 466ed83..222bb62 100644 --- a/Assets/Cryville/Crtr/Skin/Components/MeshBase.cs +++ b/Assets/Cryville/Crtr/Skin/Components/MeshBase.cs @@ -14,7 +14,7 @@ namespace Cryville.Crtr.Skin.Components { SubmitProperty("zindex", new PropOp.Integer(v => ZIndex = (short)v)); } - protected MeshWrapper mesh = new MeshWrapper(); + protected MeshWrapper mesh = new(); protected Material[] materials; short _zindex; diff --git a/Assets/Cryville/Crtr/Skin/Components/PolygonSGO.cs b/Assets/Cryville/Crtr/Skin/Components/PolygonSGO.cs index 8784a26..a1ae159 100644 --- a/Assets/Cryville/Crtr/Skin/Components/PolygonSGO.cs +++ b/Assets/Cryville/Crtr/Skin/Components/PolygonSGO.cs @@ -6,13 +6,13 @@ using UnityEngine; namespace Cryville.Crtr.Skin.Components { public class PolygonSGO : SectionalGameObject { - static readonly SimpleObjectPool> _ptPool = new SimpleObjectPool>(1024); - static readonly SimpleObjectPool> _lPool = new SimpleObjectPool>(1024); + static readonly SimpleObjectPool> _ptPool = new(1024); + static readonly SimpleObjectPool> _lPool = new(1024); - static readonly ListPool _indexPool = new ListPool(); - static readonly ListPool _vertPool = new ListPool(); - static readonly ListPool _uvPool = new ListPool(); - static readonly ArrayPool _shapePool = new ArrayPool(0x100, 0x10000); + static readonly ListPool _indexPool = new(); + static readonly ListPool _vertPool = new(); + static readonly ListPool _uvPool = new(); + static readonly ArrayPool _shapePool = new(0x100, 0x10000); public PolygonSGO() { SubmitProperty("head", new PropOp.String(v => head.FrameName = v)); @@ -50,9 +50,9 @@ namespace Cryville.Crtr.Skin.Components { return r; } - public SpriteInfo head = new SpriteInfo(); - public SpriteInfo body = new SpriteInfo(); - public SpriteInfo tail = new SpriteInfo(); + public SpriteInfo head = new(); + public SpriteInfo body = new(); + public SpriteInfo tail = new(); List vertices; List lengths; @@ -104,7 +104,7 @@ namespace Cryville.Crtr.Skin.Components { List verts; List uvs; List trih = null, trib = null, trit = null; - static readonly List _emptyTris = new List(); + static readonly List _emptyTris = new(); public override void Seal() { if (vertCount <= 1 || sumLength == 0) return; diff --git a/Assets/Cryville/Crtr/Skin/Components/SkinAnimation.cs b/Assets/Cryville/Crtr/Skin/Components/SkinAnimation.cs index 10a51bd..d130510 100644 --- a/Assets/Cryville/Crtr/Skin/Components/SkinAnimation.cs +++ b/Assets/Cryville/Crtr/Skin/Components/SkinAnimation.cs @@ -27,8 +27,7 @@ namespace Cryville.Crtr.Skin.Components { } else { var id = new Identifier(value); - AnimationSpan anim; - if (!ChartPlayer.pskin.animations.TryGetValue(id, out anim)) { + if (!ChartPlayer.pskin.animations.TryGetValue(id, out AnimationSpan anim)) { Game.MainLogger.Log(4, "Skin", "Animation {0} not found", id.Name); _anim = null; return; diff --git a/Assets/Cryville/Crtr/Skin/Components/SpritePlane.cs b/Assets/Cryville/Crtr/Skin/Components/SpritePlane.cs index c71dd8c..871de1b 100644 --- a/Assets/Cryville/Crtr/Skin/Components/SpritePlane.cs +++ b/Assets/Cryville/Crtr/Skin/Components/SpritePlane.cs @@ -45,7 +45,7 @@ namespace Cryville.Crtr.Skin.Components { } else Frame = null; if (_mat != null) { - _mat.mainTexture = Frame == null ? null : Frame.Texture; + _mat.mainTexture = Frame?.Texture; } } public static bool IsNullOrEmpty(SpriteInfo sprite) { @@ -88,7 +88,7 @@ namespace Cryville.Crtr.Skin.Components { OnFrameUpdate(); } } - SpriteInfo[] m_frames = new SpriteInfo[] { new SpriteInfo() }; + SpriteInfo[] m_frames = new SpriteInfo[] { new() }; public string[] Frames { set { m_frames = new SpriteInfo[value.Length]; @@ -169,12 +169,12 @@ namespace Cryville.Crtr.Skin.Components { protected override Vector3 BaseScale { get { - switch (m_fit) { - case FitMode.none: return Vector3.one; - case FitMode.width: return new Vector3(1, 1, 1 / CurrentFrame.Ratio); - case FitMode.height: return new Vector3(CurrentFrame.Ratio, 1, 1); - default: throw new NotSupportedException("Unsupported fit mode"); - } + return m_fit switch { + FitMode.none => Vector3.one, + FitMode.width => new Vector3(1, 1, 1 / CurrentFrame.Ratio), + FitMode.height => new Vector3(CurrentFrame.Ratio, 1, 1), + _ => throw new NotSupportedException("Unsupported fit mode"), + }; } } diff --git a/Assets/Cryville/Crtr/Skin/Components/SpriteScale3.cs b/Assets/Cryville/Crtr/Skin/Components/SpriteScale3.cs index 73aa384..6a6dc60 100644 --- a/Assets/Cryville/Crtr/Skin/Components/SpriteScale3.cs +++ b/Assets/Cryville/Crtr/Skin/Components/SpriteScale3.cs @@ -9,7 +9,7 @@ namespace Cryville.Crtr.Skin.Components { } static readonly Dictionary uvrefl - = new Dictionary() { + = new() { {-0.5f, 0}, {-0.4f, 1}, {0.4f, 2}, {0.5f, 3}, }; static Vector2[] _origuv; @@ -30,7 +30,7 @@ namespace Cryville.Crtr.Skin.Components { } } - Vector2 _border = new Vector2(0, 1); + Vector2 _border = new(0, 1); public Vector2 Border { get { return _border; } set { @@ -67,12 +67,12 @@ namespace Cryville.Crtr.Skin.Components { case 3: x = 1; bx = 1; break; default: throw new NotSupportedException("Built-in resource corrupted"); } - float y; - switch ((int)muv[i].y) { - case 0: y = 0; break; - case 3: y = 1; break; - default: throw new NotSupportedException("Built-in resource corrupted"); - } + + var y = (int)muv[i].y switch { + 0 => 0, + 3 => (float)1, + _ => throw new NotSupportedException("Built-in resource corrupted"), + }; _uvs[i] = frame.Frame.GetUV(x, y); bx -= 0.5f; y -= 0.5f; _verts[i] = new Vector3(bx, 0, y); diff --git a/Assets/Cryville/Crtr/Skin/Components/SpriteText.cs b/Assets/Cryville/Crtr/Skin/Components/SpriteText.cs index 347a481..04fe426 100644 --- a/Assets/Cryville/Crtr/Skin/Components/SpriteText.cs +++ b/Assets/Cryville/Crtr/Skin/Components/SpriteText.cs @@ -22,8 +22,7 @@ namespace Cryville.Crtr.Skin.Components { protected override unsafe void Execute() { var keys = GetOperand(0).AsString(); var values = GetOperand(1); - int arrtype; int len; - values.GetArraySuffix(out arrtype, out len); + values.GetArraySuffix(out int arrtype, out int len); if (arrtype != PdtInternalType.String) throw new InvalidCastException("Not an array of strings"); if (len != keys.Length) throw new ArgumentException("Length of key not equal to frame count"); var result = new Dictionary(len); @@ -49,7 +48,7 @@ namespace Cryville.Crtr.Skin.Components { set { m_frames = value; UpdateFrames(); } } - readonly TargetString m_value = new TargetString(); + readonly TargetString m_value = new(); public TargetString Value { get { return m_value; } } public float m_size; @@ -103,10 +102,10 @@ namespace Cryville.Crtr.Skin.Components { } float sum_x; - readonly Dictionary meshes = new Dictionary(); - readonly Dictionary> verts = new Dictionary>(); - readonly Dictionary> uvs = new Dictionary>(); - readonly Dictionary> tris = new Dictionary>(); + readonly Dictionary meshes = new(); + readonly Dictionary> verts = new(); + readonly Dictionary> uvs = new(); + readonly Dictionary> tris = new(); void UpdateMeshes() { if (meshes.Count == 0) return; sum_x = 0; @@ -117,8 +116,7 @@ namespace Cryville.Crtr.Skin.Components { tris[key].Clear(); } foreach (var c in m_value) { - SpriteInfo f; - if (!m_frames.TryGetValue(c, out f)) { + if (!m_frames.TryGetValue(c, out SpriteInfo f)) { Game.MainLogger.Log(3, "Skin", "Could not render the character '{0}' in the string \"{1}\" on the text component because no image is assigned to that character.", c, m_value); continue; } @@ -173,7 +171,7 @@ namespace Cryville.Crtr.Skin.Components { UpdateFrames(); mesh.Mesh.Clear(); UpdateScale(); - Value.OnUpdate += UpdateScale; + Value.Updated += UpdateScale; } } } diff --git a/Assets/Cryville/Crtr/Skin/Components/TrackLine.cs b/Assets/Cryville/Crtr/Skin/Components/TrackLine.cs index beee864..956c3ec 100644 --- a/Assets/Cryville/Crtr/Skin/Components/TrackLine.cs +++ b/Assets/Cryville/Crtr/Skin/Components/TrackLine.cs @@ -3,7 +3,7 @@ using UnityEngine; namespace Cryville.Crtr.Skin.Components { public class TrackLine : SectionalGameObject { - readonly List vertices = new List(); + readonly List vertices = new(); LineRenderer lineRenderer; diff --git a/Assets/Cryville/Crtr/Skin/EffectGroup.cs b/Assets/Cryville/Crtr/Skin/EffectGroup.cs index 0c37d24..3c902c3 100644 --- a/Assets/Cryville/Crtr/Skin/EffectGroup.cs +++ b/Assets/Cryville/Crtr/Skin/EffectGroup.cs @@ -8,7 +8,7 @@ namespace Cryville.Crtr.Skin { readonly EffectPool _pool; class EffectPool : ObjectPool { readonly List _instances - = new List(); + = new(); readonly EffectGroup _group; public EffectPool(EffectGroup group) : base(256) { _group = group; @@ -23,9 +23,9 @@ namespace Cryville.Crtr.Skin { } } readonly Dictionary _instances - = new Dictionary(); + = new(); readonly List _endQueue - = new List(); + = new(); public EffectGroup(EffectDefinition def) { Definition = def; _pool = new EffectPool(this); @@ -51,8 +51,7 @@ namespace Cryville.Crtr.Skin { } } public void Emit(float index, Transform target = null) { - EffectInstance instance; - bool flag = _instances.TryGetValue(index, out instance); + bool flag = _instances.TryGetValue(index, out EffectInstance instance); if (!flag) _instances.Add(index, instance = _pool.Rent()); instance.Index = index; if (instance.CanEmit()) { diff --git a/Assets/Cryville/Crtr/Skin/EffectInstance.cs b/Assets/Cryville/Crtr/Skin/EffectInstance.cs index 6723c1c..645fc79 100644 --- a/Assets/Cryville/Crtr/Skin/EffectInstance.cs +++ b/Assets/Cryville/Crtr/Skin/EffectInstance.cs @@ -33,7 +33,7 @@ namespace Cryville.Crtr.Skin { ChartEvent _ctxev; ContainerState _ctxstate; internal static readonly int _VAR_EFFECT_INDEX = IdentifierManager.Shared.Request("effect_index"); - readonly PropStores.Float _indexst = new PropStores.Float(); + readonly PropStores.Float _indexst = new(); public float Index { get { return _indexst.Value; } set { _indexst.Value = value; } diff --git a/Assets/Cryville/Crtr/Skin/EffectManager.cs b/Assets/Cryville/Crtr/Skin/EffectManager.cs index b9d7458..10bab13 100644 --- a/Assets/Cryville/Crtr/Skin/EffectManager.cs +++ b/Assets/Cryville/Crtr/Skin/EffectManager.cs @@ -6,7 +6,7 @@ using UnityEngine; namespace Cryville.Crtr.Skin { public class EffectManager { readonly IntKeyedDictionary _groups - = new IntKeyedDictionary(); + = new(); public EffectManager(PdtSkin skin) { foreach (var e in skin.effects) { _groups.Add(e.Key.Key, new EffectGroup(e.Value)); @@ -22,8 +22,7 @@ namespace Cryville.Crtr.Skin { GetGroup(id).Emit(index, target); } EffectGroup GetGroup(int id) { - EffectGroup result; - if (_groups.TryGetValue(id, out result)) return result; + if (_groups.TryGetValue(id, out EffectGroup result)) return result; throw new ArgumentException(string.Format("The effect \"{0}\" is not found", IdentifierManager.Shared.Retrieve(id))); } public void Dispose() { diff --git a/Assets/Cryville/Crtr/Skin/SkinContainer.cs b/Assets/Cryville/Crtr/Skin/SkinContainer.cs index a3dba17..c321c45 100644 --- a/Assets/Cryville/Crtr/Skin/SkinContainer.cs +++ b/Assets/Cryville/Crtr/Skin/SkinContainer.cs @@ -9,12 +9,12 @@ namespace Cryville.Crtr.Skin { readonly ISkinnableGroup _group; readonly SkinElement _rootElement; readonly DynamicStack[] _stacks = new DynamicStack[3]; - readonly HashSet _once = new HashSet(); - public readonly IntKeyedDictionary Variables = new IntKeyedDictionary(); + readonly HashSet _once = new(); + public readonly IntKeyedDictionary Variables = new(); class DynamicStack { - public readonly List Properties = new List(); - public readonly List Elements = new List(); + public readonly List Properties = new(); + public readonly List Elements = new(); public void Clear() { Properties.Clear(); Elements.Clear(); @@ -78,7 +78,7 @@ namespace Cryville.Crtr.Skin { var stack = _stacks[dl]; if (stack.Properties.Count == 0 && stack.Elements.Count == 0) return; var nstack = dl + 1 < _stacks.Length ? _stacks[dl + 1] : null; - if (nstack != null) nstack.Clear(); + nstack?.Clear(); Profiler.BeginSample("SkinContainer.MatchDynamic"); if (!recursive) PdtEvaluator.Instance.ContextSkinContainer = this; for (int i = 0; i < stack.Properties.Count; i++) { @@ -150,7 +150,7 @@ namespace Cryville.Crtr.Skin { } if (rc.PropSrcs != null) PdtEvaluator.Instance.ContextCascadeDiscard(); } - readonly PropStores.Float _rtimest = new PropStores.Float(); + readonly PropStores.Float _rtimest = new(); public void MatchAnimation(AnimationSpan span, float rtime, RuntimeSkinContext ctx) { PdtEvaluator.Instance.ContextSkinContainer = this; PdtEvaluator.Instance.ContextSelfValue = _rtimest.Source; diff --git a/Assets/Cryville/Crtr/Skin/SkinDefinition.cs b/Assets/Cryville/Crtr/Skin/SkinDefinition.cs index fa9bcdf..1410eae 100644 --- a/Assets/Cryville/Crtr/Skin/SkinDefinition.cs +++ b/Assets/Cryville/Crtr/Skin/SkinDefinition.cs @@ -20,37 +20,35 @@ namespace Cryville.Crtr.Skin { [JsonRequired] public string ruleset; - public List frames = new List(); + public List frames = new(); [JsonIgnore] public PdtSkin Root { get; private set; } public void LoadPdt(DirectoryInfo dir) { - using (StreamReader pdtreader = new StreamReader(Path.Combine(dir.FullName, data + ".pdt"), Encoding.UTF8)) { - var src = pdtreader.ReadToEnd(); - var interpreter = new SkinInterpreter(src, null); - var format = interpreter.GetFormatVersion(); - if (format.Length == 1) { - Root = new PdtSkin(); - Root.elements = (SkinElement)new SkinInterpreter(src, new PdtBinder()).Interpret(typeof(SkinElement)); - } - else { - switch (format[1]) { - case 1: - Root = (PdtSkin)new SkinInterpreter(src, new PdtBinder()).Interpret(typeof(PdtSkin)); - break; - default: throw new NotSupportedException("Unsupported skin format"); - } - } + using StreamReader pdtreader = new(Path.Combine(dir.FullName, data + ".pdt"), Encoding.UTF8); + var src = pdtreader.ReadToEnd(); + var interpreter = new SkinInterpreter(src, null); + var format = interpreter.GetFormatVersion(); + if (format.Length == 1) { + Root = new PdtSkin { + elements = (SkinElement)new SkinInterpreter(src, new PdtBinder()).Interpret(typeof(SkinElement)) + }; + } + else { + Root = format[1] switch { + 1 => (PdtSkin)new SkinInterpreter(src, new PdtBinder()).Interpret(typeof(PdtSkin)), + _ => throw new NotSupportedException("Unsupported skin format"), + }; } } } public class PdtSkin { public Dictionary animations - = new Dictionary(); + = new(); public Dictionary effects - = new Dictionary(); + = new(); public SkinElement elements; public void Optimize(PdtEvaluator etor) { @@ -74,11 +72,11 @@ namespace Cryville.Crtr.Skin { public class SkinElement { [ElementList] public PairList elements - = new PairList(); + = new(); [PropertyList] public PairList properties - = new PairList(); + = new(); public bool IsDynamic { get; @@ -102,19 +100,18 @@ namespace Cryville.Crtr.Skin { } public class EffectDefinition { - static readonly Identifier _ident_init = new Identifier(""); + static readonly Identifier _ident_init = new(""); #pragma warning disable IDE1006 public PdtExpression duration { set { - EffectState s; - if (!states.TryGetValue(_ident_init, out s)) + if (!states.TryGetValue(_ident_init, out EffectState s)) throw new InvalidOperationException("Cannot set duration and states at the same time"); s.duration = value; } } #pragma warning restore IDE1006 public Identifier init = _ident_init; - public Dictionary states = new Dictionary { + public Dictionary states = new() { { _ident_init, new EffectState() { rewind = _ident_init } } }; public SkinElement elements; @@ -129,11 +126,11 @@ namespace Cryville.Crtr.Skin { public class AnimationSpan { [ElementList] public PairList spans - = new PairList(); + = new(); [PropertyList] public PairList properties - = new PairList(); + = new(); public void Optimize(PdtEvaluator etor) { foreach (var p in properties) { diff --git a/Assets/Cryville/Crtr/Skin/SkinInterpreter.cs b/Assets/Cryville/Crtr/Skin/SkinInterpreter.cs index 118c02d..e16d934 100644 --- a/Assets/Cryville/Crtr/Skin/SkinInterpreter.cs +++ b/Assets/Cryville/Crtr/Skin/SkinInterpreter.cs @@ -7,9 +7,9 @@ namespace Cryville.Crtr.Skin { public class SkinInterpreter : PdtInterpreter { public SkinInterpreter(string src, Binder binder) : base(src, binder) { } - readonly List s = new List(); - readonly HashSet a = new HashSet(); - readonly List k = new List(2); + readonly List s = new(); + readonly HashSet a = new(); + readonly List k = new(2); protected override object InterpretKey(Type type) { if (typeof(SkinElement).IsAssignableFrom(type)) return InterpretSkinElementKey(); diff --git a/Assets/Cryville/Crtr/Skin/SkinPropertyKey.cs b/Assets/Cryville/Crtr/Skin/SkinPropertyKey.cs index 215505c..6766841 100644 --- a/Assets/Cryville/Crtr/Skin/SkinPropertyKey.cs +++ b/Assets/Cryville/Crtr/Skin/SkinPropertyKey.cs @@ -40,8 +40,7 @@ namespace Cryville.Crtr.Skin { throw new FormatException("Unknown error"); } static Type GetComponentByName(string name) { - Type result; - if (BuiltinResources.Components.TryGetValue(name, out result)) return result; + if (BuiltinResources.Components.TryGetValue(name, out Type result)) return result; throw new ArgumentException(string.Format("Component type \"{0}\" not found", name)); } } @@ -102,8 +101,7 @@ namespace Cryville.Crtr.Skin { "Trying to set property \"{0}\" but the component is not found", IdentifierManager.Shared.Retrieve(Name) )); - SkinProperty result; - if (!comp.Properties.TryGetValue(Name, out result)) + if (!comp.Properties.TryGetValue(Name, out SkinProperty result)) throw new InvalidOperationException(string.Format( "Property \"{0}\" not found on component", IdentifierManager.Shared.Retrieve(Name) @@ -186,15 +184,13 @@ namespace Cryville.Crtr.Skin { } public override bool IsValueRequired { get { return true; } } public override void ExecuteStatic(ISkinnableGroup group, RuntimeSkinContext ctx, PdtExpression exp, IntKeyedDictionary vars) { - PropStores.Float v; - if (!vars.TryGetValue(Name, out v)) + if (!vars.TryGetValue(Name, out PropStores.Float v)) vars.Add(Name, v = new PropStores.Float()); if (!PdtEvaluator.Instance.Evaluate(v.Target, exp)) throw new EvaluationFailureException(); } public override void ExecuteDynamic(ISkinnableGroup group, RuntimeSkinContext ctx, PdtExpression exp, IntKeyedDictionary vars, int dl) { - PropStores.Float v; - if (!vars.TryGetValue(Name, out v)) + if (!vars.TryGetValue(Name, out PropStores.Float v)) throw new InvalidOperationException(string.Format("Variable \"{0}\" not defined", IdentifierManager.Shared.Retrieve(Name))); if (!PdtEvaluator.Instance.Evaluate(v.Target, exp)) throw new EvaluationFailureException(); diff --git a/Assets/Cryville/Crtr/Skin/SkinSelectors.cs b/Assets/Cryville/Crtr/Skin/SkinSelectors.cs index caa0409..dca0571 100644 --- a/Assets/Cryville/Crtr/Skin/SkinSelectors.cs +++ b/Assets/Cryville/Crtr/Skin/SkinSelectors.cs @@ -75,7 +75,7 @@ namespace Cryville.Crtr.Skin { var obj = new GameObject("__obj__"); obj.transform.SetParent(c.Transform, false); obj.AddComponent(); - return new SkinContext[] { new SkinContext(obj.transform) }; + return new SkinContext[] { new(obj.transform) }; } } public class Anchor : SkinSelector { @@ -86,8 +86,7 @@ namespace Cryville.Crtr.Skin { public override string ToString() { return string.Format(".{0}", IdentifierManager.Shared.Retrieve(Name)); } public override IEnumerable MatchStatic(ISkinnableGroup g, SkinContext c) { - IReadOnlyCollection anchors; - if (g.TryGetAnchorsByName(Name, out anchors)) { + if (g.TryGetAnchorsByName(Name, out IReadOnlyCollection anchors)) { return anchors.Select(a => a.SkinContext); } else return Enumerable.Empty(); diff --git a/Assets/Cryville/Crtr/SpriteFrame.cs b/Assets/Cryville/Crtr/SpriteFrame.cs index 463ebea..816a3c3 100644 --- a/Assets/Cryville/Crtr/SpriteFrame.cs +++ b/Assets/Cryville/Crtr/SpriteFrame.cs @@ -28,16 +28,16 @@ namespace Cryville.Crtr { float y0 = Mathf.Min(_uv.yMin, _uv.yMax); float y1 = Mathf.Max(_uv.yMin, _uv.yMax); if (m_rotated) cuv = new Vector2[]{ - new Vector2(x0, y1), - new Vector2(x1, y0), - new Vector2(x0, y0), - new Vector2(x1, y1), + new(x0, y1), + new(x1, y0), + new(x0, y0), + new(x1, y1), }; else cuv = new Vector2[]{ - new Vector2(x0, y0), - new Vector2(x1, y1), - new Vector2(x1, y0), - new Vector2(x0, y1), + new(x0, y0), + new(x1, y1), + new(x1, y0), + new(x0, y1), }; } } diff --git a/Assets/Cryville/Crtr/UI/Dialog.cs b/Assets/Cryville/Crtr/UI/Dialog.cs index 20ce8c5..44ab6c0 100644 --- a/Assets/Cryville/Crtr/UI/Dialog.cs +++ b/Assets/Cryville/Crtr/UI/Dialog.cs @@ -14,7 +14,7 @@ namespace Cryville.Crtr.UI { [SerializeField] TextMeshProUGUI m_button1Text; [SerializeField] GameObject m_button1; float _fadeDuration; - static readonly Queue _queue = new Queue(); + static readonly Queue _queue = new(); struct DialogEntry { public Action callback; public string message; @@ -57,8 +57,7 @@ namespace Cryville.Crtr.UI { } public void OnButton(int id) { if (_cur == null) return; - var cb = _cur.Value.callback; - if (cb != null) cb(id); + _cur.Value.callback?.Invoke(id); _cur = null; } public static void Suppress() { @@ -75,15 +74,14 @@ namespace Cryville.Crtr.UI { _queue.Enqueue(new DialogEntry { callback = callback, message = message, action0 = action0, action1 = action1 }); } public static int ShowAndWait(string message, string action0 = "OK", string action1 = null) { - using (var ev = new AutoResetEvent(false)) { - int result = 0; - _queue.Enqueue(new DialogEntry { - callback = r => { result = r; ev.Set(); }, - message = message, action0 = action0, action1 = action1, - }); - ev.WaitOne(); - return result; - } + using var ev = new AutoResetEvent(false); + int result = 0; + _queue.Enqueue(new DialogEntry { + callback = r => { result = r; ev.Set(); }, + message = message, action0 = action0, action1 = action1, + }); + ev.WaitOne(); + return result; } } } diff --git a/Assets/Cryville/Crtr/UI/Menu.cs b/Assets/Cryville/Crtr/UI/Menu.cs index fadf9e3..73e9b1a 100644 --- a/Assets/Cryville/Crtr/UI/Menu.cs +++ b/Assets/Cryville/Crtr/UI/Menu.cs @@ -57,7 +57,7 @@ namespace Cryville.Crtr.UI { } #pragma warning restore IDE0051 - readonly Stack _uiStack = new Stack(); + readonly Stack _uiStack = new(); public void PushTitle(string title) { _uiStack.Push(title); if (m_title) m_title.SetText(title); diff --git a/Assets/Cryville/GlobalSuppressions.cs b/Assets/Cryville/GlobalSuppressions.cs index e54c522..0ecca0e 100644 --- a/Assets/Cryville/GlobalSuppressions.cs +++ b/Assets/Cryville/GlobalSuppressions.cs @@ -3,7 +3,7 @@ // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -using System.Diagnostics.CodeAnalysis; +/*using System.Diagnostics.CodeAnalysis; // Inline variable declaration not supported [assembly: SuppressMessage("Style", "IDE0020")] @@ -49,4 +49,4 @@ using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0251")] // Unity: TryGetComponent not supported -[assembly: SuppressMessage("Performance", "UNT0026")] +[assembly: SuppressMessage("Performance", "UNT0026")]*/ diff --git a/Assets/Plugins/Cryville.Unity.EventSystems/StandaloneInputModule.cs b/Assets/Plugins/Cryville.Unity.EventSystems/StandaloneInputModule.cs index 5e8871d..f0e73ff 100644 --- a/Assets/Plugins/Cryville.Unity.EventSystems/StandaloneInputModule.cs +++ b/Assets/Plugins/Cryville.Unity.EventSystems/StandaloneInputModule.cs @@ -33,8 +33,7 @@ namespace Cryville.Unity.EventSystems { for (int i = 0; i < input.touchCount; i++) { Touch touch = input.GetTouch(i); if (touch.type != TouchType.Indirect) { - bool pressed, released; - PointerEventData pointer = GetTouchPointerEventData(touch, out pressed, out released); + PointerEventData pointer = GetTouchPointerEventData(touch, out bool pressed, out bool released); ProcessTouchPress(pointer, pressed, released); if (!released) { ProcessMove(pointer); @@ -48,8 +47,7 @@ namespace Cryville.Unity.EventSystems { return input.touchCount > 0; } protected new PointerEventData GetTouchPointerEventData(Touch input, out bool pressed, out bool released) { - PointerEventData pointerData; - bool created = GetPointerData(input.fingerId, out pointerData, create: true); + bool created = GetPointerData(input.fingerId, out PointerEventData pointerData, create: true); pointerData.Reset(); pressed = created || input.phase == TouchPhase.Began; released = input.phase == TouchPhase.Canceled || input.phase == TouchPhase.Ended; @@ -65,7 +63,7 @@ namespace Cryville.Unity.EventSystems { pointerData.position = input.position; pointerData.button = PointerEventData.InputButton.Left; if (input.phase == TouchPhase.Canceled) { - pointerData.pointerCurrentRaycast = default(RaycastResult); + pointerData.pointerCurrentRaycast = default; } else { eventSystem.RaycastAll(pointerData, m_RaycastResultCache); diff --git a/Assets/TextMesh Pro/Scripts/Editor/TMP_BaseEditorPanel.cs b/Assets/TextMesh Pro/Scripts/Editor/TMP_BaseEditorPanel.cs index 4f3e646..ff4b598 100644 --- a/Assets/TextMesh Pro/Scripts/Editor/TMP_BaseEditorPanel.cs +++ b/Assets/TextMesh Pro/Scripts/Editor/TMP_BaseEditorPanel.cs @@ -342,7 +342,7 @@ namespace TMPro.EditorUtilities //#if UNITY_2022_1_OR_NEWER //Vector3 newLeft = Handles.FreeMoveHandle(oldLeft, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); //#else - Vector3 newLeft = Handles.FreeMoveHandle(oldLeft, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); + var fmh_345_63_638860614827494399 = Quaternion.identity; Vector3 newLeft = Handles.FreeMoveHandle(oldLeft, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); //#endif bool hasChanged = false; if (oldLeft != newLeft) @@ -361,7 +361,7 @@ namespace TMPro.EditorUtilities //#if UNITY_2022_1_OR_NEWER //Vector3 newTop = Handles.FreeMoveHandle(oldTop, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); //#else - Vector3 newTop = Handles.FreeMoveHandle(oldTop, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); + var fmh_364_61_638860614827520141 = Quaternion.identity; Vector3 newTop = Handles.FreeMoveHandle(oldTop, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); //#endif if (oldTop != newTop) { @@ -379,7 +379,7 @@ namespace TMPro.EditorUtilities //#if UNITY_2022_1_OR_NEWER //Vector3 newRight = Handles.FreeMoveHandle(oldRight, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); //#else - Vector3 newRight = Handles.FreeMoveHandle(oldRight, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); + var fmh_382_65_638860614827523042 = Quaternion.identity; Vector3 newRight = Handles.FreeMoveHandle(oldRight, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); //#endif if (oldRight != newRight) { @@ -397,7 +397,7 @@ namespace TMPro.EditorUtilities //#if UNITY_2022_1_OR_NEWER //Vector3 newBottom = Handles.FreeMoveHandle(oldBottom, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); //#else - Vector3 newBottom = Handles.FreeMoveHandle(oldBottom, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); + var fmh_400_67_638860614827525664 = Quaternion.identity; Vector3 newBottom = Handles.FreeMoveHandle(oldBottom, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap); //#endif if (oldBottom != newBottom) { diff --git a/Assets/TextMesh Pro/Scripts/Runtime/TMP_Settings.cs b/Assets/TextMesh Pro/Scripts/Runtime/TMP_Settings.cs index 18acb71..de83774 100644 --- a/Assets/TextMesh Pro/Scripts/Runtime/TMP_Settings.cs +++ b/Assets/TextMesh Pro/Scripts/Runtime/TMP_Settings.cs @@ -104,13 +104,13 @@ namespace TMPro /// /// The character that will be used as a replacement for missing glyphs in a font asset. /// - public static int missingGlyphCharacter + public static uint missingGlyphCharacter { get { return instance.m_missingGlyphCharacter; } set { instance.m_missingGlyphCharacter = value; } } [SerializeField] - private int m_missingGlyphCharacter; + private uint m_missingGlyphCharacter; /// /// Determines if the "Clear Dynamic Data on Build" property will be set to true or false on newly created dynamic font assets. diff --git a/Assets/TextMesh Pro/Scripts/Runtime/TMP_Text.cs b/Assets/TextMesh Pro/Scripts/Runtime/TMP_Text.cs index 75d332e..41a7bcf 100644 --- a/Assets/TextMesh Pro/Scripts/Runtime/TMP_Text.cs +++ b/Assets/TextMesh Pro/Scripts/Runtime/TMP_Text.cs @@ -1303,7 +1303,7 @@ namespace TMPro /// The source text that contains the missing character. /// The font asset that is missing the requested characters. /// The text component where the requested character is missing. - public delegate void MissingCharacterEventCallback(int unicode, int stringIndex, string text, FontAsset fontAsset, TMP_Text textComponent); + public delegate void MissingCharacterEventCallback(uint unicode, int stringIndex, string text, FontAsset fontAsset, TMP_Text textComponent); /// /// Event delegate to be called when the requested Unicode character is missing from the font asset. @@ -1512,7 +1512,7 @@ namespace TMPro [System.Diagnostics.DebuggerDisplay("Unicode ({unicode}) '{(char)unicode}'")] internal struct UnicodeChar { - public int unicode; + public uint unicode; public int stringIndex; public int length; } @@ -2120,11 +2120,11 @@ namespace TMPro if (writeIndex + 2 > m_TextProcessingArray.Length) ResizeInternalArray(ref m_TextProcessingArray); - m_TextProcessingArray[writeIndex].unicode = (int)m_TextBackingArray[readIndex + 1]; + m_TextProcessingArray[writeIndex].unicode = m_TextBackingArray[readIndex + 1]; m_TextProcessingArray[writeIndex].stringIndex = readIndex; m_TextProcessingArray[writeIndex].length = 1; - m_TextProcessingArray[writeIndex + 1].unicode = (int)m_TextBackingArray[readIndex + 2]; + m_TextProcessingArray[writeIndex + 1].unicode = m_TextBackingArray[readIndex + 2]; m_TextProcessingArray[writeIndex + 1].stringIndex = readIndex; m_TextProcessingArray[writeIndex + 1].length = 1; @@ -2215,7 +2215,7 @@ namespace TMPro { if (writeIndex == m_TextProcessingArray.Length) ResizeInternalArray(ref m_TextProcessingArray); - m_TextProcessingArray[writeIndex].unicode = (int)TMP_TextParsingUtilities.ConvertToUTF32(c, m_TextBackingArray[readIndex + 1]); + m_TextProcessingArray[writeIndex].unicode = TMP_TextParsingUtilities.ConvertToUTF32(c, m_TextBackingArray[readIndex + 1]); m_TextProcessingArray[writeIndex].stringIndex = readIndex; m_TextProcessingArray[writeIndex].length = 2; @@ -2305,7 +2305,7 @@ namespace TMPro if (writeIndex == m_TextProcessingArray.Length) ResizeInternalArray(ref m_TextProcessingArray); - m_TextProcessingArray[writeIndex].unicode = (int)c; + m_TextProcessingArray[writeIndex].unicode = c; m_TextProcessingArray[writeIndex].stringIndex = readIndex; m_TextProcessingArray[writeIndex].length = 1; @@ -2811,11 +2811,11 @@ namespace TMPro int styleLength = style.styleOpeningTagArray.Length; // Replace