From 31eb773bdd627c08da565b5b99946ce54d7809ab Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Sun, 15 Sep 2024 19:56:49 -0500 Subject: [PATCH 01/31] refactor: comment out private fields/variables that are not used --- Prowl.Editor/Editor/GameWindow.cs | 2 +- Prowl.Editor/Editor/SceneViewWindow.cs | 2 +- Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Prowl.Editor/Editor/GameWindow.cs b/Prowl.Editor/Editor/GameWindow.cs index a845a7f71..8b630aa13 100644 --- a/Prowl.Editor/Editor/GameWindow.cs +++ b/Prowl.Editor/Editor/GameWindow.cs @@ -34,7 +34,7 @@ public enum Resolutions const int HeaderHeight = 27; RenderTexture RenderTarget; - bool previouslyPlaying = false; + // bool previouslyPlaying = false; bool hasFrame; public static WeakReference LastFocused; diff --git a/Prowl.Editor/Editor/SceneViewWindow.cs b/Prowl.Editor/Editor/SceneViewWindow.cs index 6155ed5c6..0c084e9bd 100644 --- a/Prowl.Editor/Editor/SceneViewWindow.cs +++ b/Prowl.Editor/Editor/SceneViewWindow.cs @@ -26,7 +26,7 @@ public class SceneViewWindow : EditorWindow double fpsTimer; double fps; double moveSpeed = 1; - bool hasStarted = false; + // bool hasStarted = false; double camX, camY; readonly TransformGizmo gizmo; diff --git a/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs b/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs index a28e39666..7f98caf03 100644 --- a/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs +++ b/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs @@ -63,7 +63,7 @@ public DtNavMeshQuery? Query private Bounds debug_bounds; private Vector3[][][] debug_polygons; - private float timer = 0; + // private float timer = 0; #endregion From fa9425785f2155e75a742b58e35aa83c716c3f94 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Sun, 15 Sep 2024 19:58:37 -0500 Subject: [PATCH 02/31] refactor: comment out private fields that are not used --- Prowl.Editor/Assets/Importers/FontImporter.cs | 2 +- Prowl.Editor/Editor/EditorWindow.cs | 4 ++-- Prowl.Editor/Editor/SceneViewWindow.cs | 4 ++-- Prowl.Runtime/Components/Audio/AudioSource.cs | 2 +- Prowl.Runtime/GUI/Widgets/Gizmo/ViewManipulatorGizmo.cs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Prowl.Editor/Assets/Importers/FontImporter.cs b/Prowl.Editor/Assets/Importers/FontImporter.cs index f3072d170..9341fa240 100644 --- a/Prowl.Editor/Assets/Importers/FontImporter.cs +++ b/Prowl.Editor/Assets/Importers/FontImporter.cs @@ -27,7 +27,7 @@ public override void Import(SerializedAsset ctx, FileInfo assetPath) [CustomEditor(typeof(FontImporter))] public class FontEditor : ScriptedEditor { - static int start, end; + // static int start, end; private readonly int numberOfProperties = 0; public void InputFloat(string name, ref float val) { diff --git a/Prowl.Editor/Editor/EditorWindow.cs b/Prowl.Editor/Editor/EditorWindow.cs index 63dcb2828..86bac7cba 100644 --- a/Prowl.Editor/Editor/EditorWindow.cs +++ b/Prowl.Editor/Editor/EditorWindow.cs @@ -42,7 +42,7 @@ public class EditorWindow public bool IsDocked => m_Leaf != null; private DockNode m_Leaf; - private Vector2 m_DockPosition; + // private Vector2 m_DockPosition; public DockNode Leaf { @@ -359,4 +359,4 @@ protected virtual void Draw() { } protected virtual void Update() { } protected virtual void Close() { } -} \ No newline at end of file +} diff --git a/Prowl.Editor/Editor/SceneViewWindow.cs b/Prowl.Editor/Editor/SceneViewWindow.cs index 0c084e9bd..d5598fe6b 100644 --- a/Prowl.Editor/Editor/SceneViewWindow.cs +++ b/Prowl.Editor/Editor/SceneViewWindow.cs @@ -17,8 +17,8 @@ public class SceneViewWindow : EditorWindow private static bool LastFocusedCameraChanged; readonly Camera Cam; - Material gridMat; - Mesh gridMesh; + // Material gridMat; + // Mesh gridMesh; RenderTexture RenderTarget; Vector2 WindowCenter; Vector2 mouseUV; diff --git a/Prowl.Runtime/Components/Audio/AudioSource.cs b/Prowl.Runtime/Components/Audio/AudioSource.cs index 4a0149fdf..f1b4fe0e4 100644 --- a/Prowl.Runtime/Components/Audio/AudioSource.cs +++ b/Prowl.Runtime/Components/Audio/AudioSource.cs @@ -19,7 +19,7 @@ public sealed class AudioSource : MonoBehaviour private ActiveAudio _source; private AudioBuffer _buffer; - private uint _lastVersion; + // private uint _lastVersion; private bool _looping = false; private float _gain = 1f; private float _maxDistance = 32f; diff --git a/Prowl.Runtime/GUI/Widgets/Gizmo/ViewManipulatorGizmo.cs b/Prowl.Runtime/GUI/Widgets/Gizmo/ViewManipulatorGizmo.cs index db1de1965..17d3e935b 100644 --- a/Prowl.Runtime/GUI/Widgets/Gizmo/ViewManipulatorGizmo.cs +++ b/Prowl.Runtime/GUI/Widgets/Gizmo/ViewManipulatorGizmo.cs @@ -11,7 +11,7 @@ public class ViewManipulatorGizmo private readonly Gui _gui; private Rect _gizmoRect; - private Matrix4x4 _view; + // private Matrix4x4 _view; private Vector3 camForward; private Vector3 camUp; private bool _orthographic; From 09f0d3f7639fd8d5a6c9107ad7010fb804023a70 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 11:33:52 -0500 Subject: [PATCH 03/31] fix: check of not null --- Prowl.Editor/Utilities/MenuItem.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Prowl.Editor/Utilities/MenuItem.cs b/Prowl.Editor/Utilities/MenuItem.cs index 174d3b539..5ed0cbb9f 100644 --- a/Prowl.Editor/Utilities/MenuItem.cs +++ b/Prowl.Editor/Utilities/MenuItem.cs @@ -165,6 +165,8 @@ public static bool DrawMenu(MenuPath menu, bool simpleRoot, int depth, Size? roo if (Gui.ActiveGUI.BeginPopup(menu.Path + "Popup", out var node)) { + ArgumentNullException.ThrowIfNull(node); + using (node.Width(150).Layout(LayoutType.Column).Padding(5).Spacing(5).FitContentHeight().Enter()) { bool changed = false; From f8f2ebeac1bac685021a49d2316657dd5831f929 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 11:34:34 -0500 Subject: [PATCH 04/31] fix: replace `async Task` for `void` for a method that do not use any async internally --- Prowl.Editor/Assets/AssetDatabase.Packages.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Prowl.Editor/Assets/AssetDatabase.Packages.cs b/Prowl.Editor/Assets/AssetDatabase.Packages.cs index 56cdb183f..234616a33 100644 --- a/Prowl.Editor/Assets/AssetDatabase.Packages.cs +++ b/Prowl.Editor/Assets/AssetDatabase.Packages.cs @@ -325,7 +325,7 @@ public static async Task InstallPackage(string packageId, string version) Update(); } - public static async Task UninstallPackage(string packageId, string version) + public static void UninstallPackage(string packageId, string version) { ArgumentNullException.ThrowIfNull(packageId, nameof(packageId)); ArgumentNullException.ThrowIfNull(version, nameof(version)); From f9cdd5957d5bd1879eaf521ed3dc2a10964177e3 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 11:41:14 -0500 Subject: [PATCH 05/31] fix: switch for a SceneViewPreferences.Instance.GridType must contain all possibilities --- Prowl.Editor/Editor/SceneViewWindow.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Prowl.Editor/Editor/SceneViewWindow.cs b/Prowl.Editor/Editor/SceneViewWindow.cs index d5598fe6b..0b3211ea6 100644 --- a/Prowl.Editor/Editor/SceneViewWindow.cs +++ b/Prowl.Editor/Editor/SceneViewWindow.cs @@ -123,6 +123,7 @@ protected override void Draw() Matrix4x4.CreateTranslation(new Vector3(gX, gY, 0)), GridType.YZ => Matrix4x4.CreateLookToLeftHanded(Vector3.zero, Vector3.up, Vector3.right) * Matrix4x4.CreateTranslation(new Vector3(0, gY, gZ)), + _ => throw new NotImplementedException(), }; } From 2277029748131db8ef9276200e175eb449a9a411 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 11:56:09 -0500 Subject: [PATCH 06/31] fix: public static int OrderlessHash must ensure that T is not null because it will be the index of a dictionary --- Prowl.Runtime/Utils/ProwlHash.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Prowl.Runtime/Utils/ProwlHash.cs b/Prowl.Runtime/Utils/ProwlHash.cs index 78bd8830b..712a2e864 100644 --- a/Prowl.Runtime/Utils/ProwlHash.cs +++ b/Prowl.Runtime/Utils/ProwlHash.cs @@ -204,7 +204,7 @@ public static ulong Combine(T1 value1, T2 value2 } // From https://stackoverflow.com/questions/670063/getting-hash-of-a-list-of-strings-regardless-of-order - public static int OrderlessHash(IEnumerable source, IEqualityComparer? comparer = null) + public static int OrderlessHash(IEnumerable source, IEqualityComparer? comparer = null) where T : notnull { comparer ??= EqualityComparer.Default; From 90aef82cff8ae0bfa10ad9b6faa1b5ab02c2e8ba Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 12:11:25 -0500 Subject: [PATCH 07/31] refactor: optimizing Prowl.Runtime.GUI.Spacing to reuse code --- Prowl.Runtime/GUI/Layout/Spacing.cs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/Prowl.Runtime/GUI/Layout/Spacing.cs b/Prowl.Runtime/GUI/Layout/Spacing.cs index f6d9ab800..7cac19637 100644 --- a/Prowl.Runtime/GUI/Layout/Spacing.cs +++ b/Prowl.Runtime/GUI/Layout/Spacing.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. See the LICENSE file in the project root for details. using System; +using System.Diagnostics.CodeAnalysis; namespace Prowl.Runtime.GUI; @@ -31,22 +32,29 @@ public Spacing(double left, double right, double top, double bottom) public static bool operator ==(Spacing s1, Spacing s2) { - return MathD.ApproximatelyEquals(s1.Left, s2.Left) && - MathD.ApproximatelyEquals(s1.Right, s2.Right) && - MathD.ApproximatelyEquals(s1.Top, s2.Top) && - MathD.ApproximatelyEquals(s1.Bottom, s2.Bottom); + return s1.Equals(s2); } public static bool operator !=(Spacing s1, Spacing s2) { - return MathD.ApproximatelyEquals(s1.Left , s2.Left) || - MathD.ApproximatelyEquals(s1.Right , s2.Right) || - MathD.ApproximatelyEquals(s1.Top , s2.Top) || - MathD.ApproximatelyEquals(s1.Bottom , s2.Bottom); + return !s1.Equals(s2); } - public override bool Equals(object obj) + public override bool Equals([AllowNull] object obj) { - throw new System.NotImplementedException(); + return obj is Spacing spacing && Equals(spacing); + } + + public readonly bool Equals(Spacing other) + { + return Left == other.Left && + Right == other.Right && + Top == other.Top && + Bottom == other.Bottom; + } + + public override int GetHashCode() + { + return HashCode.Combine(Left, Right, Top, Bottom); } } From 191e341e2c9e65a23943c7eefa6edb29c394fd78 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 12:21:08 -0500 Subject: [PATCH 08/31] fix: assure that the t.Get is not null inside SerializedProperty.Merge --- Prowl.Runtime/Serializer/SerializedProperty.Compound.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Prowl.Runtime/Serializer/SerializedProperty.Compound.cs b/Prowl.Runtime/Serializer/SerializedProperty.Compound.cs index 6c8f511ed..d25054f85 100644 --- a/Prowl.Runtime/Serializer/SerializedProperty.Compound.cs +++ b/Prowl.Runtime/Serializer/SerializedProperty.Compound.cs @@ -137,10 +137,8 @@ public static SerializedProperty Merge(List allTags) switch (nameVal.Value.TagType) { case PropertyType.Compound: - mergedTag = Merge(allTags.Select(t => t.Get(nameVal.Key)).ToList()); - return mergedTag != null; case PropertyType.List: - mergedTag = Merge(allTags.Select(t => t.Get(nameVal.Key)).ToList()); + mergedTag = Merge(allTags.Where(t => t != null).Select(t => t?.Get(nameVal.Key)!).ToList()); return mergedTag != null; default: if (nameVal.Value.Value?.Equals(nTag.Value) != false) From aea007d0e22e45a16b72b04798d01ed9e2148357 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 12:25:09 -0500 Subject: [PATCH 09/31] fix: KeyFrame's CompareTo and Equals methods allowing null (it will be dealt internally) --- Prowl.Editor/Assets/AssetDatabase.Core.cs | 1 + Prowl.Runtime/AnimationCurve.cs | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Prowl.Editor/Assets/AssetDatabase.Core.cs b/Prowl.Editor/Assets/AssetDatabase.Core.cs index 1cca34a7e..fde5f0a03 100644 --- a/Prowl.Editor/Assets/AssetDatabase.Core.cs +++ b/Prowl.Editor/Assets/AssetDatabase.Core.cs @@ -80,6 +80,7 @@ public static AssetDirectoryCache GetRootFolderCache(int index) public static void AddRootFolder(string rootFolder) { ArgumentException.ThrowIfNullOrEmpty(rootFolder); + ArgumentNullException.ThrowIfNull(Project.Active); var rootPath = Path.Combine(Project.Active.ProjectPath, rootFolder); var info = new DirectoryInfo(rootPath); diff --git a/Prowl.Runtime/AnimationCurve.cs b/Prowl.Runtime/AnimationCurve.cs index adb60b66d..0252d7194 100644 --- a/Prowl.Runtime/AnimationCurve.cs +++ b/Prowl.Runtime/AnimationCurve.cs @@ -4,6 +4,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace Prowl.Runtime; @@ -420,9 +421,9 @@ public KeyFrame(double position, double value, double tangentIn = 0, double tang #region Inherited Methods - public int CompareTo(KeyFrame other) => Position.CompareTo(other.Position); - public bool Equals(KeyFrame other) => (this == other); - public override bool Equals(object obj) => (obj as KeyFrame) != null && Equals((KeyFrame)obj); + public int CompareTo([AllowNull] KeyFrame other) => Position.CompareTo(other.Position); + public bool Equals([AllowNull] KeyFrame other) => this == other; + public override bool Equals([AllowNull] object obj) => (obj as KeyFrame) != null && Equals((KeyFrame)obj); public override int GetHashCode() => Position.GetHashCode() ^ Value.GetHashCode() ^ TangentIn.GetHashCode() ^ TangentOut.GetHashCode() ^ Continuity.GetHashCode(); From 4497acf1b253b8832e94bae61e642b1570df9cc1 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 12:31:41 -0500 Subject: [PATCH 10/31] fix: comment unused field and SceneMeshData.MeshData, that are never used --- Prowl.Runtime/AnimationCurve.cs | 2 +- Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs | 10 +++++----- Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Prowl.Runtime/AnimationCurve.cs b/Prowl.Runtime/AnimationCurve.cs index 0252d7194..73e2d89bc 100644 --- a/Prowl.Runtime/AnimationCurve.cs +++ b/Prowl.Runtime/AnimationCurve.cs @@ -423,7 +423,7 @@ public KeyFrame(double position, double value, double tangentIn = 0, double tang public int CompareTo([AllowNull] KeyFrame other) => Position.CompareTo(other.Position); public bool Equals([AllowNull] KeyFrame other) => this == other; - public override bool Equals([AllowNull] object obj) => (obj as KeyFrame) != null && Equals((KeyFrame)obj); + public override bool Equals([AllowNull] object obj) => obj is KeyFrame keyFrame && Equals(keyFrame); public override int GetHashCode() => Position.GetHashCode() ^ Value.GetHashCode() ^ TangentIn.GetHashCode() ^ TangentOut.GetHashCode() ^ Continuity.GetHashCode(); diff --git a/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs b/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs index 7f98caf03..ee243e106 100644 --- a/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs +++ b/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs @@ -410,11 +410,11 @@ public RcVec3f CalcVel(RcVec3f pos, RcVec3f tgt, float speed) class SceneMeshData { - public class MeshData - { - public List vertices; - public List indices; - } + // public class MeshData + // { + // public List vertices; + // public List indices; + // } public readonly List shapeData = new(); public readonly List transformsOut = new(); diff --git a/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs b/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs index d31bd937d..0a0aa5dd7 100644 --- a/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs +++ b/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs @@ -107,7 +107,7 @@ public enum GizmoOrientation { Global, Local } internal Matrix4x4 ViewProjection; internal Matrix4x4 Model; internal Matrix4x4 ModelViewProjection; - internal Matrix4x4 InverseModelViewProjection; + // internal Matrix4x4 InverseModelViewProjection; private readonly List _subGizmos = []; internal Gui _gui; From 96f57775b2a61fa44e4f419504ff5aa6b438cfa3 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 12:58:02 -0500 Subject: [PATCH 11/31] fix: new InspectorWindow.CreateInstanceCustomEditor to optimized and enhance code --- Prowl.Editor/Editor/InspectorWindow.cs | 29 +++++++++++++++++--------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/Prowl.Editor/Editor/InspectorWindow.cs b/Prowl.Editor/Editor/InspectorWindow.cs index 436887236..f21c653f0 100644 --- a/Prowl.Editor/Editor/InspectorWindow.cs +++ b/Prowl.Editor/Editor/InspectorWindow.cs @@ -8,6 +8,7 @@ using Prowl.Icons; using Prowl.Runtime; using Prowl.Runtime.GUI; +using EditorCustom = (object parent, Prowl.Editor.Assets.ScriptedEditor? editor); namespace Prowl.Editor; @@ -20,7 +21,7 @@ public class InspectorWindow : EditorWindow private object? Selected; private bool lockSelection; - (object, ScriptedEditor)? customEditor; + (object parent, ScriptedEditor scriptedEditor)? customEditor; public InspectorWindow() : base() { @@ -114,9 +115,7 @@ protected override void Draw() Type? editorType = CustomEditorAttribute.GetEditor(meta.importer.GetType()); if (editorType != null) { - customEditor = (path, (ScriptedEditor)Activator.CreateInstance(editorType)); - customEditor.Value.Item2.target = meta; - customEditor.Value.Item2.OnEnable(); + CreateInstanceCustomEditor(path, editorType, meta); destroyCustomEditor = false; } else @@ -143,7 +142,7 @@ protected override void Draw() else if (customEditor.Value.Item1.Equals(path)) { // We are still editing the same asset path - customEditor.Value.Item2.OnInspectorGUI(); + customEditor.Value.scriptedEditor?.OnInspectorGUI(); destroyCustomEditor = false; } } @@ -155,9 +154,7 @@ protected override void Draw() Type? editorType = CustomEditorAttribute.GetEditor(Selected.GetType()); if (editorType != null) { - customEditor = (Selected, (ScriptedEditor)Activator.CreateInstance(editorType)); - customEditor.Value.Item2.target = Selected; - customEditor.Value.Item2.OnEnable(); + customEditor = CreateInstanceCustomEditor(Selected, editorType, Selected); destroyCustomEditor = false; } else @@ -177,19 +174,31 @@ protected override void Draw() else if (customEditor.Value.Item1 == Selected) { // We are still editing the same object - customEditor.Value.Item2.OnInspectorGUI(); + customEditor.Value.scriptedEditor?.OnInspectorGUI(); destroyCustomEditor = false; } } if (destroyCustomEditor) { - customEditor?.Item2.OnDisable(); + customEditor?.scriptedEditor?.OnDisable(); customEditor = null; } } } + private (object parent, ScriptedEditor scriptedEditor)? CreateInstanceCustomEditor(object path, Type editorType, object meta) + { + var scriptedEditor = Activator.CreateInstance(editorType) as ScriptedEditor; + customEditor = (path, scriptedEditor); + if (customEditor.Value.scriptedEditor is not null) + { + customEditor.Value.scriptedEditor.target = meta; + customEditor.Value.scriptedEditor.OnEnable(); + } + return customEditor; + } + private void DrawInspectorLabel(string message) { double ItemSize = EditorStylePrefs.Instance.ItemSize; From 3a622baf9d39bef34dffbc3bcd229599cdf9a261 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 13:07:21 -0500 Subject: [PATCH 12/31] fix: EngineObject.FindObjectsOfType should never return null --- Prowl.Runtime/EngineObject.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Prowl.Runtime/EngineObject.cs b/Prowl.Runtime/EngineObject.cs index 451bccd59..1b66fe76c 100644 --- a/Prowl.Runtime/EngineObject.cs +++ b/Prowl.Runtime/EngineObject.cs @@ -57,7 +57,7 @@ public virtual void OnValidate() { } return null; } - public static T?[] FindObjectsOfType() where T : EngineObject + public static T[] FindObjectsOfType() where T : EngineObject { List objects = new(); foreach (var obj in allObjects) From 56e3ef11da0f062f9a74613a86133b90218d6c2e Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 13:10:31 -0500 Subject: [PATCH 13/31] fix: some arguments passed using `ref`instead the `in` used in the signature --- Prowl.Runtime/Audio/OpenAL/OpenALActiveAudio.cs | 4 ++-- Prowl.Runtime/Rendering/Texture/TextureSampler.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Prowl.Runtime/Audio/OpenAL/OpenALActiveAudio.cs b/Prowl.Runtime/Audio/OpenAL/OpenALActiveAudio.cs index 2665c1ff0..1635e4e7b 100644 --- a/Prowl.Runtime/Audio/OpenAL/OpenALActiveAudio.cs +++ b/Prowl.Runtime/Audio/OpenAL/OpenALActiveAudio.cs @@ -83,7 +83,7 @@ public override Vector3 Position set { System.Numerics.Vector3 vec3 = value; - OpenALEngine.al.SetSourceProperty(ID, SourceVector3.Position, ref vec3); + OpenALEngine.al.SetSourceProperty(ID, SourceVector3.Position, in vec3); } } @@ -97,7 +97,7 @@ public override Vector3 Direction set { System.Numerics.Vector3 vec3 = value; - OpenALEngine.al.SetSourceProperty(ID, SourceVector3.Direction, ref vec3); + OpenALEngine.al.SetSourceProperty(ID, SourceVector3.Direction, in vec3); } } diff --git a/Prowl.Runtime/Rendering/Texture/TextureSampler.cs b/Prowl.Runtime/Rendering/Texture/TextureSampler.cs index baa9cb327..3734dbc51 100644 --- a/Prowl.Runtime/Rendering/Texture/TextureSampler.cs +++ b/Prowl.Runtime/Rendering/Texture/TextureSampler.cs @@ -96,7 +96,7 @@ private void RecreateInternalSampler() { OnDispose(); _internalDescription = description; - _internalSampler = Graphics.Factory.CreateSampler(ref _internalDescription); + _internalSampler = Graphics.Factory.CreateSampler(in _internalDescription); } } From 9ac5c966414acbe2761463d828b98e5bde32b943 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 13:12:22 -0500 Subject: [PATCH 14/31] fix: use `await` to wait async method to finish --- Prowl.Editor/Editor/PackageManager.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Prowl.Editor/Editor/PackageManager.cs b/Prowl.Editor/Editor/PackageManager.cs index 25d2cf086..12d97d5aa 100644 --- a/Prowl.Editor/Editor/PackageManager.cs +++ b/Prowl.Editor/Editor/PackageManager.cs @@ -170,7 +170,7 @@ private void DrawPackageList() } } - private void DrawPackageDetails() + private async void DrawPackageDetails() { if (loadingDetails) { @@ -211,7 +211,7 @@ private void DrawPackageDetails() if (canUpdate && EditorGUI.StyledButton("Update", installWidth / 2, itemSize)) { AssetDatabase.UninstallPackage(_metadata.Identity.Id, installedPackage.Identity.Version.ToString()); - AssetDatabase.InstallPackage(_metadata.Identity.Id, _projectVersions[_selectedVersionIndex]); + await AssetDatabase.InstallPackage(_metadata.Identity.Id, _projectVersions[_selectedVersionIndex]); } if (EditorGUI.StyledButton("Uninstall", canUpdate ? installWidth / 2 : installWidth, itemSize)) @@ -226,7 +226,7 @@ private void DrawPackageDetails() if (gui.Combo("Version", "VersionPopup", ref _selectedVersionIndex, _projectVersions, 0, 0, 75, itemSize)) PopulateDetails(_projectVersions[_selectedVersionIndex]); if (EditorGUI.StyledButton("Install", installWidth, itemSize)) - AssetDatabase.InstallPackage(_metadata.Identity.Id, _projectVersions[_selectedVersionIndex]); + await AssetDatabase.InstallPackage(_metadata.Identity.Id, _projectVersions[_selectedVersionIndex]); } } From 194948f884475d856cb5c7723d6fc347b0e74825 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 13:15:55 -0500 Subject: [PATCH 15/31] fix: rename Prowl.Editor.SelectHandler's Equals to EqualsFunc to avoid name conflict --- Prowl.Editor/SelectHandler.cs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/Prowl.Editor/SelectHandler.cs b/Prowl.Editor/SelectHandler.cs index 1cbcb763c..b9141f02b 100644 --- a/Prowl.Editor/SelectHandler.cs +++ b/Prowl.Editor/SelectHandler.cs @@ -23,7 +23,7 @@ public class SelectHandler where T : class { bool selectedThisFrame; readonly List selected = new(); - SortedList previousFrameSelectables; + SortedList previousFrameSelectables = []; SortedList selectables = new(); int lastSelectedIndex = -1; @@ -35,12 +35,12 @@ public class SelectHandler where T : class public event Action? OnDeselectObject; private readonly Func CheckIsDestroyed; - private readonly Func Equals; + private readonly Func EqualsFunc; public SelectHandler(Func checkIsDestroyed, Func equals) { CheckIsDestroyed = checkIsDestroyed; - Equals = equals; + EqualsFunc = equals; } public void StartFrame() @@ -94,7 +94,7 @@ public bool IsSelected(T obj) { for (int i = 0; i < selected.Count; i++) { - if (Equals.Invoke(selected[i], obj)) + if (EqualsFunc.Invoke(selected[i], obj)) return true; } return false; @@ -155,7 +155,7 @@ public void Select(T obj, bool additively = false) { for (int i = 0; i < selected.Count; i++) { - if (Equals.Invoke(selected[i], obj)) + if (EqualsFunc.Invoke(selected[i], obj)) { selected.RemoveAt(i); break; @@ -178,11 +178,10 @@ public void Select(T obj, bool additively = false) private void SetSelectedIndex(T entity) { - if (previousFrameSelectables == null) return; // if sorted has this value using reference equals, set lastSelectedIndex to the index of it for (int i = 0; i < previousFrameSelectables.Count; i++) { - if (Equals.Invoke(previousFrameSelectables.Values[i], entity)) + if (EqualsFunc.Invoke(previousFrameSelectables.Values[i], entity)) { lastSelectedIndex = previousFrameSelectables.Keys[i]; break; From 0e6c93ee58462eb113ec905d7164629736bdfa17 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 13:19:35 -0500 Subject: [PATCH 16/31] fix: using new and override to avoid conflict with inherited methods --- Prowl.Runtime/Components/Physics/Rigidbody.cs | 2 +- Prowl.Runtime/Resources/ScriptableObject.cs | 4 ++-- Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Prowl.Runtime/Components/Physics/Rigidbody.cs b/Prowl.Runtime/Components/Physics/Rigidbody.cs index e262b0ed0..8b16c662c 100644 --- a/Prowl.Runtime/Components/Physics/Rigidbody.cs +++ b/Prowl.Runtime/Components/Physics/Rigidbody.cs @@ -104,7 +104,7 @@ public ContinuousDetectionMode ContinuousDetectionMode } } - public bool Awake + public new bool Awake { get => BodyReference?.Awake ?? false; set diff --git a/Prowl.Runtime/Resources/ScriptableObject.cs b/Prowl.Runtime/Resources/ScriptableObject.cs index 29ff2f974..4b638da1d 100644 --- a/Prowl.Runtime/Resources/ScriptableObject.cs +++ b/Prowl.Runtime/Resources/ScriptableObject.cs @@ -9,8 +9,8 @@ public ScriptableObject() : base() { } private ScriptableObject(string name) : base(name) { } // ScriptableObjects can only be created via the AssetDatabase loading them, so their guranteed to always Deserialize - public void OnAfterDeserialize() => OnEnable(); - public void OnBeforeSerialize() { } + public virtual void OnAfterDeserialize() => OnEnable(); + public virtual void OnBeforeSerialize() { } public virtual void OnEnable() { } diff --git a/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs b/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs index 55cda142d..c8749b2a8 100644 --- a/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs +++ b/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs @@ -175,9 +175,9 @@ protected virtual void OnDestroy() Clear(); } - public void OnBeforeSerialize() { } + public override void OnBeforeSerialize() { } - public void OnAfterDeserialize() + public override void OnAfterDeserialize() { // Clear null nodes nodes.RemoveAll(n => n == null); From 398b8e6da0761e1e9ecf781a93de1be26a468905 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 14:27:12 -0500 Subject: [PATCH 17/31] fix: unreachable code in Prowl.Runtime.PhysicsSetting --- Prowl.Runtime/Physics.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Prowl.Runtime/Physics.cs b/Prowl.Runtime/Physics.cs index 4b9cd8434..ec625aa5d 100644 --- a/Prowl.Runtime/Physics.cs +++ b/Prowl.Runtime/Physics.cs @@ -61,11 +61,7 @@ public static PhysicsBody GetContainer(CollidableReference collidable) { return GetContainer(collidable.StaticHandle); } - else - { - return GetContainer(collidable.BodyHandle); - } - return null; + return GetContainer(collidable.BodyHandle); } public static Rigidbody GetContainer(BodyHandle handle) From 571d4587c1bb68fad85b09cdf3ac2550cb46f370 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 14:30:39 -0500 Subject: [PATCH 18/31] fix: variable is assigned but its value is never used --- Prowl.Editor/Editor/NodeEditor/NodeEditor.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs index 969abe55e..aedc967dd 100644 --- a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs +++ b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs @@ -1086,15 +1086,16 @@ public void Release() private void DrawMenuItems(NodeMenuItemInfo menuItem, Gui g) { - bool foundName = false; + // bool foundName = false; bool hasSearch = string.IsNullOrEmpty(_searchText) == false; foreach (var item in menuItem.Children) { if (hasSearch && (item.Name.Contains(_searchText, StringComparison.CurrentCultureIgnoreCase) == false || item.Type == null)) { DrawMenuItems(item, g); - if (hasSearch && item.Name.Equals(_searchText, StringComparison.CurrentCultureIgnoreCase)) - foundName = true; + // TODO: `foundName` is not used anywhere + // if (hasSearch && item.Name.Equals(_searchText, StringComparison.CurrentCultureIgnoreCase)) + // foundName = true; continue; } From 3f7fb2c82629f995f8402ec0407a7741014ecabf Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 14:44:59 -0500 Subject: [PATCH 19/31] fix: check null before using it --- Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs | 9 +++++---- Prowl.Runtime/Components/Physics/CharacterController.cs | 8 ++++---- .../Physics/Constraints/_ConstraintComponentBase.cs | 2 +- Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs | 3 ++- Prowl.Runtime/GUI/Widgets/Gui.InputField.cs | 2 +- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs b/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs index 45f7b7df8..218e467eb 100644 --- a/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs +++ b/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs @@ -133,9 +133,10 @@ public static bool ParseShader(string input, FileIncluder includer, out Runtime. string sourceCode = sourceBuilder.ToString(); - if (!ParseProgramInfo(sourceCode, out EntryPoint[]? entrypoints, out (int, int)? shaderModel, out CompilationMessage? message)) + if (!ParseProgramInfo(sourceCode, out EntryPoint[] entrypoints, out (int, int)? shaderModel, out CompilationMessage? message)) { - LogCompilationError(message.Value.message, includer, message.Value.line, message.Value.column); + if (message is not null) + LogCompilationError(message.Value.message, includer, message.Value.line, message.Value.column); return false; } @@ -670,10 +671,10 @@ private static Dictionary> ParseKeywords(Tokenizer entrypointsList = []; - entrypoints = null; + entrypoints = []; shaderModel = null; message = null; diff --git a/Prowl.Runtime/Components/Physics/CharacterController.cs b/Prowl.Runtime/Components/Physics/CharacterController.cs index 2b102d3d7..9262a22c7 100644 --- a/Prowl.Runtime/Components/Physics/CharacterController.cs +++ b/Prowl.Runtime/Components/Physics/CharacterController.cs @@ -33,7 +33,7 @@ public override bool Kinematic protected override void RigidbodyAttached() { - ref var character = ref Physics.Characters.AllocateCharacter(BodyReference.Value.Handle); + ref var character = ref Physics.Characters.AllocateCharacter(BodyReference!.Value.Handle); character.LocalUp = new Vector3(0, 1, 0); character.JumpVelocity = jumpVelocity; character.MaximumVerticalForce = maxVerticalForce; @@ -49,12 +49,12 @@ protected override void RigidbodyAttached() protected override void RigidbodyDetached() { - Physics.Characters.RemoveCharacterByBodyHandle(BodyReference.Value.Handle); + Physics.Characters.RemoveCharacterByBodyHandle(BodyReference!.Value.Handle); } public override void Update() { - ref var character = ref Physics.Characters.GetCharacterByBodyHandle(BodyReference.Value.Handle); + ref var character = ref Physics.Characters.GetCharacterByBodyHandle(BodyReference!.Value.Handle); character.CosMaximumSlope = MathF.Cos(maxSlope.ToRad()); character.JumpVelocity = jumpVelocity; @@ -75,5 +75,5 @@ public override void Update() BodyReference.Value.LocalInertia = new BodyInertia { InverseMass = 1f / Mass }; } - public void TryJump() => Physics.Characters.GetCharacterByBodyHandle(BodyReference.Value.Handle).TryJump = true; + public void TryJump() => Physics.Characters.GetCharacterByBodyHandle(BodyReference!.Value.Handle).TryJump = true; } diff --git a/Prowl.Runtime/Components/Physics/Constraints/_ConstraintComponentBase.cs b/Prowl.Runtime/Components/Physics/Constraints/_ConstraintComponentBase.cs index 3da64fe0b..9a2e53092 100644 --- a/Prowl.Runtime/Components/Physics/Constraints/_ConstraintComponentBase.cs +++ b/Prowl.Runtime/Components/Physics/Constraints/_ConstraintComponentBase.cs @@ -95,7 +95,7 @@ internal override void RebuildConstraint() int count = 0; foreach (var component in _constraintComponent.Bodies) - bodies[count++] = component.BodyReference.Value.Handle; + bodies[count++] = component.BodyReference!.Value.Handle; Span validBodies = bodies[..count]; diff --git a/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs b/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs index 35897c4ee..50496102f 100644 --- a/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs +++ b/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs @@ -22,7 +22,8 @@ public TextEditRow LayoutRow(int startIndex) r.baseline_y_delta = (float)size.y; r.ymin = 0.0f; r.ymax = (float)size.y; - r.num_chars = text_remaining.Value - startIndex; + if (text_remaining is not null) + r.num_chars = text_remaining.Value - startIndex; return r; } diff --git a/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs b/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs index 6baa96075..ad93b74f9 100644 --- a/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs +++ b/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs @@ -293,7 +293,7 @@ internal static bool OnProcess(WidgetStyle style, Interactable interact, ref str { var temp = (int?)p; Vector2? out_offset = null; - Vector2 rect_size = font.InputTextCalcTextSizeW(Text, p, text_selected_end, ref temp, ref out_offset, true); p = temp.Value; + Vector2 rect_size = font.InputTextCalcTextSizeW(Text, p, text_selected_end, ref temp, ref out_offset, true); p = temp!.Value; if (rect_size.x <= 0.0f) rect_size.x = (int)(font.GetCharAdvance(' ') * 0.50f); // So we can see selected empty lines Rect rect = new Rect(rect_pos + new Vector2(0.0f, bg_offy_up - fontsize), new Vector2(rect_size.x, bg_offy_dn + fontsize)); rect.Clip(clip_rect); From 3adbc9bc9c67d43f3303d87a57faebfdd7786e29 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 14:46:09 -0500 Subject: [PATCH 20/31] refactor: in `AssetsBrowserWindow.DrawFileEntry` no need to use hasSubset. just check if `subAsset` is not null --- Prowl.Editor/Editor/AssetsBrowserWindow.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Prowl.Editor/Editor/AssetsBrowserWindow.cs b/Prowl.Editor/Editor/AssetsBrowserWindow.cs index f28898527..406d4bc31 100644 --- a/Prowl.Editor/Editor/AssetsBrowserWindow.cs +++ b/Prowl.Editor/Editor/AssetsBrowserWindow.cs @@ -334,20 +334,20 @@ public void RenderEntry(ref int index, AssetDirectoryCache.FileNode entry) var interact = gui.GetInteractable(); AssetsTreeWindow.HandleFileClick(-1, interact, entry, i, true); - DrawFileEntry(index++, entry.File, interact, true, subAssets[i]); + DrawFileEntry(index++, entry.File, interact, subAssets[i]); } } } } - private void DrawFileEntry(int index, FileSystemInfo entry, Interactable interact, bool hasSubAsset = false, AssetDatabase.SubAssetCache? subAsset = null) + private void DrawFileEntry(int index, FileSystemInfo entry, Interactable interact, AssetDatabase.SubAssetCache? subAsset = null) { var rect = gui.CurrentNode.LayoutData.Rect; //if (hasSubAsset) // rect.Expand(-10); var entrySize = rect.width; - gui.Tooltip(hasSubAsset ? subAsset.Value.name : entry.FullName); + gui.Tooltip(subAsset is not null ? subAsset.Value.name : entry.FullName); var color = EditorStylePrefs.Instance.Borders; if (entry is FileInfo f) From d7a54f2c20325fc81dcc32248e4c3ea6ff8b8bc7 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 15:04:50 -0500 Subject: [PATCH 21/31] fix: CS8603 check for null before using it --- .../Assets/AssetDatabase.Utilities.cs | 2 +- Prowl.Editor/Editor/Docking/DockContainer.cs | 30 ++++++++++--------- Prowl.Editor/Editor/Docking/DockNode.cs | 8 ++--- Prowl.Editor/Editor/EditorWindow.cs | 8 ++--- Prowl.Editor/Editor/NodeEditor/NodeEditor.cs | 14 +++++---- .../Drawers/PropertyDrawerEnumerable.cs | 16 +++++----- Prowl.Editor/EditorGuiManager.cs | 18 +++++------ Prowl.Editor/Utilities/TreePath.cs | 4 +-- .../Prowl.Desktop/StandaloneAssetProvider.cs | 2 +- 9 files changed, 55 insertions(+), 47 deletions(-) diff --git a/Prowl.Editor/Assets/AssetDatabase.Utilities.cs b/Prowl.Editor/Assets/AssetDatabase.Utilities.cs index e33483436..fe4e83a43 100644 --- a/Prowl.Editor/Assets/AssetDatabase.Utilities.cs +++ b/Prowl.Editor/Assets/AssetDatabase.Utilities.cs @@ -239,7 +239,7 @@ public static void GenerateUniqueAssetPath(ref FileInfo file) return result; } - public static Type GetTypeOfAsset(Guid guid, ushort fileID) + public static Type? GetTypeOfAsset(Guid guid, ushort fileID) { if (assetGuidToMeta.TryGetValue(guid, out var meta)) if (meta.assetTypes.Length > fileID) diff --git a/Prowl.Editor/Editor/Docking/DockContainer.cs b/Prowl.Editor/Editor/Docking/DockContainer.cs index 696f384e9..bd2c18acf 100644 --- a/Prowl.Editor/Editor/Docking/DockContainer.cs +++ b/Prowl.Editor/Editor/Docking/DockContainer.cs @@ -9,15 +9,15 @@ namespace Prowl.Editor.Docking; public class DockContainer { - public DockNode Root = new DockNode(); - private Vector2 PaddedMins => new Vector2(0, 0); + public DockNode Root = new(); + private Vector2 PaddedMins => new(0, 0); public void Update(Rect root) { Root.UpdateRecursive(root.Min, root.Max); } - public DockNode TraceLeaf(double x, double y) + public DockNode? TraceLeaf(double x, double y) { x -= PaddedMins.x; y -= PaddedMins.y; @@ -25,7 +25,7 @@ public DockNode TraceLeaf(double x, double y) return Root.TraceLeaf(x, y); } - public DockPlacement GetPlacement(double x, double y, out List possibleAreas, out Rect hovered) + public DockPlacement GetPlacement(double x, double y, out List? possibleAreas, out Rect hovered) { possibleAreas = null; hovered = Rect.Zero; @@ -38,21 +38,23 @@ public DockPlacement GetPlacement(double x, double y, out List possibleAre return default; Vector2 cen = (leaf.Mins + leaf.Maxs) * 0.5f; - Vector2 size = new Vector2(100, 100); + Vector2 size = new(100, 100); // TODO: Why do we need to remove half of the size? Shouldn't ((min + max) / 2) be the center already? cen.x -= size.x / 2; cen.y -= size.y / 2; - Rect main = new Rect(cen, size); + Rect main = new(cen, size); - Rect left = new Rect(cen - new Vector2(size.x + 5, 0), size); - Rect right = new Rect(cen + new Vector2(size.x + 5, 0), size); - Rect top = new Rect(cen - new Vector2(0, size.y + 5), size); - Rect bottom = new Rect(cen + new Vector2(0, size.y + 5), size); + Rect left = new(cen - new Vector2(size.x + 5, 0), size); + Rect right = new(cen + new Vector2(size.x + 5, 0), size); + Rect top = new(cen - new Vector2(0, size.y + 5), size); + Rect bottom = new(cen + new Vector2(0, size.y + 5), size); possibleAreas = [main, left, right, top, bottom]; - DockPlacement placement = new DockPlacement(); - placement.Leaf = leaf; - placement.PolygonVerts = new Vector2[4]; + DockPlacement placement = new() + { + Leaf = leaf, + PolygonVerts = new Vector2[4] + }; while (true) { @@ -318,7 +320,7 @@ public bool DetachWindow(EditorWindow window) if (leaf.LeafWindows.Count == 0) { - DockNode parent = FindParent(leaf); + DockNode? parent = FindParent(leaf); if (parent != null) { DockNode neighborNode; diff --git a/Prowl.Editor/Editor/Docking/DockNode.cs b/Prowl.Editor/Editor/Docking/DockNode.cs index 4b69997cd..5c1108372 100644 --- a/Prowl.Editor/Editor/Docking/DockNode.cs +++ b/Prowl.Editor/Editor/Docking/DockNode.cs @@ -52,7 +52,7 @@ public enum NodeType for (int i = 0; i < 2; ++i) { - DockNode leaf = Child[i].TraceLeaf(x, y); + DockNode? leaf = Child[i].TraceLeaf(x, y); if (leaf != null) return leaf; } @@ -82,7 +82,7 @@ public enum NodeType return this; } - DockNode node = Child[0].TraceSeparator(x, y); + DockNode? node = Child[0].TraceSeparator(x, y); if (node != null) return node; @@ -138,7 +138,7 @@ public void UpdateRecursive(double x, double y, double w, double h) } } - public DockNode FindParent(DockNode node) + public DockNode? FindParent(DockNode node) { if (Type == NodeType.Leaf) return null; @@ -147,7 +147,7 @@ public DockNode FindParent(DockNode node) if (Child[i] == node) return this; - DockNode n = Child[0].FindParent(node); + DockNode? n = Child[0].FindParent(node); if (n != null) return n; diff --git a/Prowl.Editor/Editor/EditorWindow.cs b/Prowl.Editor/Editor/EditorWindow.cs index 86bac7cba..86ce50644 100644 --- a/Prowl.Editor/Editor/EditorWindow.cs +++ b/Prowl.Editor/Editor/EditorWindow.cs @@ -41,10 +41,10 @@ public class EditorWindow public double MaxZ = double.MinValue; public bool IsDocked => m_Leaf != null; - private DockNode m_Leaf; + private DockNode? m_Leaf; // private Vector2 m_DockPosition; - public DockNode Leaf + public DockNode? Leaf { get => m_Leaf; internal set => m_Leaf = value; @@ -128,7 +128,7 @@ public void ProcessFrame() { HandleTitleBarInteraction(); - if (IsDocked && Leaf.LeafWindows.Count > 0) + if (IsDocked && Leaf?.LeafWindows.Count > 0) { double[] tabWidths = new double[Leaf.LeafWindows.Count]; double total = 0; @@ -310,7 +310,7 @@ private void HandleTitleBarInteraction() if (gui.IsPointerMoving && IsDocked) { - EditorGuiManager.Container.DetachWindow(this); + EditorGuiManager.Container?.DetachWindow(this); // Position the window so the mouse is over the title bar _x = gui.PointerPos.x - (_width / 2); _y = gui.PointerPos.y - 10; diff --git a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs index aedc967dd..e22b6ca5f 100644 --- a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs +++ b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs @@ -444,9 +444,13 @@ protected bool DrawBackingField(Gui g, Node node, int fieldIndex, NodePort port) bool changed = false; var fieldInfo = GetFieldInfo(port.node.GetType(), port.fieldName); - InputAttribute field = fieldInfo.GetCustomAttributes(true).FirstOrDefault(); + if (fieldInfo is null) + { + return changed; + } + InputAttribute? field = fieldInfo.GetCustomAttributes(true).FirstOrDefault(); bool showBacking = false; - if (field.backingValue != ShowBackingValue.Never) + if (field is not null && field.backingValue != ShowBackingValue.Never) showBacking = field.backingValue == ShowBackingValue.Always || (field.backingValue == ShowBackingValue.Unconnected && !port.IsConnected); if (showBacking) @@ -462,12 +466,12 @@ protected bool DrawBackingField(Gui g, Node node, int fieldIndex, NodePort port) return changed; } - protected static FieldInfo GetFieldInfo(Type type, string fieldName) + protected static FieldInfo? GetFieldInfo(Type type, string fieldName) { // If we can't find field in the first run, it's probably a private field in a base class. - FieldInfo field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + FieldInfo? field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); // Search base classes for private fields only. Public fields are found above - while (field == null && (type = type.BaseType) != typeof(Node)) field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); + while (field is not null && type.BaseType is not null && (type = type.BaseType) != typeof(Node)) field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); return field; } diff --git a/Prowl.Editor/Editor/PropertyDrawer/Drawers/PropertyDrawerEnumerable.cs b/Prowl.Editor/Editor/PropertyDrawer/Drawers/PropertyDrawerEnumerable.cs index 0091cf7ca..a20e51096 100644 --- a/Prowl.Editor/Editor/PropertyDrawer/Drawers/PropertyDrawerEnumerable.cs +++ b/Prowl.Editor/Editor/PropertyDrawer/Drawers/PropertyDrawerEnumerable.cs @@ -1,6 +1,8 @@ // This file is part of the Prowl Game Engine // Licensed under the MIT License. See the LICENSE file in the project root for details. +using DotRecast.Core; + using Prowl.Editor.Preferences; using Prowl.Icons; using Prowl.Runtime; @@ -104,12 +106,12 @@ public override bool PropertyLayout(Gui gui, string label, int index, Type prope // See if Element has a field called "Name" or "name" and use that as the label var nameField = ElementType(list).GetField("Name") ?? ElementType(list).GetField("name"); - string elementName = ((string)nameField?.GetValue(element)) ?? "Element " + i; + string elementName = nameField?.GetValue(element) as string ?? "Element " + i; config |= EditorGUI.PropertyGridConfig.NoBackground; changed |= DrawerAttribute.DrawProperty(gui, elementName, i, ElementType(list), ref element, config); if (changed) - SetElement(list, i, element); + SetElement(list, i, element!); if (drawerID == selectedDrawer && i == selectedElement) @@ -222,14 +224,14 @@ public override bool PropertyLayout(Gui gui, string label, int index, Type prope [Drawer(typeof(Array))] public class PropertyDrawerArray : PropertyDrawerEnumerable { - protected override Type ElementType(Array value) => value.GetType().GetElementType(); + protected override Type ElementType(Array value) => value.GetType().GetElementType()!; protected override int GetCount(Array value) => value.Length; - protected override object GetElement(Array value, int index) => value.GetValue(index); + protected override object GetElement(Array value, int index) => value.GetValue(index)!; protected override void SetElement(Array value, int index, object element) => value.SetValue(element, index); protected override void RemoveElement(ref Array value, int index) { var elementType = value.GetType().GetElementType(); - var newArray = Array.CreateInstance(elementType, value.Length - 1); + var newArray = Array.CreateInstance(elementType!, value.Length - 1); Array.Copy(value, 0, newArray, 0, index); Array.Copy(value, index + 1, newArray, index, value.Length - index - 1); value = newArray; @@ -237,7 +239,7 @@ protected override void RemoveElement(ref Array value, int index) protected override void AddElement(ref Array value) { var elementType = value.GetType().GetElementType(); - var newArray = Array.CreateInstance(elementType, value.Length + 1); + var newArray = Array.CreateInstance(elementType!, value.Length + 1); Array.Copy(value, newArray, value.Length); value = newArray; } @@ -248,7 +250,7 @@ public class PropertyDrawerList : PropertyDrawerEnumerable value.GetType().GetGenericArguments()[0]; protected override int GetCount(System.Collections.IList value) => value.Count; - protected override object GetElement(System.Collections.IList value, int index) => value[index]; + protected override object GetElement(System.Collections.IList value, int index) => value[index] ?? throw new Exception(); protected override void SetElement(System.Collections.IList value, int index, object element) => value[index] = element; protected override void RemoveElement(ref System.Collections.IList value, int index) => value.RemoveAt(index); protected override void AddElement(ref System.Collections.IList value) diff --git a/Prowl.Editor/EditorGuiManager.cs b/Prowl.Editor/EditorGuiManager.cs index 846df24a0..8547147e0 100644 --- a/Prowl.Editor/EditorGuiManager.cs +++ b/Prowl.Editor/EditorGuiManager.cs @@ -19,9 +19,9 @@ public static class EditorGuiManager public static System.Numerics.Vector4 SelectedColor => new System.Numerics.Vector4(0.06f, 0.53f, 0.98f, 1.00f); public static Gui Gui; - public static DockContainer? Container; + public static DockContainer Container; public static EditorWindow DraggingWindow; - public static DockNode DragSplitter; + public static DockNode? DragSplitter; private static Vector2 m_DragPos; private static double m_StartSplitPos; @@ -49,7 +49,7 @@ public static void FocusWindow(EditorWindow editorWindow) Windows.Add(editorWindow); FocusedWindow = new WeakReference(editorWindow); - if (editorWindow.IsDocked) + if (editorWindow.IsDocked && editorWindow.Leaf is not null) editorWindow.Leaf.WindowNum = editorWindow.Leaf.LeafWindows.IndexOf(editorWindow); } @@ -69,8 +69,8 @@ internal static void Remove(EditorWindow editorWindow) public static void Update() { - if (FocusedWindow != null && FocusedWindow.Target != null) - FocusWindow(FocusedWindow.Target as EditorWindow); // Ensure focused window is always on top (But below floating windows if docked) + if (FocusedWindow != null && FocusedWindow.Target != null && FocusedWindow.Target is EditorWindow editorWindow) + FocusWindow(editorWindow); // Ensure focused window is always on top (But below floating windows if docked) // Sort by docking as well, Docked windows are guranteed to come first Windows.Sort((a, b) => b.IsDocked.CompareTo(a.IsDocked)); @@ -208,7 +208,7 @@ private static void DrawContent(Gui g) { if (!Gui.IsBlockedByInteractable(cursorPos)) { - DockNode node = Container.Root.TraceSeparator(cursorPos.x, cursorPos.y); + DockNode? node = Container.Root.TraceSeparator(cursorPos.x, cursorPos.y); if (node != null) { node.GetSplitterBounds(out var bmins, out var bmaxs, 4); @@ -273,7 +273,7 @@ private static void DrawContent(Gui g) for (int i = 0; i < windowList.Count; i++) { EditorWindow window = windowList[i]; - if (!window.IsDocked || window.Leaf.LeafWindows[window.Leaf.WindowNum] == window) + if (!window.IsDocked || window.Leaf?.LeafWindows[window.Leaf.WindowNum] == window) { g.SetZIndex(i * 100); g.PushID((ulong)window._id); @@ -308,7 +308,7 @@ public static void SaveScene() return; } - if (AssetDatabase.TryGetFile(scene.AssetID, out var file)) + if (AssetDatabase.TryGetFile(scene.AssetID, out var file) && file is not null) { AssetDatabase.Delete(file); @@ -464,7 +464,7 @@ public static void CreateScript() FileInfo file = new FileInfo(Path.Combine(Directory.FullName, $"New Script.cs")); AssetDatabase.GenerateUniqueAssetPath(ref file); - using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"Prowl.Editor.EmbeddedResources.NewScript.txt"); + using Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"Prowl.Editor.EmbeddedResources.NewScript.txt") ?? throw new Exception(); using StreamReader reader = new StreamReader(stream); string script = reader.ReadToEnd(); script = script.Replace("%SCRIPTNAME%", EditorUtils.FilterAlpha(Path.GetFileNameWithoutExtension(file.Name))); diff --git a/Prowl.Editor/Utilities/TreePath.cs b/Prowl.Editor/Utilities/TreePath.cs index 412885b8c..4a630acbb 100644 --- a/Prowl.Editor/Utilities/TreePath.cs +++ b/Prowl.Editor/Utilities/TreePath.cs @@ -41,10 +41,10 @@ public void AddChild(string path, T data = default) currentNode.Children.Add(leafNode); } - public TreePath FindNode(string path) + public TreePath? FindNode(string path) { string[] parts = path.Split('/'); - TreePath currentNode = this; + TreePath? currentNode = this; foreach (string part in parts) { diff --git a/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs b/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs index 17c27e730..05d14e485 100644 --- a/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs +++ b/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs @@ -73,7 +73,7 @@ public AssetRef LoadAsset(IAssetRef assetID) where T : EngineObject throw new FileNotFoundException($"Asset with GUID {guid} not found."); } - public string GetPathFromGUID(Guid guid) + public string? GetPathFromGUID(Guid guid) { foreach (AssetBundle package in packages) if (package.TryGetPath(guid, out var path)) From 93617edc97faa76c9b220210d9c81b2b63b76672 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 15:35:19 -0500 Subject: [PATCH 22/31] fix: several null checks --- Prowl.Editor/Assets/AssetDatabase.Core.cs | 6 +- .../Assets/Importers/AudioClipImporter.cs | 5 +- Prowl.Editor/Assets/Importers/FontImporter.cs | 2 +- .../Assets/Importers/MaterialImporter.cs | 2 +- .../Assets/Importers/ModelImporter.cs | 2 +- .../Assets/Importers/TextureImporter.cs | 2 +- Prowl.Editor/Assets/MetaFile.cs | 5 +- Prowl.Editor/Editor/InspectorWindow.cs | 2 +- Prowl.Editor/Editor/NodeEditor/NodeEditor.cs | 2 +- Prowl.Editor/Editor/ProjectSettingsWindow.cs | 4 +- .../ScriptedEditors/ScriptableObjectEditor.cs | 19 +-- Prowl.Editor/Utilities/TreePath.cs | 14 +- .../Prowl.Desktop/StandaloneAssetProvider.cs | 12 +- Prowl.Runtime/AssetRef.cs | 2 +- Prowl.Runtime/Components/MeshRenderer.cs | 2 +- .../Components/SkinnedMeshRenderer.cs | 2 +- .../GUI/Graphics/UIDrawListRenderer.cs | 2 +- Prowl.Runtime/GUI/Widgets/Gui.InputField.cs | 129 +++++++++--------- Prowl.Runtime/GameObject/MonoBehaviour.cs | 2 +- Prowl.Runtime/Utils/MultiValueDictionary.cs | 18 +-- 20 files changed, 120 insertions(+), 114 deletions(-) diff --git a/Prowl.Editor/Assets/AssetDatabase.Core.cs b/Prowl.Editor/Assets/AssetDatabase.Core.cs index fde5f0a03..82ce36938 100644 --- a/Prowl.Editor/Assets/AssetDatabase.Core.cs +++ b/Prowl.Editor/Assets/AssetDatabase.Core.cs @@ -249,7 +249,7 @@ static bool ProcessFile(string file, out bool metaOutdated) { // No meta file, create and import var newMeta = new MetaFile(fileInfo); - if (newMeta.importer == null) + if (newMeta.Importer == null) { Debug.LogError($"No importer found for file:\n{fileInfo.FullName}"); return false; @@ -352,7 +352,7 @@ public static bool Reimport(FileInfo assetFile, bool disposeExisting = true) Debug.LogError($"No valid meta file found for asset: {ToRelativePath(assetFile)}"); return false; } - if (meta.importer == null) + if (meta.Importer == null) { Debug.LogError($"No valid importer found for asset: {ToRelativePath(assetFile)}"); return false; @@ -362,7 +362,7 @@ public static bool Reimport(FileInfo assetFile, bool disposeExisting = true) SerializedAsset ctx = new(meta.guid); try { - meta.importer.Import(ctx, assetFile); + meta.Importer.Import(ctx, assetFile); } catch (Exception e) { diff --git a/Prowl.Editor/Assets/Importers/AudioClipImporter.cs b/Prowl.Editor/Assets/Importers/AudioClipImporter.cs index e078b223d..dd6f38fc6 100644 --- a/Prowl.Editor/Assets/Importers/AudioClipImporter.cs +++ b/Prowl.Editor/Assets/Importers/AudioClipImporter.cs @@ -124,7 +124,8 @@ public class AudioClipEditor : ScriptedEditor public override void OnEnable() { - serialized = AssetDatabase.LoadAsset((target as MetaFile).AssetPath); + var metaFile = target as MetaFile ?? throw new Exception(); + serialized = AssetDatabase.LoadAsset(metaFile.AssetPath) ?? throw new Exception(); } public override void OnDisable() @@ -140,7 +141,7 @@ public override void OnInspectorGUI() { double ItemSize = EditorStylePrefs.Instance.ItemSize; - var importer = (AudioClipImporter)(target as MetaFile).importer; + var importer = (AudioClipImporter)(target as MetaFile).Importer; try { diff --git a/Prowl.Editor/Assets/Importers/FontImporter.cs b/Prowl.Editor/Assets/Importers/FontImporter.cs index 9341fa240..6306e3d2c 100644 --- a/Prowl.Editor/Assets/Importers/FontImporter.cs +++ b/Prowl.Editor/Assets/Importers/FontImporter.cs @@ -101,7 +101,7 @@ public override void OnInspectorGUI() { double ItemSize = EditorStylePrefs.Instance.ItemSize; - var importer = (FontImporter)(target as MetaFile).importer; + var importer = (FontImporter)(target as MetaFile).Importer; gui.CurrentNode.Layout(LayoutType.Column); diff --git a/Prowl.Editor/Assets/Importers/MaterialImporter.cs b/Prowl.Editor/Assets/Importers/MaterialImporter.cs index 420219bdb..28115f558 100644 --- a/Prowl.Editor/Assets/Importers/MaterialImporter.cs +++ b/Prowl.Editor/Assets/Importers/MaterialImporter.cs @@ -38,7 +38,7 @@ public class MaterialImporterEditor : ScriptedEditor { public override void OnInspectorGUI() { - var importer = (MaterialImporter)(target as MetaFile).importer; + var importer = (MaterialImporter)(target as MetaFile).Importer; try { diff --git a/Prowl.Editor/Assets/Importers/ModelImporter.cs b/Prowl.Editor/Assets/Importers/ModelImporter.cs index 86947ed4c..22978f18e 100644 --- a/Prowl.Editor/Assets/Importers/ModelImporter.cs +++ b/Prowl.Editor/Assets/Importers/ModelImporter.cs @@ -667,7 +667,7 @@ public override void OnInspectorGUI() { double ItemSize = EditorStylePrefs.Instance.ItemSize; - var importer = (ModelImporter)(target as MetaFile).importer; + var importer = (ModelImporter)(target as MetaFile).Importer; var serialized = AssetDatabase.LoadAsset((target as MetaFile).AssetPath); gui.CurrentNode.Layout(LayoutType.Column); diff --git a/Prowl.Editor/Assets/Importers/TextureImporter.cs b/Prowl.Editor/Assets/Importers/TextureImporter.cs index 7d0bf576f..8a60277c1 100644 --- a/Prowl.Editor/Assets/Importers/TextureImporter.cs +++ b/Prowl.Editor/Assets/Importers/TextureImporter.cs @@ -53,7 +53,7 @@ public class TextureEditor : ScriptedEditor { public override void OnInspectorGUI() { - var importer = (TextureImporter)(target as MetaFile).importer; + var importer = (TextureImporter)(target as MetaFile).Importer; gui.CurrentNode.Layout(LayoutType.Column); diff --git a/Prowl.Editor/Assets/MetaFile.cs b/Prowl.Editor/Assets/MetaFile.cs index 3415d51d4..886549ec9 100644 --- a/Prowl.Editor/Assets/MetaFile.cs +++ b/Prowl.Editor/Assets/MetaFile.cs @@ -18,7 +18,7 @@ public class MetaFile public string[] assetTypes = []; public DateTime lastModified; - public ScriptedImporter importer; + public readonly ScriptedImporter Importer; public List dependencies; /// Default constructor for MetaFile. @@ -35,7 +35,8 @@ public MetaFile(FileInfo assetFile) AssetPath = assetFile; guid = Guid.NewGuid(); lastModified = assetFile.LastWriteTimeUtc; - importer = Activator.CreateInstance(importerType) as ScriptedImporter; + var importer = Activator.CreateInstance(importerType) as ScriptedImporter; + Importer = importer ?? throw new Exception(); } /// Save the MetaFile to a specified file or default to the associated asset file with a ".meta" extension. diff --git a/Prowl.Editor/Editor/InspectorWindow.cs b/Prowl.Editor/Editor/InspectorWindow.cs index f21c653f0..f58038a92 100644 --- a/Prowl.Editor/Editor/InspectorWindow.cs +++ b/Prowl.Editor/Editor/InspectorWindow.cs @@ -112,7 +112,7 @@ protected override void Draw() var meta = MetaFile.Load(path); if (meta != null) { - Type? editorType = CustomEditorAttribute.GetEditor(meta.importer.GetType()); + Type? editorType = CustomEditorAttribute.GetEditor(meta.Importer.GetType()); if (editorType != null) { CreateInstanceCustomEditor(path, editorType, meta); diff --git a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs index e22b6ca5f..286de3770 100644 --- a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs +++ b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs @@ -1038,7 +1038,7 @@ public bool DrawBlackBoard(Gui gui) { object? obj = graph; // Get graph.parameters field - FieldInfo props = graph.GetType().GetField("parameters", BindingFlags.Instance | BindingFlags.Public); + FieldInfo props = graph.GetType().GetField("parameters", BindingFlags.Instance | BindingFlags.Public) ?? throw new Exception(); return EditorGUI.PropertyGrid("BlackBoard", ref obj, [props], EditorGUI.PropertyGridConfig.NoHeader); } } diff --git a/Prowl.Editor/Editor/ProjectSettingsWindow.cs b/Prowl.Editor/Editor/ProjectSettingsWindow.cs index 9e4ab3e3c..c27093f2c 100644 --- a/Prowl.Editor/Editor/ProjectSettingsWindow.cs +++ b/Prowl.Editor/Editor/ProjectSettingsWindow.cs @@ -107,8 +107,8 @@ private void RenderBody() if (currentType == null) return; // Draw Settings - object setting = currentSingleton; - + object? setting = currentSingleton ?? throw new Exception(); + string name = currentType.Name.Replace("Preferences", ""); if (PropertyGrid(name, ref setting, TargetFields.Serializable | TargetFields.Properties, PropertyGridConfig.NoBorder | PropertyGridConfig.NoBackground)) { diff --git a/Prowl.Editor/Editor/ScriptedEditors/ScriptableObjectEditor.cs b/Prowl.Editor/Editor/ScriptedEditors/ScriptableObjectEditor.cs index 8f3da8b78..ea48c4075 100644 --- a/Prowl.Editor/Editor/ScriptedEditors/ScriptableObjectEditor.cs +++ b/Prowl.Editor/Editor/ScriptedEditors/ScriptableObjectEditor.cs @@ -12,19 +12,20 @@ namespace Prowl.Editor.ScriptedEditors; [CustomEditor(typeof(ScriptableObjectImporter))] public class ScriptableObjectEditor : ScriptedEditor { - ScriptableObject? scriptObject; + ScriptableObject? _scriptObject; public override void OnInspectorGUI() { - var importer = (ScriptableObjectImporter)(target as MetaFile).importer; + var metaFile = target as MetaFile ?? throw new Exception(); + // var importer = (ScriptableObjectImporter)metaFile.importer; try { bool changed = false; - scriptObject ??= Serializer.Deserialize(StringTagConverter.ReadFromFile((target as MetaFile).AssetPath)); + _scriptObject ??= Serializer.Deserialize(StringTagConverter.ReadFromFile(metaFile.AssetPath)); - object t = scriptObject; + object t = _scriptObject ?? throw new Exception(); changed |= PropertyGrid("CompPropertyGrid", ref t, TargetFields.Serializable | TargetFields.Properties, PropertyGridConfig.NoHeader | PropertyGridConfig.NoBorder | PropertyGridConfig.NoBackground); // Draw any Buttons @@ -32,15 +33,15 @@ public override void OnInspectorGUI() if (changed) { - scriptObject.OnValidate(); - StringTagConverter.WriteToFile(Serializer.Serialize(scriptObject), (target as MetaFile).AssetPath); - AssetDatabase.Reimport((target as MetaFile).AssetPath); + _scriptObject.OnValidate(); + StringTagConverter.WriteToFile(Serializer.Serialize(_scriptObject), metaFile.AssetPath); + AssetDatabase.Reimport(metaFile.AssetPath); } } catch (Exception e) { - double ItemSize = EditorStylePrefs.Instance.ItemSize; - gui.Node("DummyForText").ExpandWidth().Height(ItemSize * 10); + double itemSize = EditorStylePrefs.Instance.ItemSize; + gui.Node("DummyForText").ExpandWidth().Height(itemSize * 10); gui.Draw2D.DrawText("Failed to Deserialize ScriptableObject, The ScriptableObject file is invalid. Error: " + e.ToString(), gui.CurrentNode.LayoutData.Rect); } } diff --git a/Prowl.Editor/Utilities/TreePath.cs b/Prowl.Editor/Utilities/TreePath.cs index 4a630acbb..fa1892777 100644 --- a/Prowl.Editor/Utilities/TreePath.cs +++ b/Prowl.Editor/Utilities/TreePath.cs @@ -3,22 +3,22 @@ namespace Prowl.Editor; -public class TreePath +public class TreePath where T : notnull { - public TreePath Parent { get; set; } + public TreePath? Parent { get; set; } public string Name { get; set; } public T Data { get; set; } - public List> Children { get; } = new List>(); + public List> Children { get; } = []; public TreePath() { } - public TreePath(string name, T data = default) + public TreePath(string name, T data) { Name = name; Data = data; } - public void AddChild(string path, T data = default) + public void AddChild(string path, T data) { string[] parts = path.Split('/'); TreePath currentNode = this; @@ -26,7 +26,7 @@ public void AddChild(string path, T data = default) for (int i = 0; i < parts.Length - 1; i++) { string part = parts[i]; - TreePath childNode = currentNode.Children.Find(c => c.Name == part); + TreePath? childNode = currentNode.Children.Find(c => c.Name == part); if (childNode == null) { childNode = new TreePath { Name = part }; @@ -71,4 +71,4 @@ private void SearchRecursive(TreePath node, string query, List> r foreach (TreePath child in node.Children) SearchRecursive(child, query, results, ignoreCase); } -} \ No newline at end of file +} diff --git a/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs b/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs index 05d14e485..c45e4b5fd 100644 --- a/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs +++ b/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs @@ -31,7 +31,7 @@ public AssetRef LoadAsset(string relativeAssetPath, ushort fileID = 0) whe return (T)(fileID == 0 ? _loaded[guid].Main : _loaded[guid].SubAssets[fileID - 1]); foreach (AssetBundle package in packages) - if (package.TryGetAsset(relativeAssetPath, out var asset)) + if (package.TryGetAsset(relativeAssetPath, out var asset) && asset is not null) { _loaded[guid] = asset; return (T)(fileID == 0 ? asset.Main : asset.SubAssets[fileID - 1]); @@ -45,7 +45,7 @@ public AssetRef LoadAsset(Guid guid, ushort fileID = 0) where T : EngineOb return (T)(fileID == 0 ? _loaded[guid].Main : _loaded[guid].SubAssets[fileID - 1]); foreach (AssetBundle package in packages) - if (package.TryGetAsset(guid, out var asset)) + if (package.TryGetAsset(guid, out var asset) && asset is not null) { _loaded[guid] = asset; return (T)(fileID == 0 ? asset.Main : asset.SubAssets[fileID - 1]); @@ -53,7 +53,7 @@ public AssetRef LoadAsset(Guid guid, ushort fileID = 0) where T : EngineOb throw new FileNotFoundException($"Asset with GUID {guid} not found."); } - public AssetRef LoadAsset(IAssetRef assetID) where T : EngineObject + public AssetRef LoadAsset(IAssetRef? assetID) where T : EngineObject { if (assetID == null) return null; return LoadAsset(assetID.AssetID, assetID.FileID); @@ -61,11 +61,11 @@ public AssetRef LoadAsset(IAssetRef assetID) where T : EngineObject public SerializedAsset? LoadAsset(Guid guid) { - if (_loaded.ContainsKey(guid)) - return _loaded[guid]; + if (_loaded.TryGetValue(guid, out SerializedAsset? loadAsset)) + return loadAsset; foreach (AssetBundle package in packages) - if (package.TryGetAsset(guid, out var asset)) + if (package.TryGetAsset(guid, out var asset) && asset is not null) { _loaded[guid] = asset; return asset; diff --git a/Prowl.Runtime/AssetRef.cs b/Prowl.Runtime/AssetRef.cs index 5c6a3094a..aa4335ed2 100644 --- a/Prowl.Runtime/AssetRef.cs +++ b/Prowl.Runtime/AssetRef.cs @@ -85,7 +85,7 @@ public bool IsAvailable { get { - if (instance != null && !instance.IsDestroyed) return true; + if (instance is { IsDestroyed: false }) return true; RetrieveInstance(); return instance != null; } diff --git a/Prowl.Runtime/Components/MeshRenderer.cs b/Prowl.Runtime/Components/MeshRenderer.cs index ac140106d..9c2320d70 100644 --- a/Prowl.Runtime/Components/MeshRenderer.cs +++ b/Prowl.Runtime/Components/MeshRenderer.cs @@ -74,7 +74,7 @@ public Material GetMaterial() public void GetRenderingData(out PropertyBlock properties, out IGeometryDrawData drawData, out Matrix4x4 model) { - drawData = Mesh.Res; + drawData = Mesh.Res ?? throw new System.ArgumentNullException(nameof(Mesh)); properties = Properties; model = Transform.localToWorldMatrix; } diff --git a/Prowl.Runtime/Components/SkinnedMeshRenderer.cs b/Prowl.Runtime/Components/SkinnedMeshRenderer.cs index 4727ffec6..fdfb6e235 100644 --- a/Prowl.Runtime/Components/SkinnedMeshRenderer.cs +++ b/Prowl.Runtime/Components/SkinnedMeshRenderer.cs @@ -78,6 +78,6 @@ public void Deserialize(SerializedProperty value, Serializer.SerializationContex { Mesh = Serializer.Deserialize>(value["Mesh"], ctx); Material = Serializer.Deserialize>(value["Material"], ctx); - Bones = Serializer.Deserialize(value["Bones"], ctx); + Bones = Serializer.Deserialize(value["Bones"], ctx) ?? []; } } diff --git a/Prowl.Runtime/GUI/Graphics/UIDrawListRenderer.cs b/Prowl.Runtime/GUI/Graphics/UIDrawListRenderer.cs index 21571dfa5..ed5ff7d7f 100644 --- a/Prowl.Runtime/GUI/Graphics/UIDrawListRenderer.cs +++ b/Prowl.Runtime/GUI/Graphics/UIDrawListRenderer.cs @@ -19,7 +19,7 @@ public enum ColorSpaceHandling public static class UIDrawListRenderer { - private static readonly Assembly s_assembly = Assembly.GetAssembly(typeof(UIDrawListRenderer)); + private static readonly Assembly s_assembly = Assembly.GetAssembly(typeof(UIDrawListRenderer)) ?? throw new NullReferenceException(); private static ColorSpaceHandling s_handling; // Device objects diff --git a/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs b/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs index ad93b74f9..82df3ecdb 100644 --- a/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs +++ b/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs @@ -130,50 +130,52 @@ static int ImStrbolW(string data, int bufMidLine, int bufBegin) private static StbTextEditState stb; - internal static bool OnProcess(WidgetStyle style, Interactable interact, ref string Text, uint MaxLength, InputFieldFlags Flags) + internal static bool OnProcess(WidgetStyle style, Interactable interact, ref string text, uint maxLength, InputFieldFlags Flags) { var g = ActiveGUI; - var font = style.Font.IsAvailable ? style.Font.Res : Font.DefaultFont; + var font = style.Font is { IsAvailable: true, Res: not null } ? style.Font.Res : Font.DefaultFont; var fontsize = style.FontSize; - var render_pos = new Vector2(g.CurrentNode.LayoutData.InnerRect.x, g.CurrentNode.LayoutData.InnerRect.y); + var renderPos = new Vector2(g.CurrentNode.LayoutData.InnerRect.x, g.CurrentNode.LayoutData.InnerRect.y); // Center text vertically //render_pos.y += (g.CurrentNode.LayoutData.InnerRect.height - fontsize) / 2; - render_pos.y += 3; - render_pos.x += 5; + renderPos.y += 3; + renderPos.x += 5; bool justSelected = false; - if (stb == null || stb.ID != interact.ID) + if (stb.ID != interact.ID) { justSelected = true; - stb = new(); - stb.ID = interact.ID; - stb.SingleLine = !((Flags & InputFieldFlags.Multiline) == InputFieldFlags.Multiline); - stb.font = font; - stb.Text = Text; + stb = new StbTextEditState + { + ID = interact.ID, + SingleLine = (Flags & InputFieldFlags.Multiline) != InputFieldFlags.Multiline, + font = font, + Text = text + }; } - HandleKeyEvent(stb, MaxLength, Flags); + HandleKeyEvent(stb, maxLength, Flags); HandleMouseEvent(stb); if (justSelected && (Flags & InputFieldFlags.AutoSelectAll) == InputFieldFlags.AutoSelectAll) { stb.SelectStart = 0; - stb.SelectEnd = Text.Length; + stb.SelectEnd = text.Length; } if (g.IsNodeHovered() && g.IsPointerDoubleClick(MouseButton.Left)) { stb.SelectStart = 0; - stb.SelectEnd = Text.Length; + stb.SelectEnd = text.Length; } //g.DrawText(font, Text, fontsize, render_pos, Color.black); // Render - Rect clip_rect = g.CurrentNode.LayoutData.InnerRect; - Vector2 text_size = new Vector2(0f, 0f); + Rect clipRect = g.CurrentNode.LayoutData.InnerRect; + // Vector2 textSize = new Vector2(0f, 0f); stb.cursorAnim += Time.deltaTimeF; - bool is_multiline = !stb.SingleLine; + bool isMultiline = !stb.SingleLine; Vector2 size = new Vector2(g.CurrentNode.LayoutData.InnerRect.width, g.CurrentNode.LayoutData.InnerRect.height); // We need to: @@ -181,33 +183,33 @@ internal static bool OnProcess(WidgetStyle style, Interactable interact, ref str // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d.2d cursor position calculation) // - Measure text height (for scrollbar) // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) - int text_begin = 0; - Vector2 cursor_offset = Vector2.zero, select_start_offset = Vector2.zero; + int textBegin = 0; + Vector2 cursorOffset = Vector2.zero, select_start_offset = Vector2.zero; { // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. - int[] searches_input_ptr = new int[2]; - searches_input_ptr[0] = text_begin + stb.CursorIndex; - searches_input_ptr[1] = -1; + int[] searchesInputPtr = new int[2]; + searchesInputPtr[0] = textBegin + stb.CursorIndex; + searchesInputPtr[1] = -1; int searches_remaining = 1; int[] searches_result_line_number = [-1, -999]; if (stb.SelectStart != stb.SelectEnd) { - searches_input_ptr[1] = text_begin + MathD.Min(stb.SelectStart, stb.SelectEnd); + searchesInputPtr[1] = textBegin + MathD.Min(stb.SelectStart, stb.SelectEnd); searches_result_line_number[1] = -1; searches_remaining++; } // Iterate all lines to find our line numbers // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. - searches_remaining += is_multiline ? 1 : 0; + searches_remaining += isMultiline ? 1 : 0; int line_count = 0; - for (int s = text_begin; s < stb.Text.Length && stb.Text[s] != 0; s++) + for (int s = textBegin; s < stb.Text.Length && stb.Text[s] != 0; s++) if (stb.Text[s] == '\n') { line_count++; - if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } - if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_number[0] == -1 && s >= searchesInputPtr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_number[1] == -1 && s >= searchesInputPtr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } } line_count++; if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; @@ -216,17 +218,18 @@ internal static bool OnProcess(WidgetStyle style, Interactable interact, ref str int? remaining = null; Vector2? out_offset = null; // Calculate 2d position by finding the beginning of the line and measuring distance - cursor_offset.x = font.InputTextCalcTextSizeW(stb.Text, ImStrbolW(stb.Text, searches_input_ptr[0], text_begin), searches_input_ptr[0], ref remaining, ref out_offset).x; - cursor_offset.y = searches_result_line_number[0] * fontsize; + cursorOffset.x = font.InputTextCalcTextSizeW(stb.Text, ImStrbolW(stb.Text, searchesInputPtr[0], textBegin), searchesInputPtr[0], ref remaining, ref out_offset).x; + cursorOffset.y = searches_result_line_number[0] * fontsize; if (searches_result_line_number[1] >= 0) { - select_start_offset.x = font.InputTextCalcTextSizeW(stb.Text, ImStrbolW(stb.Text, searches_input_ptr[1], text_begin), searches_input_ptr[1], ref remaining, ref out_offset).x; + select_start_offset.x = font.InputTextCalcTextSizeW(stb.Text, ImStrbolW(stb.Text, searchesInputPtr[1], textBegin), searchesInputPtr[1], ref remaining, ref out_offset).x; select_start_offset.y = searches_result_line_number[1] * fontsize; } + // TODO: commented textSize because its' never used // Calculate text height - if (is_multiline) - text_size = new Vector2(size.x, line_count * fontsize); + // if (isMultiline) + // textSize = new Vector2(size.x, line_count * fontsize); } // Scroll @@ -236,10 +239,10 @@ internal static bool OnProcess(WidgetStyle style, Interactable interact, ref str if ((Flags & InputFieldFlags.NoHorizontalScroll) == 0) { double scroll_increment_x = size.x * 0.25f; - if (cursor_offset.x < stb.ScrollX) - stb.ScrollX = (int)MathD.Max(0.0f, cursor_offset.x - scroll_increment_x); - else if (cursor_offset.x - size.x >= stb.ScrollX) - stb.ScrollX = (int)(cursor_offset.x - size.x + scroll_increment_x); + if (cursorOffset.x < stb.ScrollX) + stb.ScrollX = (int)MathD.Max(0.0f, cursorOffset.x - scroll_increment_x); + else if (cursorOffset.x - size.x >= stb.ScrollX) + stb.ScrollX = (int)(cursorOffset.x - size.x + scroll_increment_x); } else { @@ -247,71 +250,71 @@ internal static bool OnProcess(WidgetStyle style, Interactable interact, ref str } // Vertical scroll - if (is_multiline) + if (isMultiline) { double scroll_y = g.CurrentNode.VScroll; - if (cursor_offset.y - fontsize < scroll_y) - scroll_y = MathD.Max(0.0f, cursor_offset.y - fontsize); - else if (cursor_offset.y - size.y >= scroll_y) - scroll_y = cursor_offset.y - size.y; + if (cursorOffset.y - fontsize < scroll_y) + scroll_y = MathD.Max(0.0f, cursorOffset.y - fontsize); + else if (cursorOffset.y - size.y >= scroll_y) + scroll_y = cursorOffset.y - size.y; g.SetNodeStorage("VScroll", scroll_y); } } stb.CursorFollow = false; - if (is_multiline) - render_pos.y -= g.CurrentNode.VScroll; + if (isMultiline) + renderPos.y -= g.CurrentNode.VScroll; Vector2 render_scroll = new Vector2(stb.ScrollX, 0.0f); if ((Flags & InputFieldFlags.OnlyDisplay) == InputFieldFlags.OnlyDisplay) { Color32 colb = style.TextColor; - g.Draw2D.DrawList.AddText(font, fontsize, render_pos - render_scroll, colb, stb.Text, 0, stb.Text.Length, 0.0f, (is_multiline ? null : (Vector4?)clip_rect)); + g.Draw2D.DrawList.AddText(font, fontsize, renderPos - render_scroll, colb, stb.Text, 0, stb.Text.Length, 0.0f, (isMultiline ? null : (Vector4?)clipRect)); return false; } // Draw selection if (stb.SelectStart != stb.SelectEnd) { - int text_selected_begin = text_begin + MathD.Min(stb.SelectStart, stb.SelectEnd); - int text_selected_end = text_begin + MathD.Max(stb.SelectStart, stb.SelectEnd); + int text_selected_begin = textBegin + MathD.Min(stb.SelectStart, stb.SelectEnd); + int text_selected_end = textBegin + MathD.Max(stb.SelectStart, stb.SelectEnd); - float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. - float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + float bg_offy_up = isMultiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + float bg_offy_dn = isMultiline ? 0.0f : 2.0f; Color32 bg_color = style.ActiveColor; - Vector2 rect_pos = render_pos + select_start_offset - render_scroll; + Vector2 rect_pos = renderPos + select_start_offset - render_scroll; for (int p = text_selected_begin; p < text_selected_end;) { - if (rect_pos.y > clip_rect.y + clip_rect.height + fontsize) + if (rect_pos.y > clipRect.y + clipRect.height + fontsize) break; - if (rect_pos.y < clip_rect.y) + if (rect_pos.y < clipRect.y) { while (p < text_selected_end) - if (Text[p++] == '\n') //TODO: what should we access here? + if (text[p++] == '\n') //TODO: what should we access here? break; } else { var temp = (int?)p; Vector2? out_offset = null; - Vector2 rect_size = font.InputTextCalcTextSizeW(Text, p, text_selected_end, ref temp, ref out_offset, true); p = temp!.Value; + Vector2 rect_size = font.InputTextCalcTextSizeW(text, p, text_selected_end, ref temp, ref out_offset, true); p = temp!.Value; if (rect_size.x <= 0.0f) rect_size.x = (int)(font.GetCharAdvance(' ') * 0.50f); // So we can see selected empty lines Rect rect = new Rect(rect_pos + new Vector2(0.0f, bg_offy_up - fontsize), new Vector2(rect_size.x, bg_offy_dn + fontsize)); - rect.Clip(clip_rect); - if (rect.Overlaps(clip_rect)) + rect.Clip(clipRect); + if (rect.Overlaps(clipRect)) g.Draw2D.DrawList.AddRectFilled(rect.Min, rect.Max, bg_color); } - rect_pos.x = render_pos.x - render_scroll.x; + rect_pos.x = renderPos.x - render_scroll.x; rect_pos.y += fontsize; } } Color32 col = style.TextColor; - g.Draw2D.DrawList.AddText(font, fontsize, render_pos - render_scroll, col, stb.Text, 0, stb.Text.Length, 0.0f, (is_multiline ? null : (Vector4?)clip_rect)); + g.Draw2D.DrawList.AddText(font, fontsize, renderPos - render_scroll, col, stb.Text, 0, stb.Text.Length, 0.0f, (isMultiline ? null : (Vector4?)clipRect)); //g.DrawText(font, fontsize, Text, render_pos - render_scroll, Color.black, 0, stb.CurLenA, 0.0f, (is_multiline ? null : (ImVec4?)clip_rect)); // Draw blinking cursor - Vector2 cursor_screen_pos = render_pos + cursor_offset - render_scroll; + Vector2 cursor_screen_pos = renderPos + cursorOffset - render_scroll; bool cursor_is_visible = (stb.cursorAnim <= 0.0f) || (stb.cursorAnim % 1.20f) <= 0.80f; if (cursor_is_visible) g.Draw2D.DrawList.AddLine(cursor_screen_pos + new Vector2(0.0f, -fontsize - 4f), cursor_screen_pos + new Vector2(0.0f, -5f), col); @@ -319,7 +322,7 @@ internal static bool OnProcess(WidgetStyle style, Interactable interact, ref str if ((Flags & InputFieldFlags.EnterReturnsTrue) == InputFieldFlags.EnterReturnsTrue) { - Text = stb.Text; + text = stb.Text; if (g.IsKeyPressed(Key.Return)) { g.FocusID = 0; @@ -329,12 +332,12 @@ internal static bool OnProcess(WidgetStyle style, Interactable interact, ref str } else { - if (!is_multiline && g.IsKeyPressed(Key.Return)) + if (!isMultiline && g.IsKeyPressed(Key.Return)) g.FocusID = 0; - var oldText = Text; - Text = stb.Text; - return oldText != Text; + var oldText = text; + text = stb.Text; + return oldText != text; } } diff --git a/Prowl.Runtime/GameObject/MonoBehaviour.cs b/Prowl.Runtime/GameObject/MonoBehaviour.cs index bef2d9ab7..13623ddb0 100644 --- a/Prowl.Runtime/GameObject/MonoBehaviour.cs +++ b/Prowl.Runtime/GameObject/MonoBehaviour.cs @@ -65,7 +65,7 @@ public MonoBehaviour() : base() { } public void RemoveSelf() => GameObject.RemoveComponent(this); public T? GetComponent() where T : MonoBehaviour => GameObject.GetComponent(); public MonoBehaviour? GetComponent(Type type) => GameObject.GetComponent(type); - public bool TryGetComponent(out T component) where T : MonoBehaviour => (component = GetComponent()) != null; + public bool TryGetComponent(out T? component) where T : MonoBehaviour => (component = GetComponent()) != null; public IEnumerable GetComponents() where T : MonoBehaviour => GameObject.GetComponents(); public IEnumerable GetComponents(Type type) => GameObject.GetComponents(type); public T? GetComponentInParent(bool includeSelf = true) where T : MonoBehaviour => GameObject.GetComponentInParent(includeSelf); diff --git a/Prowl.Runtime/Utils/MultiValueDictionary.cs b/Prowl.Runtime/Utils/MultiValueDictionary.cs index 0fffc4642..94eeb1dfb 100644 --- a/Prowl.Runtime/Utils/MultiValueDictionary.cs +++ b/Prowl.Runtime/Utils/MultiValueDictionary.cs @@ -148,7 +148,7 @@ public MultiValueDictionary(IEnumerable - /// Creates a new new instance of the + /// Creates a new instance of the /// class that is empty, has the default initial capacity, and uses the default /// for . The /// internal dictionary will use instances of the @@ -180,7 +180,7 @@ public static MultiValueDictionary Create() } /// - /// Creates a new new instance of the + /// Creates a new instance of the /// class that is empty, has the specified initial capacity, and uses the default /// for . The /// internal dictionary will use instances of the @@ -216,7 +216,7 @@ public static MultiValueDictionary Create(int ca } /// - /// Creates a new new instance of the + /// Creates a new instance of the /// class that is empty, has the default initial capacity, and uses the specified /// for . The /// internal dictionary will use instances of the @@ -250,7 +250,7 @@ public static MultiValueDictionary Create(IEqual } /// - /// Creates a new new instance of the + /// Creates a new instance of the /// class that is empty, has the specified initial capacity, and uses the specified /// for . The /// internal dictionary will use instances of the @@ -375,7 +375,7 @@ public static MultiValueDictionary Create(IEnume ======================================================================*/ /// - /// Creates a new new instance of the + /// Creates a new instance of the /// class that is empty, has the default initial capacity, and uses the default /// for . The /// internal dictionary will use instances of the @@ -409,7 +409,7 @@ public static MultiValueDictionary Create(Func - /// Creates a new new instance of the + /// Creates a new instance of the /// class that is empty, has the specified initial capacity, and uses the default /// for . The /// internal dictionary will use instances of the @@ -447,7 +447,7 @@ public static MultiValueDictionary Create(int ca } /// - /// Creates a new new instance of the + /// Creates a new instance of the /// class that is empty, has the default initial capacity, and uses the specified /// for . The /// internal dictionary will use instances of the @@ -483,7 +483,7 @@ public static MultiValueDictionary Create(IEqual } /// - /// Creates a new new instance of the + /// Creates a new instance of the /// class that is empty, has the specified initial capacity, and uses the specified /// for . The /// internal dictionary will use instances of the @@ -816,7 +816,7 @@ public bool TryGetValue(TKey key, out IReadOnlyCollection value) throw new ArgumentNullException(nameof(key)); var success = _dictionary.TryGetValue(key, out InnerCollectionView collection); - value = collection; + value = collection is null ? new List() : collection; return success; } From 65d1ffb5b196c51c3ec6b675d97dc8a9a8d61f52 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 16:03:44 -0500 Subject: [PATCH 23/31] fix: CS8605 checking possible null on casting --- Prowl.Editor/Editor/EditorGUI.cs | 6 ++-- .../Drawers/Bool_PropertyDrawer.cs | 2 +- .../Drawers/Color_PropertyDrawer.cs | 2 +- .../Drawers/Double_PropertyDrawer.cs | 4 +-- .../Drawers/Float_PropertyDrawer.cs | 2 +- .../Drawers/Vector2_PropertyDrawer.cs | 2 +- .../Drawers/Vector3_PropertyDrawer.cs | 2 +- .../Drawers/Vector4_PropertyDrawer.cs | 2 +- Prowl.Runtime/Components/UI/GUICanvas.cs | 6 ++-- Prowl.Runtime/GUI/Gui.State.cs | 14 ++++---- Prowl.Runtime/GameObject/GameObject.cs | 6 ++-- .../RenderPipeline/DefaultRenderPipeline.cs | 14 +++++--- Prowl.Runtime/Resources/AnimationClip.cs | 32 ++++++++++--------- .../Serializer/SerializedProperty.cs | 2 +- Prowl.Runtime/Utils/NodeSystem/Node.cs | 2 +- Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs | 2 +- .../Utils/NodeSystem/Nodes/ReflectedNode.cs | 2 +- 17 files changed, 55 insertions(+), 47 deletions(-) diff --git a/Prowl.Editor/Editor/EditorGUI.cs b/Prowl.Editor/Editor/EditorGUI.cs index 94a8b2cc0..ffadbbf38 100644 --- a/Prowl.Editor/Editor/EditorGUI.cs +++ b/Prowl.Editor/Editor/EditorGUI.cs @@ -357,7 +357,7 @@ static bool HandleBeginGUIAttributes(string id, object target, IEnumerable EditorStylePrefs.Instance.ItemSize * 2; public override bool OnValueGUI(Gui gui, string ID, Type targetType, ref object? value) { - double val = (double)value; + double val = value is double v ? v : double.NaN; bool changed = EditorGUI.InputDouble(ID + "Val", ref val, 0, 0, Size.Percentage(1f), EditorGUI.InputFieldStyle); value = val; return changed; } -} \ No newline at end of file +} diff --git a/Prowl.Editor/Editor/PropertyDrawer/Drawers/Float_PropertyDrawer.cs b/Prowl.Editor/Editor/PropertyDrawer/Drawers/Float_PropertyDrawer.cs index 367cc4e3b..d1ef8579c 100644 --- a/Prowl.Editor/Editor/PropertyDrawer/Drawers/Float_PropertyDrawer.cs +++ b/Prowl.Editor/Editor/PropertyDrawer/Drawers/Float_PropertyDrawer.cs @@ -13,7 +13,7 @@ public class Float_PropertyDrawer : PropertyDrawer public override bool OnValueGUI(Gui gui, string ID, Type targetType, ref object? value) { - float val = (float)value; + float val = value is float v ? v : Convert.ToSingle(value); bool changed = EditorGUI.InputFloat(ID + "Val", ref val, 0, 0, Size.Percentage(1f), EditorGUI.InputFieldStyle); value = val; return changed; diff --git a/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector2_PropertyDrawer.cs b/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector2_PropertyDrawer.cs index 5c9fb0f92..ac520f071 100644 --- a/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector2_PropertyDrawer.cs +++ b/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector2_PropertyDrawer.cs @@ -15,7 +15,7 @@ public override bool OnValueGUI(Gui gui, string ID, Type targetType, ref object? { gui.CurrentNode.Layout(LayoutType.Row).ScaleChildren(); - Vector2 val = (Vector2)value; + Vector2 val = value is Vector2 v ? v : throw new Exception(); bool changed = EditorGUI.InputDouble(ID + "X", ref val.x, 0, 0, 0, EditorGUI.VectorXStyle); changed |= EditorGUI.InputDouble(ID + "Y", ref val.y, 0, 0, 0, EditorGUI.VectorYStyle); value = val; diff --git a/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector3_PropertyDrawer.cs b/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector3_PropertyDrawer.cs index 678e24b56..81cb7d677 100644 --- a/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector3_PropertyDrawer.cs +++ b/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector3_PropertyDrawer.cs @@ -15,7 +15,7 @@ public override bool OnValueGUI(Gui gui, string ID, Type targetType, ref object? { gui.CurrentNode.Layout(LayoutType.Row).ScaleChildren(); - Vector3 val = (Vector3)value; + Vector3 val = value is Vector3 v ? v : throw new Exception(); bool changed = EditorGUI.InputDouble(ID + "X", ref val.x, 0, 0, 0, EditorGUI.VectorXStyle); changed |= EditorGUI.InputDouble(ID + "Y", ref val.y, 0, 0, 0, EditorGUI.VectorYStyle); changed |= EditorGUI.InputDouble(ID + "Z", ref val.z, 0, 0, 0, EditorGUI.VectorZStyle); diff --git a/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector4_PropertyDrawer.cs b/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector4_PropertyDrawer.cs index 72091e902..cf4cf33f0 100644 --- a/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector4_PropertyDrawer.cs +++ b/Prowl.Editor/Editor/PropertyDrawer/Drawers/Vector4_PropertyDrawer.cs @@ -14,7 +14,7 @@ public override bool OnValueGUI(Gui gui, string ID, Type targetType, ref object? { gui.CurrentNode.Layout(LayoutType.Row).ScaleChildren(); - Vector4 val = (Vector4)value; + Vector4 val = value is Vector4 v ? v : throw new Exception(); bool changed = EditorGUI.InputDouble(ID + "X", ref val.x, 0, 0, 0, EditorGUI.VectorXStyle); changed |= EditorGUI.InputDouble(ID + "Y", ref val.y, 0, 0, 0, EditorGUI.VectorYStyle); changed |= EditorGUI.InputDouble(ID + "Z", ref val.z, 0, 0, 0, EditorGUI.VectorZStyle); diff --git a/Prowl.Runtime/Components/UI/GUICanvas.cs b/Prowl.Runtime/Components/UI/GUICanvas.cs index 871ee70ed..d998a3105 100644 --- a/Prowl.Runtime/Components/UI/GUICanvas.cs +++ b/Prowl.Runtime/Components/UI/GUICanvas.cs @@ -22,13 +22,15 @@ public enum Space { Screen } public override void Awake() { - TargetCamera = GetComponent(); - if (TargetCamera == null) + var targetCamera = GetComponent(); + if (targetCamera == null) { Debug.LogError("Target Camera is not set on GUICanvas."); return; } + TargetCamera = targetCamera; + gui = new Gui(DoAntiAliasing); //if (space == Space.Screen) diff --git a/Prowl.Runtime/GUI/Gui.State.cs b/Prowl.Runtime/GUI/Gui.State.cs index 309f3b9b2..d79967377 100644 --- a/Prowl.Runtime/GUI/Gui.State.cs +++ b/Prowl.Runtime/GUI/Gui.State.cs @@ -12,7 +12,7 @@ public partial class Gui { public int CurrentZIndex => CurrentNode.ZIndex; - private static readonly Dictionary _storage = []; + private static readonly Dictionary s_storage = []; /// /// Set the ZIndex for the current node @@ -37,11 +37,11 @@ public void SetZIndex(int index, bool keepClipSpace = false) /// Get a value from the current node's storage public T GetNodeStorage(LayoutNode node, string key, T defaultValue = default) where T : unmanaged { - if (!_storage.TryGetValue(node.ID, out var storage)) + if (!s_storage.TryGetValue(node.ID, out var storage)) return defaultValue; - if (storage.ContainsKey(key)) - return (T)storage[key]; + if (storage.ContainsKey(key) && storage[key] is T value) + return value; return defaultValue; } @@ -51,8 +51,8 @@ public T GetNodeStorage(LayoutNode node, string key, T defaultValue = default /// Set a value in the current node's storage public void SetNodeStorage(LayoutNode node, string key, T value) where T : unmanaged { - if (!_storage.TryGetValue(node.ID, out var storage)) - _storage[node.ID] = storage = []; + if (!s_storage.TryGetValue(node.ID, out var storage)) + s_storage[node.ID] = storage = []; storage[key] = value; } @@ -60,7 +60,7 @@ public void SetNodeStorage(LayoutNode node, string key, T value) where T : un /// /// Push an ID onto the ID stack. /// Useful for when you want to use the same string ID for multiple nodes that would otherwise conflict. - /// Or maybe you dont have control like a List of User-Created Nodes, you PushID(Index) and PopID() when done + /// Or maybe you don't have control like a List of User-Created Nodes, you PushID(Index) and PopID() when done /// /// public void PushID(ulong id) => IDStack.Push(id); diff --git a/Prowl.Runtime/GameObject/GameObject.cs b/Prowl.Runtime/GameObject/GameObject.cs index 67c348c07..0b6fa90ed 100644 --- a/Prowl.Runtime/GameObject/GameObject.cs +++ b/Prowl.Runtime/GameObject/GameObject.cs @@ -662,7 +662,7 @@ public void Deserialize(SerializedProperty value, Serializer.SerializationContex layerIndex = value["LayerIndex"].ByteValue; hideFlags = (HideFlags)value["HideFlags"].IntValue; - _transform = Serializer.Deserialize(value["Transform"], ctx); + _transform = Serializer.Deserialize(value["Transform"], ctx) ?? new Transform(); _transform.gameObject = this; if (value.TryGet("AssetID", out var guid)) @@ -670,9 +670,9 @@ public void Deserialize(SerializedProperty value, Serializer.SerializationContex if (value.TryGet("FileID", out var fileID)) FileID = fileID.UShortValue; - var children = value["Children"]; + var children2 = value["Children"]; this.children = new(); - foreach (var childTag in children.List) + foreach (var childTag in children2.List) { GameObject? child = Serializer.Deserialize(childTag, ctx); if (child == null) continue; diff --git a/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs b/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs index 0ed6e16a3..cf2858c63 100644 --- a/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs +++ b/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs @@ -25,6 +25,7 @@ public class DefaultRenderPipeline : RenderPipeline private static void ValidateDefaults() { + // TODO: FIXME: these values are never null s_quadMesh ??= Mesh.CreateQuad(Vector2.one); s_gridMaterial ??= new Material(Application.AssetProvider.LoadAsset("Defaults/Grid.shader")); s_defaultMaterial ??= new Material(Application.AssetProvider.LoadAsset("Defaults/DefaultUnlit.shader")); @@ -33,16 +34,19 @@ private static void ValidateDefaults() s_whiteTexture ??= Texture2D.EmptyWhite; - if (s_skyDome == null) - { - GameObject skyDomeModel = Application.AssetProvider.LoadAsset("Defaults/SkyDome.obj").Res; - MeshRenderer renderer = skyDomeModel.GetComponentInChildren(true, true); + // TODO: FIXME: s_skyDome is never null + // if (s_skyDome == null) + // { + GameObject skyDomeModel = Application.AssetProvider.LoadAsset("Defaults/SkyDome.obj").Res; + MeshRenderer renderer = skyDomeModel.GetComponentInChildren(true, true); + if (renderer.Mesh.Res is not null) + { s_skyDome = renderer.Mesh.Res; } + // } } - public override void Render(Framebuffer target, Camera camera, in RenderingData data) { ValidateDefaults(); diff --git a/Prowl.Runtime/Resources/AnimationClip.cs b/Prowl.Runtime/Resources/AnimationClip.cs index a1186f4ac..5b89881d5 100644 --- a/Prowl.Runtime/Resources/AnimationClip.cs +++ b/Prowl.Runtime/Resources/AnimationClip.cs @@ -94,21 +94,23 @@ public void Deserialize(SerializedProperty value, Serializer.SerializationContex var boneList = value.Get("Bones"); foreach (var boneProp in boneList.List) { - var bone = new AnimBone(); - bone.BoneName = boneProp.Get("BoneName").StringValue; - - bone.PosX = Serializer.Deserialize(boneProp.Get("PosX"), ctx); - bone.PosY = Serializer.Deserialize(boneProp.Get("PosY"), ctx); - bone.PosZ = Serializer.Deserialize(boneProp.Get("PosZ"), ctx); - - bone.RotX = Serializer.Deserialize(boneProp.Get("RotX"), ctx); - bone.RotY = Serializer.Deserialize(boneProp.Get("RotY"), ctx); - bone.RotZ = Serializer.Deserialize(boneProp.Get("RotZ"), ctx); - bone.RotW = Serializer.Deserialize(boneProp.Get("RotW"), ctx); - - bone.ScaleX = Serializer.Deserialize(boneProp.Get("ScaleX"), ctx); - bone.ScaleY = Serializer.Deserialize(boneProp.Get("ScaleY"), ctx); - bone.ScaleZ = Serializer.Deserialize(boneProp.Get("ScaleZ"), ctx); + var bone = new AnimBone + { + BoneName = boneProp.Get("BoneName").StringValue, + + PosX = Serializer.Deserialize(boneProp.Get("PosX"), ctx) ?? new AnimationCurve(), + PosY = Serializer.Deserialize(boneProp.Get("PosY"), ctx) ?? new AnimationCurve(), + PosZ = Serializer.Deserialize(boneProp.Get("PosZ"), ctx) ?? new AnimationCurve(), + + RotX = Serializer.Deserialize(boneProp.Get("RotX"), ctx) ?? new AnimationCurve(), + RotY = Serializer.Deserialize(boneProp.Get("RotY"), ctx) ?? new AnimationCurve(), + RotZ = Serializer.Deserialize(boneProp.Get("RotZ"), ctx) ?? new AnimationCurve(), + RotW = Serializer.Deserialize(boneProp.Get("RotW"), ctx) ?? new AnimationCurve(), + + ScaleX = Serializer.Deserialize(boneProp.Get("ScaleX"), ctx) ?? new AnimationCurve(), + ScaleY = Serializer.Deserialize(boneProp.Get("ScaleY"), ctx) ?? new AnimationCurve(), + ScaleZ = Serializer.Deserialize(boneProp.Get("ScaleZ"), ctx) ?? new AnimationCurve() + }; Bones.Add(bone); } diff --git a/Prowl.Runtime/Serializer/SerializedProperty.cs b/Prowl.Runtime/Serializer/SerializedProperty.cs index 3d6c978b7..c420d5f13 100644 --- a/Prowl.Runtime/Serializer/SerializedProperty.cs +++ b/Prowl.Runtime/Serializer/SerializedProperty.cs @@ -199,7 +199,7 @@ public void Set(object value) /// Returns the value of this tag, cast as a bool. /// When used on a tag other than BoolTag. - public bool BoolValue { get => (bool)Value; set => Set(value); } + public bool BoolValue { get => (Value is not null && (bool)Value); set => Set(value); } /// Returns the value of this tag, cast as a byte. /// When used on a tag other than ByteTag. diff --git a/Prowl.Runtime/Utils/NodeSystem/Node.cs b/Prowl.Runtime/Utils/NodeSystem/Node.cs index ed8766a9b..0e88f7651 100644 --- a/Prowl.Runtime/Utils/NodeSystem/Node.cs +++ b/Prowl.Runtime/Utils/NodeSystem/Node.cs @@ -408,7 +408,7 @@ public bool ContainsKey(string key) public bool TryGetValue(string key, out NodePort value) { var result = dictionary.TryGetValue(key, out NodePort dictionaryValue); - value = dictionaryValue; + value = dictionaryValue ?? throw new KeyNotFoundException(); return result; } diff --git a/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs b/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs index c8749b2a8..ee97e3eaa 100644 --- a/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs +++ b/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs @@ -145,7 +145,7 @@ public virtual void Clear() public virtual NodeGraph Copy() { SerializedProperty graphTag = Serializer.Serialize(this); - NodeGraph graph = Serializer.Deserialize(graphTag); + NodeGraph graph = Serializer.Deserialize(graphTag) ?? throw new NullReferenceException(); // Instantiate all nodes inside the graph for (int i = 0; i < nodes.Count; i++) { diff --git a/Prowl.Runtime/Utils/NodeSystem/Nodes/ReflectedNode.cs b/Prowl.Runtime/Utils/NodeSystem/Nodes/ReflectedNode.cs index a91820ea5..7b7e9055a 100644 --- a/Prowl.Runtime/Utils/NodeSystem/Nodes/ReflectedNode.cs +++ b/Prowl.Runtime/Utils/NodeSystem/Nodes/ReflectedNode.cs @@ -47,7 +47,7 @@ public void SetMethod(MethodInfo method_info) cached_method = method_info; node_title = GetNodeName(method_info); - type_Name = method_info.ReflectedType.FullName; + type_Name = method_info.ReflectedType.FullName ?? throw new InvalidOperationException(); method_Name = method_info.Name; AddDynamicInput(typeof(FlowNode), ConnectionType.Override, TypeConstraint.Strict, "From", true); From 6e6f8fe1ed600c82eb4989e692a576b3b28c7946 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 16:06:45 -0500 Subject: [PATCH 24/31] fix: call Dispose() directly is obsolete. Using .Destroy() --- Prowl.Editor/Editor/GameWindow.cs | 2 +- Prowl.Editor/Editor/NodeEditor/NodeEditor.cs | 2 +- Prowl.Editor/Editor/SceneViewWindow.cs | 2 +- Prowl.Editor/Utilities/Texture2DLoader.cs | 2 +- Prowl.Runtime/EngineObject.cs | 4 ++-- Prowl.Runtime/GameObject/GameObject.cs | 4 ++-- Prowl.Runtime/Rendering/Texture/RenderTexture.cs | 2 +- Prowl.Runtime/Rendering/Texture/Texture.cs | 2 +- 8 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Prowl.Editor/Editor/GameWindow.cs b/Prowl.Editor/Editor/GameWindow.cs index 8b630aa13..1d68e0486 100644 --- a/Prowl.Editor/Editor/GameWindow.cs +++ b/Prowl.Editor/Editor/GameWindow.cs @@ -61,7 +61,7 @@ public GameWindow() : base() public void RefreshRenderTexture() { - RenderTarget?.Dispose(); + RenderTarget?.Destroy(); RenderTarget = new RenderTexture( (uint)GeneralPreferences.Instance.CurrentWidth, diff --git a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs index 286de3770..a72aaa593 100644 --- a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs +++ b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs @@ -613,7 +613,7 @@ public NodeEditor(NodeGraph graph) public void RefreshRenderTexture(Vector2 renderSize) { - RenderTarget?.Dispose(); + RenderTarget?.Destroy(); RenderTarget = new RenderTexture( (uint)renderSize.x, diff --git a/Prowl.Editor/Editor/SceneViewWindow.cs b/Prowl.Editor/Editor/SceneViewWindow.cs index 0b3211ea6..cd0249ba2 100644 --- a/Prowl.Editor/Editor/SceneViewWindow.cs +++ b/Prowl.Editor/Editor/SceneViewWindow.cs @@ -55,7 +55,7 @@ public SceneViewWindow() : base() public void RefreshRenderTexture(int width, int height) { - RenderTarget?.Dispose(); + RenderTarget?.Destroy(); RenderTarget = new RenderTexture( (uint)width, (uint)height, diff --git a/Prowl.Editor/Utilities/Texture2DLoader.cs b/Prowl.Editor/Utilities/Texture2DLoader.cs index 2e4737b60..644973227 100644 --- a/Prowl.Editor/Utilities/Texture2DLoader.cs +++ b/Prowl.Editor/Utilities/Texture2DLoader.cs @@ -88,7 +88,7 @@ public static Texture2D FromImage(Image image, bool generateMipm } catch { - texture.Dispose(); + texture.Destroy(); throw; } } diff --git a/Prowl.Runtime/EngineObject.cs b/Prowl.Runtime/EngineObject.cs index 1b66fe76c..a57a3c3ae 100644 --- a/Prowl.Runtime/EngineObject.cs +++ b/Prowl.Runtime/EngineObject.cs @@ -98,7 +98,7 @@ public static void DestroyImmediate(EngineObject obj) { if (obj.IsDestroyed) throw new Exception(obj.Name + " is already destroyed."); obj.IsDestroyed = true; - obj.Dispose(); + obj.Destroy(); } public static void HandleDestroyed() @@ -106,7 +106,7 @@ public static void HandleDestroyed() while (destroyed.TryPop(out var obj)) { if (!obj.IsDestroyed) continue; - obj.Dispose(); + obj.Destroy(); } CleanupAllObjects(); diff --git a/Prowl.Runtime/GameObject/GameObject.cs b/Prowl.Runtime/GameObject/GameObject.cs index 0b6fa90ed..d1410cfe3 100644 --- a/Prowl.Runtime/GameObject/GameObject.cs +++ b/Prowl.Runtime/GameObject/GameObject.cs @@ -560,13 +560,13 @@ public override void OnDispose() // Internal_DestroyCommitted removes the child from the parent // Hense why we do a while loop on the first element instead of a foreach/for while (children.Count > 0) - children[0].Dispose(); + children[0].Destroy(); foreach (var component in _components) { if (component.EnabledInHierarchy) component.Do(component.OnDisable); if (component.HasStarted) component.Do(component.OnDestroy); // OnDestroy is only called if the component has previously been active - component.Dispose(); + component.Destroy(); } _components.Clear(); _componentCache.Clear(); diff --git a/Prowl.Runtime/Rendering/Texture/RenderTexture.cs b/Prowl.Runtime/Rendering/Texture/RenderTexture.cs index 5920ca5d3..be0b7d4ba 100644 --- a/Prowl.Runtime/Rendering/Texture/RenderTexture.cs +++ b/Prowl.Runtime/Rendering/Texture/RenderTexture.cs @@ -220,7 +220,7 @@ public override void OnDispose() DepthBuffer?.Dispose(); if (ColorBuffers != null) - foreach (Texture2D tex in ColorBuffers) + foreach (var tex in ColorBuffers) tex?.Dispose(); Framebuffer?.Dispose(); diff --git a/Prowl.Runtime/Rendering/Texture/Texture.cs b/Prowl.Runtime/Rendering/Texture/Texture.cs index 21a022b81..2647ba1b3 100644 --- a/Prowl.Runtime/Rendering/Texture/Texture.cs +++ b/Prowl.Runtime/Rendering/Texture/Texture.cs @@ -83,7 +83,7 @@ public override void OnDispose() TextureView = null; stagingTexture = null; - Sampler?.Dispose(); + Sampler?.Destroy(); } public void GenerateMipmaps(bool waitForCompletion = false) From 8eb1d4826e40ac6a477a7d93ec111118e63115da Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 16:12:06 -0500 Subject: [PATCH 25/31] fix: CS8625 assigning null to non-nullable fields. most fixes are just settings them nullable --- Prowl.Editor/Assets/AssetDatabase.Utilities.cs | 2 +- Prowl.Editor/Assets/AssetDirectoryCache.cs | 6 +++--- Prowl.Editor/Editor/AssetsTreeWindow.cs | 2 +- Prowl.Editor/Editor/DragnDrop.cs | 2 +- Prowl.Editor/Editor/HierarchyWindow.cs | 2 +- Prowl.Editor/Editor/NodeEditor/NodeEditor.cs | 8 ++++---- Prowl.Editor/Editor/ScriptedEditors/GameObjectEditor.cs | 2 +- Prowl.Editor/EditorGuiManager.cs | 2 +- Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs | 2 +- 9 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Prowl.Editor/Assets/AssetDatabase.Utilities.cs b/Prowl.Editor/Assets/AssetDatabase.Utilities.cs index fe4e83a43..2850ce231 100644 --- a/Prowl.Editor/Assets/AssetDatabase.Utilities.cs +++ b/Prowl.Editor/Assets/AssetDatabase.Utilities.cs @@ -12,7 +12,7 @@ public static partial class AssetDatabase #region Public Methods - public static bool PathToCachedNode(string path, out AssetDirectoryCache.DirNode node) + public static bool PathToCachedNode(string path, out AssetDirectoryCache.DirNode? node) { node = null; foreach (var tuple in rootFolders) diff --git a/Prowl.Editor/Assets/AssetDirectoryCache.cs b/Prowl.Editor/Assets/AssetDirectoryCache.cs index f34ce24e0..84838d91a 100644 --- a/Prowl.Editor/Assets/AssetDirectoryCache.cs +++ b/Prowl.Editor/Assets/AssetDirectoryCache.cs @@ -5,10 +5,10 @@ namespace Prowl.Editor.Assets; public class AssetDirectoryCache(DirectoryInfo root) { - public class DirNode(DirectoryInfo directory, DirNode parent) + public class DirNode(DirectoryInfo directory, DirNode? parent) { public DirectoryInfo Directory = directory; - public DirNode Parent = parent; + public DirNode? Parent = parent; public List SubDirectories = []; public List Files = []; } @@ -90,7 +90,7 @@ public void Refresh() _rootNode = BuildDirectoryTree(_rootDir, null); } - private DirNode BuildDirectoryTree(DirectoryInfo directory, DirNode parent) + private DirNode BuildDirectoryTree(DirectoryInfo directory, DirNode? parent) { DirNode node = new(directory, parent); try diff --git a/Prowl.Editor/Editor/AssetsTreeWindow.cs b/Prowl.Editor/Editor/AssetsTreeWindow.cs index 407171ffc..5513a0b83 100644 --- a/Prowl.Editor/Editor/AssetsTreeWindow.cs +++ b/Prowl.Editor/Editor/AssetsTreeWindow.cs @@ -129,7 +129,7 @@ protected override void Draw() } } - public static void DrawContextMenu(FileSystemInfo? fileInfo, DirectoryInfo? directory = null, bool fromAssetBrowser = false, LayoutNode popupHolder = null) + public static void DrawContextMenu(FileSystemInfo? fileInfo, DirectoryInfo? directory = null, bool fromAssetBrowser = false, LayoutNode? popupHolder = null) { bool closePopup = false; diff --git a/Prowl.Editor/Editor/DragnDrop.cs b/Prowl.Editor/Editor/DragnDrop.cs index 6b64a3e9a..3bce1dc68 100644 --- a/Prowl.Editor/Editor/DragnDrop.cs +++ b/Prowl.Editor/Editor/DragnDrop.cs @@ -11,7 +11,7 @@ namespace Prowl.Editor; public static class DragnDrop { - private static object[] draggedObject; + private static object[]? draggedObject; private static string payloadTag = ""; diff --git a/Prowl.Editor/Editor/HierarchyWindow.cs b/Prowl.Editor/Editor/HierarchyWindow.cs index e70377593..ff96d7675 100644 --- a/Prowl.Editor/Editor/HierarchyWindow.cs +++ b/Prowl.Editor/Editor/HierarchyWindow.cs @@ -21,7 +21,7 @@ public class HierarchyWindow : EditorWindow private const float PingDuration = 3f; private static float pingTimer; - private static WeakReference pingedGO; + private static WeakReference? pingedGO; private bool justStartedRename; public HierarchyWindow() : base() diff --git a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs index a72aaa593..634319738 100644 --- a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs +++ b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs @@ -582,7 +582,7 @@ public class NodeEditor internal Rect dragSelection; private string _searchText = string.Empty; - private static NodeMenuItemInfo rootMenuItem; + private static NodeMenuItemInfo? rootMenuItem; private readonly SelectHandler SelectHandler = new((item) => !item.IsAlive, (a, b) => ReferenceEquals(a.Target, b.Target)); @@ -1234,12 +1234,12 @@ private class NodeMenuItemInfo { public string Name; public Type Type; - public readonly MethodInfo Method; + public readonly MethodInfo? Method; public readonly List Children = []; public NodeMenuItemInfo() { } - public NodeMenuItemInfo(Type type, MethodInfo method = null) + public NodeMenuItemInfo(Type type, MethodInfo? method = null) { Type = type; Method = method; @@ -1249,7 +1249,7 @@ public NodeMenuItemInfo(Type type, MethodInfo method = null) Name = addToMenuAttribute.catagory; } - public void AddChild(string path, Type type, MethodInfo method = null) + public void AddChild(string path, Type type, MethodInfo? method = null) { string[] parts = path.Split('/'); NodeMenuItemInfo currentNode = this; diff --git a/Prowl.Editor/Editor/ScriptedEditors/GameObjectEditor.cs b/Prowl.Editor/Editor/ScriptedEditors/GameObjectEditor.cs index 63284feb9..1feb782b4 100644 --- a/Prowl.Editor/Editor/ScriptedEditors/GameObjectEditor.cs +++ b/Prowl.Editor/Editor/ScriptedEditors/GameObjectEditor.cs @@ -24,7 +24,7 @@ namespace Prowl.Editor.EditorWindows.CustomEditors; public class GameObjectEditor : ScriptedEditor { private string _searchText = string.Empty; - private static MenuItemInfo rootMenuItem; + private static MenuItemInfo? rootMenuItem; private readonly Dictionary compEditors = new(); [OnAssemblyUnload] diff --git a/Prowl.Editor/EditorGuiManager.cs b/Prowl.Editor/EditorGuiManager.cs index 8547147e0..1516d3390 100644 --- a/Prowl.Editor/EditorGuiManager.cs +++ b/Prowl.Editor/EditorGuiManager.cs @@ -20,7 +20,7 @@ public static class EditorGuiManager public static Gui Gui; public static DockContainer Container; - public static EditorWindow DraggingWindow; + public static EditorWindow? DraggingWindow; public static DockNode? DragSplitter; private static Vector2 m_DragPos; private static double m_StartSplitPos; diff --git a/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs b/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs index c45e4b5fd..32710c355 100644 --- a/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs +++ b/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs @@ -55,7 +55,7 @@ public AssetRef LoadAsset(Guid guid, ushort fileID = 0) where T : EngineOb public AssetRef LoadAsset(IAssetRef? assetID) where T : EngineObject { - if (assetID == null) return null; + ArgumentNullException.ThrowIfNull(assetID); return LoadAsset(assetID.AssetID, assetID.FileID); } From e3024433d3b1d1032e2fe4de0a56b7a82766e1d1 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 19:30:44 -0500 Subject: [PATCH 26/31] fix: null checking --- Prowl.Editor/Assets/AssetDatabase.Core.cs | 22 ++++---- .../Assets/AssetDatabase.FileOperations.cs | 4 +- Prowl.Editor/Assets/ImporterAttribute.cs | 52 +++++++++---------- Prowl.Editor/EditorGuiManager.cs | 1 - .../Prowl.Desktop/StandaloneAssetProvider.cs | 14 ++--- 5 files changed, 47 insertions(+), 46 deletions(-) diff --git a/Prowl.Editor/Assets/AssetDatabase.Core.cs b/Prowl.Editor/Assets/AssetDatabase.Core.cs index 82ce36938..ef83566b5 100644 --- a/Prowl.Editor/Assets/AssetDatabase.Core.cs +++ b/Prowl.Editor/Assets/AssetDatabase.Core.cs @@ -140,7 +140,7 @@ public static void Update(bool doUnload = true, bool forceCacheUpdate = false) if (ProcessFile(file, out _)) toReimport.Add(file); } - else if (!assetPathToMeta.TryGetValue(file, out var meta)) + else if (!assetPathToMeta.TryGetValue(file, out _)) { // File hasent changed but we dont have it in the cache, process it but dont reimport Debug.Log("Asset Found: " + file); @@ -169,7 +169,7 @@ public static void Update(bool doUnload = true, bool forceCacheUpdate = false) cacheModified = true; bool hasMeta = assetPathToMeta.TryGetValue(file, out var meta); - if (hasMeta) + if (hasMeta && meta is not null) { assetPathToMeta.Remove(file); @@ -352,11 +352,12 @@ public static bool Reimport(FileInfo assetFile, bool disposeExisting = true) Debug.LogError($"No valid meta file found for asset: {ToRelativePath(assetFile)}"); return false; } - if (meta.Importer == null) - { - Debug.LogError($"No valid importer found for asset: {ToRelativePath(assetFile)}"); - return false; - } + // TODO: FIXME: its always not null + // if (meta.Importer == null) + // { + // Debug.LogError($"No valid importer found for asset: {ToRelativePath(assetFile)}"); + // return false; + // } // Import the asset SerializedAsset ctx = new(meta.guid); @@ -495,8 +496,11 @@ public static bool Reimport(FileInfo assetFile, bool disposeExisting = true) { var serializedAsset = SerializedAsset.FromSerializedAsset(serializedAssetPath.FullName); serializedAsset.Guid = assetGuid; - serializedAsset.Main.AssetID = assetGuid; - serializedAsset.Main.FileID = 0; + if (serializedAsset.Main is not null) + { + serializedAsset.Main.AssetID = assetGuid; + serializedAsset.Main.FileID = 0; + } for (int i = 0; i < serializedAsset.SubAssets.Count; i++) { serializedAsset.SubAssets[i].AssetID = assetGuid; diff --git a/Prowl.Editor/Assets/AssetDatabase.FileOperations.cs b/Prowl.Editor/Assets/AssetDatabase.FileOperations.cs index 744d77acf..63572a6c9 100644 --- a/Prowl.Editor/Assets/AssetDatabase.FileOperations.cs +++ b/Prowl.Editor/Assets/AssetDatabase.FileOperations.cs @@ -100,7 +100,7 @@ public static bool Rename(FileInfo file, string newName) /// /// Renames a folder. /// - /// The folder to rename. + /// The folder to rename. /// The new name of the folder. /// True if the folder was renamed successfully, false otherwise. public static bool Rename(DirectoryInfo source, string newName) @@ -143,7 +143,7 @@ public static bool Delete(FileInfo file) /// /// Deletes a folder. /// - /// The folder to delete. + /// The folder to delete. /// True if the folder was deleted successfully, false otherwise. public static bool Delete(DirectoryInfo source) { diff --git a/Prowl.Editor/Assets/ImporterAttribute.cs b/Prowl.Editor/Assets/ImporterAttribute.cs index 9139f2042..c88fda272 100644 --- a/Prowl.Editor/Assets/ImporterAttribute.cs +++ b/Prowl.Editor/Assets/ImporterAttribute.cs @@ -31,26 +31,25 @@ public static void GenerateLookUp() extToIcon.Clear(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) foreach (var type in assembly.GetTypes()) - if (type != null) + { + var attribute = type.GetCustomAttribute(); + if (attribute == null) continue; + + foreach (var extRW in attribute.Extensions) { - var attribute = type.GetCustomAttribute(); - if (attribute == null) continue; - - foreach (var extRW in attribute.Extensions) - { - var ext = extRW.ToLower(); - // Make sure the Extension is formatted correctly '.png' 1 dot at start - if (ext[0] != '.') ext = '.' + ext; - // Check if has more then 1 '.' - if (ext.Count(x => x == '.') > 1) throw new Exception($"Extension {ext} is formatted incorrectly on importer: {type.Name}"); - - if (extToImporter.TryGetValue(ext, out var oldType)) - Debug.LogError($"Asset Importer Overwritten. {ext} extension already in use by: {oldType.Name}, being overwritten by: {type.Name}"); - extToImporter[ext] = type; - extToIcon[ext] = attribute.FileIcon; - extToGeneralType[ext] = attribute.GeneralType; - } + var ext = extRW.ToLower(); + // Make sure the Extension is formatted correctly '.png' 1 dot at start + if (ext[0] != '.') ext = '.' + ext; + // Check if has more then 1 '.' + if (ext.Count(x => x == '.') > 1) throw new Exception($"Extension {ext} is formatted incorrectly on importer: {type.Name}"); + + if (extToImporter.TryGetValue(ext, out var oldType)) + Debug.LogError($"Asset Importer Overwritten. {ext} extension already in use by: {oldType.Name}, being overwritten by: {type.Name}"); + extToImporter[ext] = type; + extToIcon[ext] = attribute.FileIcon; + extToGeneralType[ext] = attribute.GeneralType; } + } } [OnAssemblyUnload] @@ -104,15 +103,14 @@ public static void GenerateLookUp() { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) foreach (var type in assembly.GetTypes()) - if (type != null) - { - var attribute = type.GetCustomAttribute(); - if (attribute == null) continue; - - if (typeToEditor.TryGetValue(attribute.Type, out var oldType)) - Debug.LogError($"Custom Editor Overwritten. {attribute.Type.Name} already has a custom Editor: {oldType.Name}, being overwritten by: {type.Name}"); - typeToEditor[attribute.Type] = type; - } + { + var attribute = type.GetCustomAttribute(); + if (attribute == null) continue; + + if (typeToEditor.TryGetValue(attribute.Type, out var oldType)) + Debug.LogError($"Custom Editor Overwritten. {attribute.Type.Name} already has a custom Editor: {oldType.Name}, being overwritten by: {type.Name}"); + typeToEditor[attribute.Type] = type; + } } [OnAssemblyUnload] diff --git a/Prowl.Editor/EditorGuiManager.cs b/Prowl.Editor/EditorGuiManager.cs index 1516d3390..e86048c0f 100644 --- a/Prowl.Editor/EditorGuiManager.cs +++ b/Prowl.Editor/EditorGuiManager.cs @@ -84,7 +84,6 @@ public static void Update() Veldrid.CommandList commandList = Graphics.GetCommandList(); commandList.Name = "GUI Command Buffer"; - commandList.SetFramebuffer(Graphics.ScreenTarget); commandList.ClearColorTarget(0, Veldrid.RgbaFloat.Black); commandList.ClearDepthStencil(1.0f, 0); diff --git a/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs b/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs index 32710c355..9352879ed 100644 --- a/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs +++ b/Prowl.Players/Prowl.Desktop/StandaloneAssetProvider.cs @@ -27,28 +27,28 @@ public StandaloneAssetProvider() public AssetRef LoadAsset(string relativeAssetPath, ushort fileID = 0) where T : EngineObject { Guid guid = GetGuidFromPath(relativeAssetPath); - if (_loaded.ContainsKey(guid)) - return (T)(fileID == 0 ? _loaded[guid].Main : _loaded[guid].SubAssets[fileID - 1]); + if (_loaded.TryGetValue(guid, out SerializedAsset? value)) + return (T)(fileID == 0 ? value.Main : value.SubAssets[fileID - 1])!; foreach (AssetBundle package in packages) if (package.TryGetAsset(relativeAssetPath, out var asset) && asset is not null) { _loaded[guid] = asset; - return (T)(fileID == 0 ? asset.Main : asset.SubAssets[fileID - 1]); + return (T)(fileID == 0 ? asset.Main : asset.SubAssets[fileID - 1])!; } throw new FileNotFoundException($"Asset with path {relativeAssetPath} not found."); } public AssetRef LoadAsset(Guid guid, ushort fileID = 0) where T : EngineObject { - if (_loaded.ContainsKey(guid)) - return (T)(fileID == 0 ? _loaded[guid].Main : _loaded[guid].SubAssets[fileID - 1]); + if (_loaded.TryGetValue(guid, out SerializedAsset? value)) + return (T)(fileID == 0 ? value.Main : value.SubAssets[fileID - 1])!; foreach (AssetBundle package in packages) if (package.TryGetAsset(guid, out var asset) && asset is not null) { _loaded[guid] = asset; - return (T)(fileID == 0 ? asset.Main : asset.SubAssets[fileID - 1]); + return (T)(fileID == 0 ? asset.Main : asset.SubAssets[fileID - 1])!; } throw new FileNotFoundException($"Asset with GUID {guid} not found."); } @@ -59,7 +59,7 @@ public AssetRef LoadAsset(IAssetRef? assetID) where T : EngineObject return LoadAsset(assetID.AssetID, assetID.FileID); } - public SerializedAsset? LoadAsset(Guid guid) + public SerializedAsset LoadAsset(Guid guid) { if (_loaded.TryGetValue(guid, out SerializedAsset? loadAsset)) return loadAsset; From aca944c8f34b0c09778ba24912a004915e9c063b Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 19:31:59 -0500 Subject: [PATCH 27/31] refactor: readonly on several fields/properties that are never reassigned (typical for collections) --- Prowl.Editor/Assets/AssetDatabase.Packages.cs | 4 +-- Prowl.Editor/Assets/AssetDirectoryCache.cs | 12 +++---- Prowl.Editor/Assets/ImporterAttribute.cs | 8 ++--- Prowl.Editor/Assets/Importers/FontImporter.cs | 2 +- .../Assets/Importers/TextureImporter.cs | 2 +- Prowl.Editor/Build/Desktop_Player.cs | 6 ++-- Prowl.Editor/Editor/Docking/DockContainer.cs | 2 +- Prowl.Editor/Editor/NodeEditor/NodeEditor.cs | 4 +-- .../Preferences/AssetPipelinePreferences.cs | 4 +-- .../Editor/Preferences/GeneralPreferences.cs | 32 ++++++++--------- .../Preferences/PackageManagerPreferences.cs | 8 ++--- .../Preferences/SceneViewPreferences.cs | 24 ++++++------- Prowl.Editor/Editor/Widgets/FileDialog.cs | 2 +- Prowl.Editor/EditorGuiManager.cs | 2 +- Prowl.Editor/Project.cs | 20 +++++------ .../Utilities/ShaderCompiler/FileIncluder.cs | 2 +- .../Utilities/ShaderCompiler/ShaderParser.cs | 4 +-- Prowl.Runtime/Components/Animation.cs | 16 ++++----- Prowl.Runtime/Components/Audio/AudioSource.cs | 8 ++--- Prowl.Runtime/Components/Camera.cs | 6 ++-- .../Components/Navmesh/NavMeshAgent.cs | 16 ++++----- .../Components/Navmesh/NavMeshSurface.cs | 36 +++++++++---------- .../Components/Physics/CharacterController.cs | 12 +++---- Prowl.Runtime/Components/UI/GUICanvas.cs | 2 +- Prowl.Runtime/EngineObject.cs | 2 +- Prowl.Runtime/GUI/Graphics/UIDrawList.cs | 4 +-- Prowl.Runtime/GUI/Gui.Core.cs | 8 ++--- Prowl.Runtime/GUI/Gui.Input.cs | 18 +++++----- Prowl.Runtime/GUI/Gui.Interaction.cs | 2 +- Prowl.Runtime/GUI/GuiDraw2D.cs | 2 +- Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs | 6 ++-- Prowl.Runtime/GUI/Layout/Offset.cs | 4 +-- Prowl.Runtime/GUI/Layout/Size.cs | 6 ++-- Prowl.Runtime/GUI/Layout/Spacing.cs | 8 ++--- Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs | 6 ++-- .../GUI/Widgets/Gizmo/TransformGizmo.cs | 6 ++-- Prowl.Runtime/GUI/Widgets/Gui.InputField.cs | 4 +-- .../Attributes/InspectorUIAttribute.cs | 10 +++--- Prowl.Runtime/GameObject/TagLayerManager.cs | 4 +-- Prowl.Runtime/Physics.cs | 12 +++---- Prowl.Runtime/Rendering/CommandBuffer.cs | 2 +- Prowl.Runtime/Rendering/Material.cs | 4 +-- Prowl.Runtime/Rendering/PropertyState.cs | 6 ++-- .../RenderPipeline/DefaultRenderPipeline.cs | 2 +- .../Rendering/Shader/ShaderUniform.cs | 4 +-- .../Rendering/Texture/RenderTexture.cs | 12 +++---- Prowl.Runtime/Rendering/Texture/Texture.cs | 2 +- Prowl.Runtime/Rendering/Texture/Texture2D.cs | 6 ++-- Prowl.Runtime/SceneManager.cs | 2 +- Prowl.Runtime/Serializer/Serializer.cs | 6 ++-- Prowl.Runtime/Utils/NodeSystem/Node.cs | 24 ++++++------- Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs | 6 ++-- .../Nodes/Flow Control/ForLoopNode.cs | 4 +-- .../Nodes/Operations/String Nodes.cs | 8 ++--- .../NodeSystem/PortTypeOverrideAttribute.cs | 2 +- Prowl.Runtime/Utils/SerializedAsset.cs | 2 +- Prowl.Runtime/Utils/Tokenizer.cs | 4 +-- 57 files changed, 216 insertions(+), 216 deletions(-) diff --git a/Prowl.Editor/Assets/AssetDatabase.Packages.cs b/Prowl.Editor/Assets/AssetDatabase.Packages.cs index 234616a33..72f3169e3 100644 --- a/Prowl.Editor/Assets/AssetDatabase.Packages.cs +++ b/Prowl.Editor/Assets/AssetDatabase.Packages.cs @@ -28,9 +28,9 @@ public static partial class AssetDatabase /// Key: Package ID /// Value: Package Version /// - public static Dictionary DesiredPackages = []; + public static readonly Dictionary DesiredPackages = []; - public static List Packages = []; + public static readonly List Packages = []; #region Public Methods diff --git a/Prowl.Editor/Assets/AssetDirectoryCache.cs b/Prowl.Editor/Assets/AssetDirectoryCache.cs index 84838d91a..63054b146 100644 --- a/Prowl.Editor/Assets/AssetDirectoryCache.cs +++ b/Prowl.Editor/Assets/AssetDirectoryCache.cs @@ -7,17 +7,17 @@ public class AssetDirectoryCache(DirectoryInfo root) { public class DirNode(DirectoryInfo directory, DirNode? parent) { - public DirectoryInfo Directory = directory; - public DirNode? Parent = parent; - public List SubDirectories = []; - public List Files = []; + public readonly DirectoryInfo Directory = directory; + public readonly DirNode? Parent = parent; + public readonly List SubDirectories = []; + public readonly List Files = []; } public class FileNode { - public FileInfo File; + public readonly FileInfo File; public Guid AssetID; - public AssetDatabase.SubAssetCache[] SubAssets; + public readonly AssetDatabase.SubAssetCache[] SubAssets; public FileNode(FileInfo file) { diff --git a/Prowl.Editor/Assets/ImporterAttribute.cs b/Prowl.Editor/Assets/ImporterAttribute.cs index c88fda272..2dfb8241e 100644 --- a/Prowl.Editor/Assets/ImporterAttribute.cs +++ b/Prowl.Editor/Assets/ImporterAttribute.cs @@ -20,9 +20,9 @@ public ImporterAttribute(string fileIcon, Type generalType, params string[] exte GeneralType = generalType; } - public static Dictionary extToGeneralType = new(StringComparer.OrdinalIgnoreCase); - public static Dictionary extToImporter = new(StringComparer.OrdinalIgnoreCase); - public static Dictionary extToIcon = new(StringComparer.OrdinalIgnoreCase); + public static readonly Dictionary extToGeneralType = new(StringComparer.OrdinalIgnoreCase); + public static readonly Dictionary extToImporter = new(StringComparer.OrdinalIgnoreCase); + public static readonly Dictionary extToIcon = new(StringComparer.OrdinalIgnoreCase); [OnAssemblyLoad] public static void GenerateLookUp() @@ -96,7 +96,7 @@ public CustomEditorAttribute(Type type) Type = type; } - public static Dictionary typeToEditor = new(); + public static readonly Dictionary typeToEditor = new(); [OnAssemblyLoad] public static void GenerateLookUp() diff --git a/Prowl.Editor/Assets/Importers/FontImporter.cs b/Prowl.Editor/Assets/Importers/FontImporter.cs index 6306e3d2c..4490ac367 100644 --- a/Prowl.Editor/Assets/Importers/FontImporter.cs +++ b/Prowl.Editor/Assets/Importers/FontImporter.cs @@ -12,7 +12,7 @@ namespace Prowl.Editor.Assets; [Importer("FileIcon.png", typeof(Font), ".ttf")] public class FontImporter : ScriptedImporter { - public List characterRanges = [Font.CharacterRange.BasicLatin]; + public readonly List characterRanges = [Font.CharacterRange.BasicLatin]; public float fontSize = 20; public int width = 1024; public int height = 1024; diff --git a/Prowl.Editor/Assets/Importers/TextureImporter.cs b/Prowl.Editor/Assets/Importers/TextureImporter.cs index 8a60277c1..5198adf1d 100644 --- a/Prowl.Editor/Assets/Importers/TextureImporter.cs +++ b/Prowl.Editor/Assets/Importers/TextureImporter.cs @@ -19,7 +19,7 @@ public class TextureImporter : ScriptedImporter public FilterType textureMinFilter = FilterType.Linear; public FilterType textureMagFilter = FilterType.Linear; - public FilterType textureMipFilter = FilterType.Linear; + public readonly FilterType textureMipFilter = FilterType.Linear; public override void Import(SerializedAsset ctx, FileInfo assetPath) { diff --git a/Prowl.Editor/Build/Desktop_Player.cs b/Prowl.Editor/Build/Desktop_Player.cs index fbe70a9bd..09c0f308f 100644 --- a/Prowl.Editor/Build/Desktop_Player.cs +++ b/Prowl.Editor/Build/Desktop_Player.cs @@ -26,21 +26,21 @@ public enum Target Universal } - public Target target = Target.win_x64; + public readonly Target target = Target.win_x64; public enum Configuration { Debug, Release } - public Configuration configuration = Configuration.Release; + public readonly Configuration configuration = Configuration.Release; public enum AssetPacking { [Text("All Assets")] All, [Text("Used Assets")] Used } - public AssetPacking assetPacking = AssetPacking.Used; + public readonly AssetPacking assetPacking = AssetPacking.Used; protected override void Build(AssetRef[] scenes, DirectoryInfo output) diff --git a/Prowl.Editor/Editor/Docking/DockContainer.cs b/Prowl.Editor/Editor/Docking/DockContainer.cs index bd2c18acf..cc8a33444 100644 --- a/Prowl.Editor/Editor/Docking/DockContainer.cs +++ b/Prowl.Editor/Editor/Docking/DockContainer.cs @@ -9,7 +9,7 @@ namespace Prowl.Editor.Docking; public class DockContainer { - public DockNode Root = new(); + public readonly DockNode Root = new(); private Vector2 PaddedMins => new(0, 0); public void Update(Rect root) diff --git a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs index 634319738..6b6dbf149 100644 --- a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs +++ b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs @@ -20,7 +20,7 @@ public class NodeEditorAttribute(Type type) : Attribute { public Type Type { get; private set; } = type; - public static Dictionary nodeEditors = []; + public static readonly Dictionary nodeEditors = []; [OnAssemblyLoad] public static void GenerateLookUp() @@ -576,7 +576,7 @@ public class NodeEditor private RenderTexture RenderTarget; internal NodePort? draggingPort; - internal List reroutePoints = []; + internal readonly List reroutePoints = []; internal Vector2? dragSelectionStart; internal Rect dragSelection; diff --git a/Prowl.Editor/Editor/Preferences/AssetPipelinePreferences.cs b/Prowl.Editor/Editor/Preferences/AssetPipelinePreferences.cs index efab4a581..a3bca17c8 100644 --- a/Prowl.Editor/Editor/Preferences/AssetPipelinePreferences.cs +++ b/Prowl.Editor/Editor/Preferences/AssetPipelinePreferences.cs @@ -10,8 +10,8 @@ namespace Prowl.Editor.Preferences; public class AssetPipelinePreferences : ScriptableSingleton { [Text("Asset Browser:")] - public bool HideExtensions = true; - public float ThumbnailSize = 0.0f; + public readonly bool HideExtensions = true; + public readonly float ThumbnailSize = 0.0f; [Text("Pipeline:")] public bool AutoImport = true; } diff --git a/Prowl.Editor/Editor/Preferences/GeneralPreferences.cs b/Prowl.Editor/Editor/Preferences/GeneralPreferences.cs index cf8c9ebe0..dba2f0112 100644 --- a/Prowl.Editor/Editor/Preferences/GeneralPreferences.cs +++ b/Prowl.Editor/Editor/Preferences/GeneralPreferences.cs @@ -10,11 +10,11 @@ namespace Prowl.Editor.Preferences; public class GeneralPreferences : ScriptableSingleton { [Text("General:")] - public bool LockFPS = false; + public readonly bool LockFPS = false; [ShowIf("LockFPS")] - public int TargetFPS = 0; + public readonly int TargetFPS = 0; [ShowIf("LockFPS", true)] - public bool VSync = true; + public readonly bool VSync = true; [Text("Debugging:")] public bool ShowDebugLogs = true; @@ -23,8 +23,8 @@ public class GeneralPreferences : ScriptableSingleton public bool ShowDebugSuccess = true; [Text("Game View:")] - public bool AutoFocusGameView = true; - public bool AutoRefreshGameView = true; + public readonly bool AutoFocusGameView = true; + public readonly bool AutoRefreshGameView = true; public GameWindow.Resolutions Resolution = GameWindow.Resolutions.fit; [HideInInspector] public int CurrentWidth = 1280; @@ -37,18 +37,18 @@ public class GeneralPreferences : ScriptableSingleton public class EditorPreferences : ScriptableSingleton { [Text("UI:")] - public bool AntiAliasing = true; + public readonly bool AntiAliasing = true; [Text("File Editor:")] - public string fileEditor = ""; // code - public string fileEditorArgs = ""; // "${ProjectDirectory}" -g "${File}":${Line}:${Character} + public readonly string fileEditor = ""; // code + public readonly string fileEditorArgs = ""; // "${ProjectDirectory}" -g "${File}":${Line}:${Character} } [FilePath("EditorStyle.pref", FilePathAttribute.Location.EditorPreference)] public class EditorStylePrefs : ScriptableSingleton { [Text("Colors:")] - public double Disabled = 0.7; + public readonly double Disabled = 0.7; public Color LesserText = new(110, 110, 120); public Color Background = new(15, 15, 18); public Color WindowBGOne = new(31, 33, 40); @@ -68,17 +68,17 @@ public class EditorStylePrefs : ScriptableSingleton public double DockSpacing = 4; [Text("Rounding:")] - public double WindowRoundness = 4; - public double TabRoundness = 4; - public double AssetRoundness = 4; - public double ButtonRoundness = 4; + public readonly double WindowRoundness = 4; + public readonly double TabRoundness = 4; + public readonly double AssetRoundness = 4; + public readonly double ButtonRoundness = 4; public enum NoodlePath { Straight, Curvy, Angled, ShaderLab } public enum NoodleStroke { Basic, Dashed } [Text("Node Editor:")] - public NoodlePath NoodlePathType = NoodlePath.Curvy; - public NoodleStroke NoodleStrokeType = NoodleStroke.Basic; - public double NoodleStrokeWidth = 4; + public readonly NoodlePath NoodlePathType = NoodlePath.Curvy; + public readonly NoodleStroke NoodleStrokeType = NoodleStroke.Basic; + public readonly double NoodleStrokeWidth = 4; // Base Colors public static Color Black => new(0, 0, 0, 255); diff --git a/Prowl.Editor/Editor/Preferences/PackageManagerPreferences.cs b/Prowl.Editor/Editor/Preferences/PackageManagerPreferences.cs index 85efc6977..2279d87fc 100644 --- a/Prowl.Editor/Editor/Preferences/PackageManagerPreferences.cs +++ b/Prowl.Editor/Editor/Preferences/PackageManagerPreferences.cs @@ -10,12 +10,12 @@ public class PackageManagerPreferences : ScriptableSingleton Sources = [new("Nuget", "https://api.nuget.org/v3/index.json", true)]; + public readonly List Sources = [new("Nuget", "https://api.nuget.org/v3/index.json", true)]; public bool IncludePrerelease = true; // True for the time being untill we have a stable 1.0 release } diff --git a/Prowl.Editor/Editor/Preferences/SceneViewPreferences.cs b/Prowl.Editor/Editor/Preferences/SceneViewPreferences.cs index 99519bb6b..13c6ef071 100644 --- a/Prowl.Editor/Editor/Preferences/SceneViewPreferences.cs +++ b/Prowl.Editor/Editor/Preferences/SceneViewPreferences.cs @@ -10,27 +10,27 @@ namespace Prowl.Editor.Preferences; public class SceneViewPreferences : ScriptableSingleton { [Text("Controls:")] - public float LookSensitivity = 1f; - public float PanSensitivity = 1f; - public float ZoomSensitivity = 1f; + public readonly float LookSensitivity = 1f; + public readonly float PanSensitivity = 1f; + public readonly float ZoomSensitivity = 1f; - public bool InvertLook = false; + public readonly bool InvertLook = false; - public double SnapDistance = 0.5f; - public double SnapAngle = 10f; + public readonly double SnapDistance = 0.5f; + public readonly double SnapAngle = 10f; [Space, Text("Rendering:")] public SceneViewWindow.GridType GridType = SceneViewWindow.GridType.XZ; - public bool ShowFPS = true; + public readonly bool ShowFPS = true; [Space] - public float NearClip = 0.02f; - public float FarClip = 10000f; + public readonly float NearClip = 0.02f; + public readonly float FarClip = 10000f; public float RenderResolution = 1f; [Text("Grid:")] - public float LineWidth = 0.02f; - public float PrimaryGridSize = 1f; - public float SecondaryGridSize = 5f; + public readonly float LineWidth = 0.02f; + public readonly float PrimaryGridSize = 1f; + public readonly float SecondaryGridSize = 5f; public Color GridColor = new Color(1.0f, 1.0f, 1.0f, 0.5f); } diff --git a/Prowl.Editor/Editor/Widgets/FileDialog.cs b/Prowl.Editor/Editor/Widgets/FileDialog.cs index a6294d235..708879084 100644 --- a/Prowl.Editor/Editor/Widgets/FileDialog.cs +++ b/Prowl.Editor/Editor/Widgets/FileDialog.cs @@ -57,7 +57,7 @@ internal void UpdateCache() public class FileDialog : EditorWindow { - public FileDialogContext Dialog; + public readonly FileDialogContext Dialog; private FileDialogSortBy _sortBy = FileDialogSortBy.None; diff --git a/Prowl.Editor/EditorGuiManager.cs b/Prowl.Editor/EditorGuiManager.cs index e86048c0f..ce37ff5be 100644 --- a/Prowl.Editor/EditorGuiManager.cs +++ b/Prowl.Editor/EditorGuiManager.cs @@ -27,7 +27,7 @@ public static class EditorGuiManager public static WeakReference? FocusedWindow; - public static List Windows = []; + public static readonly List Windows = []; static readonly List WindowsToRemove = []; diff --git a/Prowl.Editor/Project.cs b/Prowl.Editor/Project.cs index 0486265c7..b7029d90f 100644 --- a/Prowl.Editor/Project.cs +++ b/Prowl.Editor/Project.cs @@ -17,22 +17,22 @@ public class Project { #region Public Properties - public DirectoryInfo ProjectDirectory; + public readonly DirectoryInfo ProjectDirectory; public bool Exists => ProjectDirectory.Exists; public string Name => ProjectDirectory.Name; public string ProjectPath => ProjectDirectory.FullName; - public DirectoryInfo AssetDirectory; - public DirectoryInfo LibraryDirectory; - public DirectoryInfo DefaultsDirectory; - public DirectoryInfo PackagesDirectory; - public DirectoryInfo TempDirectory; + public readonly DirectoryInfo AssetDirectory; + public readonly DirectoryInfo LibraryDirectory; + public readonly DirectoryInfo DefaultsDirectory; + public readonly DirectoryInfo PackagesDirectory; + public readonly DirectoryInfo TempDirectory; - public FileInfo Assembly_Proj; - public FileInfo Assembly_DLL; + public readonly FileInfo Assembly_Proj; + public readonly FileInfo Assembly_DLL; - public FileInfo Editor_Assembly_Proj; - public FileInfo Editor_Assembly_DLL; + public readonly FileInfo Editor_Assembly_Proj; + public readonly FileInfo Editor_Assembly_DLL; public static event Action OnProjectChanged; diff --git a/Prowl.Editor/Utilities/ShaderCompiler/FileIncluder.cs b/Prowl.Editor/Utilities/ShaderCompiler/FileIncluder.cs index 3857b4a8c..fb3e74e63 100644 --- a/Prowl.Editor/Utilities/ShaderCompiler/FileIncluder.cs +++ b/Prowl.Editor/Utilities/ShaderCompiler/FileIncluder.cs @@ -7,7 +7,7 @@ namespace Prowl.Editor.Utilities; public class FileIncluder { - public string SourceFile; + public readonly string SourceFile; public string SourceFilePath => Path.Join(_searchDirectories[0].FullName, SourceFile); private readonly string _relativeDirectory; diff --git a/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs b/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs index 218e467eb..06bcd96b7 100644 --- a/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs +++ b/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs @@ -849,8 +849,8 @@ public class ParsedPass public struct EntryPoint(ShaderStages stages, string name) { - public ShaderStages Stage = stages; - public string Name = name; + public readonly ShaderStages Stage = stages; + public readonly string Name = name; } diff --git a/Prowl.Runtime/Components/Animation.cs b/Prowl.Runtime/Components/Animation.cs index e11c70281..1b7e78506 100644 --- a/Prowl.Runtime/Components/Animation.cs +++ b/Prowl.Runtime/Components/Animation.cs @@ -12,10 +12,10 @@ namespace Prowl.Runtime; public class Animation : MonoBehaviour { - public List> Clips = []; + public readonly List> Clips = []; public AssetRef DefaultClip; - public bool PlayAutomatically = true; - public double Speed = 1.0; + public readonly bool PlayAutomatically = true; + public readonly double Speed = 1.0; private readonly List _states = new List(); private readonly Dictionary _stateDictionary = new Dictionary(); @@ -208,8 +208,8 @@ public void RemoveClip(string stateName) public class AnimationState { - public string Name; - public AnimationClip Clip; + public readonly string Name; + public readonly AnimationClip Clip; public bool Enabled; public double Length => Clip.Duration; public double NormalizedTime => Time / Length; @@ -219,9 +219,9 @@ public class AnimationState public double MoveWeightSpeed = 1.0; public double TargetWeight = 1.0; - public AnimationWrapMode Wrap = AnimationWrapMode.Loop; + public readonly AnimationWrapMode Wrap = AnimationWrapMode.Loop; - public HashSet MixingTransforms = new HashSet(); + public readonly HashSet MixingTransforms = new HashSet(); public enum BlendMode { @@ -229,7 +229,7 @@ public enum BlendMode Additive, } - public BlendMode Blend = BlendMode.Blend; + public readonly BlendMode Blend = BlendMode.Blend; public AnimationState(string name, AnimationClip clip) { diff --git a/Prowl.Runtime/Components/Audio/AudioSource.cs b/Prowl.Runtime/Components/Audio/AudioSource.cs index f1b4fe0e4..494a2082f 100644 --- a/Prowl.Runtime/Components/Audio/AudioSource.cs +++ b/Prowl.Runtime/Components/Audio/AudioSource.cs @@ -12,10 +12,10 @@ namespace Prowl.Runtime; public sealed class AudioSource : MonoBehaviour { public AssetRef Clip; - public bool PlayOnAwake = true; - public bool Looping = false; - public float Volume = 1f; - public float MaxDistance = 32f; + public readonly bool PlayOnAwake = true; + public readonly bool Looping = false; + public readonly float Volume = 1f; + public readonly float MaxDistance = 32f; private ActiveAudio _source; private AudioBuffer _buffer; diff --git a/Prowl.Runtime/Components/Camera.cs b/Prowl.Runtime/Components/Camera.cs index e4b92ca4d..8417c7bac 100644 --- a/Prowl.Runtime/Components/Camera.cs +++ b/Prowl.Runtime/Components/Camera.cs @@ -21,10 +21,10 @@ public class Camera : MonoBehaviour { public LayerMask LayerMask = LayerMask.Everything; - public CameraClearMode ClearMode = CameraClearMode.Skybox; + public readonly CameraClearMode ClearMode = CameraClearMode.Skybox; public Color ClearColor = new Color(0f, 0f, 0f, 1f); - public float FieldOfView = 60f; - public float OrthographicSize = 0.5f; + public readonly float FieldOfView = 60f; + public readonly float OrthographicSize = 0.5f; public int DrawOrder = 0; public Rect Viewrect = new Rect(0, 0, 1, 1); public float NearClip = 0.01f; diff --git a/Prowl.Runtime/Components/Navmesh/NavMeshAgent.cs b/Prowl.Runtime/Components/Navmesh/NavMeshAgent.cs index 6760d5995..db0e641bb 100644 --- a/Prowl.Runtime/Components/Navmesh/NavMeshAgent.cs +++ b/Prowl.Runtime/Components/Navmesh/NavMeshAgent.cs @@ -25,14 +25,14 @@ public NavMeshSurface Surface [SerializeField, HideInInspector] private NavMeshSurface surface; - public float radius = 0.5f; - public float height = 1f; - public float maxAcceleration = 8.0f; - public float maxSpeed = 3.5f; - public float collisionQueryRange = 5f; - public float pathOptimizationRange = 15f; - - public DtCrowdAgentConfig crowdConfig = new(); + public readonly float radius = 0.5f; + public readonly float height = 1f; + public readonly float maxAcceleration = 8.0f; + public readonly float maxSpeed = 3.5f; + public readonly float collisionQueryRange = 5f; + public readonly float pathOptimizationRange = 15f; + + public readonly DtCrowdAgentConfig crowdConfig = new(); public DtCrowdAgent? InternalAgent { get; internal set; } = null; diff --git a/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs b/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs index ee243e106..f765fb804 100644 --- a/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs +++ b/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs @@ -21,14 +21,14 @@ public class NavMeshSurface : MonoBehaviour { #region Public - Inspector - public bool useStaticGeometry = true; + public readonly bool useStaticGeometry = true; public LayerMask GeometryLayers; [ShowIf("useStaticGeometry")] - public List staticGeometry = new(); + public readonly List staticGeometry = new(); [ShowIf("useStaticGeometry", true)] - public List meshGeometry = new(); + public readonly List meshGeometry = new(); public BuildSettings navSettings = new(); @@ -454,25 +454,25 @@ public void Append(Collider collider) public struct BuildSettings { - public float cellSize = 0.3f; - public float cellHeight = 0.2f; + public readonly float cellSize = 0.3f; + public readonly float cellHeight = 0.2f; - public float agentHeight = 1f; - public float agentRadius = 0.5f; - public float agentMaxClimb = 0.9f; - public float agentMaxSlope = 45f; - public float agentMaxAcceleration = 8f; - public float agentMaxSpeed = 3.5f; + public readonly float agentHeight = 1f; + public readonly float agentRadius = 0.5f; + public readonly float agentMaxClimb = 0.9f; + public readonly float agentMaxSlope = 45f; + public readonly float agentMaxAcceleration = 8f; + public readonly float agentMaxSpeed = 3.5f; - public int minRegionSize = 8; - public int mergedRegionSize = 20; + public readonly int minRegionSize = 8; + public readonly int mergedRegionSize = 20; - public bool filterLowHangingObstacles = true; - public bool filterLedgeSpans = true; - public bool filterWalkableLowHeightSpans = true; + public readonly bool filterLowHangingObstacles = true; + public readonly bool filterLedgeSpans = true; + public readonly bool filterWalkableLowHeightSpans = true; - public bool tiled; - public int tileSize = 32; + public readonly bool tiled; + public readonly int tileSize = 32; public BuildSettings() { diff --git a/Prowl.Runtime/Components/Physics/CharacterController.cs b/Prowl.Runtime/Components/Physics/CharacterController.cs index 9262a22c7..9460b425e 100644 --- a/Prowl.Runtime/Components/Physics/CharacterController.cs +++ b/Prowl.Runtime/Components/Physics/CharacterController.cs @@ -14,12 +14,12 @@ namespace Prowl.Runtime; public sealed class CharacterController : Rigidbody { public float speed = 4f; - public float jumpVelocity = 6f; - public float maxSlope = (MathF.PI * 0.25f).ToDeg(); - public float maxVerticalForce = 100; - public float maxHoriztonalForce = 20; - public float supportDepth = -0.05f; - public float supportContinuationDepth = -0.1f; + public readonly float jumpVelocity = 6f; + public readonly float maxSlope = (MathF.PI * 0.25f).ToDeg(); + public readonly float maxVerticalForce = 100; + public readonly float maxHoriztonalForce = 20; + public readonly float supportDepth = -0.05f; + public readonly float supportContinuationDepth = -0.1f; [ShowInInspector] public Vector2 TargetVelocity { get; set; } = Vector2.zero; diff --git a/Prowl.Runtime/Components/UI/GUICanvas.cs b/Prowl.Runtime/Components/UI/GUICanvas.cs index d998a3105..4d43b9633 100644 --- a/Prowl.Runtime/Components/UI/GUICanvas.cs +++ b/Prowl.Runtime/Components/UI/GUICanvas.cs @@ -14,7 +14,7 @@ public class GUICanvas : MonoBehaviour public enum Space { Screen } public Space space = Space.Screen; public Camera TargetCamera; - public bool DoAntiAliasing = true; + public readonly bool DoAntiAliasing = true; private Gui gui; diff --git a/Prowl.Runtime/EngineObject.cs b/Prowl.Runtime/EngineObject.cs index a57a3c3ae..2f2547843 100644 --- a/Prowl.Runtime/EngineObject.cs +++ b/Prowl.Runtime/EngineObject.cs @@ -15,7 +15,7 @@ public class EngineObject : IDisposable static int NextID = 1; - protected int _instanceID; + protected readonly int _instanceID; public int InstanceID => _instanceID; // Asset path if we have one diff --git a/Prowl.Runtime/GUI/Graphics/UIDrawList.cs b/Prowl.Runtime/GUI/Graphics/UIDrawList.cs index b1f021065..ad0fd20a8 100644 --- a/Prowl.Runtime/GUI/Graphics/UIDrawList.cs +++ b/Prowl.Runtime/GUI/Graphics/UIDrawList.cs @@ -67,8 +67,8 @@ public class UIDrawList // This is what you have to render internal List _commandList; // Commands. Typically 1 command = 1 gpu draw call. - internal List _indices; // Index buffer. Each command consume ImDrawCmd::ElemCount of those - internal List _vertices; // Vertex buffer. + internal List _indices; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + internal readonly List _vertices; // Vertex buffer. private uint _currentVertexIndex; // == _vertices.Count private int _vertexWritePos; // point within _vertices after each add command (to avoid using the ImVector<> operators too much) diff --git a/Prowl.Runtime/GUI/Gui.Core.cs b/Prowl.Runtime/GUI/Gui.Core.cs index 55ed7ec84..59bf838ec 100644 --- a/Prowl.Runtime/GUI/Gui.Core.cs +++ b/Prowl.Runtime/GUI/Gui.Core.cs @@ -11,7 +11,7 @@ namespace Prowl.Runtime.GUI; public partial class Gui { - public static Stack ActiveGUIStack = []; + public static readonly Stack ActiveGUIStack = []; public static Gui ActiveGUI => ActiveGUIStack.Count > 0 ? ActiveGUIStack.Peek() : null; public Rect ScreenRect { get; private set; } @@ -24,8 +24,8 @@ public partial class Gui public readonly GuiDraw2D Draw2D; public readonly GuiDraw3D Draw3D; - internal LinkedList layoutNodeScopes = new(); - internal Stack IDStack = new(); + internal readonly LinkedList layoutNodeScopes = new(); + internal readonly Stack IDStack = new(); internal bool layoutDirty = false; internal ulong frameCount = 0; internal readonly List ScollableNodes = new(); @@ -214,7 +214,7 @@ public enum ClipType { None, Inner, Outer } public class LayoutNodeScope : IDisposable { - public LayoutNode _node; + public readonly LayoutNode _node; public LayoutNodeScope(LayoutNode node) { diff --git a/Prowl.Runtime/GUI/Gui.Input.cs b/Prowl.Runtime/GUI/Gui.Input.cs index c3994ced6..69e13db4c 100644 --- a/Prowl.Runtime/GUI/Gui.Input.cs +++ b/Prowl.Runtime/GUI/Gui.Input.cs @@ -13,17 +13,17 @@ public partial class Gui public event Action OnPointerPosSet; public event Action OnCursorVisibilitySet; - internal bool[] KeyCurState = new bool[KeyValues.Length]; - internal bool[] KeyPreState = new bool[KeyValues.Length]; + internal readonly bool[] KeyCurState = new bool[KeyValues.Length]; + internal readonly bool[] KeyPreState = new bool[KeyValues.Length]; - internal double[] KeyPressedTime = new double[KeyValues.Length]; + internal readonly double[] KeyPressedTime = new double[KeyValues.Length]; internal Key KeyCode = Key.Unknown; - internal bool[] PointerCurState = new bool[MouseValues.Length]; - internal bool[] PointerPreState = new bool[MouseValues.Length]; + internal readonly bool[] PointerCurState = new bool[MouseValues.Length]; + internal readonly bool[] PointerPreState = new bool[MouseValues.Length]; - internal double[] PointerPressedTime = new double[MouseValues.Length]; - internal Vector2[] PointerClickPos = new Vector2[MouseValues.Length]; + internal readonly double[] PointerPressedTime = new double[MouseValues.Length]; + internal readonly Vector2[] PointerClickPos = new Vector2[MouseValues.Length]; internal MouseButton PointerButton = (MouseButton)(-1); public Vector2 PreviousPointerPos = Vector2.zero; @@ -42,8 +42,8 @@ public Vector2 PointerPos public Vector2 PointerDelta => PointerPos - PreviousPointerPos; public bool IsPointerMoving => PointerDelta.sqrMagnitude > 0; - public double[] PointerLastClickTime = new double[MouseValues.Length]; - public Vector2[] PointerLastClickPos = new Vector2[MouseValues.Length]; + public readonly double[] PointerLastClickTime = new double[MouseValues.Length]; + public readonly Vector2[] PointerLastClickPos = new Vector2[MouseValues.Length]; public const double MaxDoubleClickTime = 0.25; private Vector2 frameBufferScale; diff --git a/Prowl.Runtime/GUI/Gui.Interaction.cs b/Prowl.Runtime/GUI/Gui.Interaction.cs index 6db3f21d8..489b73a75 100644 --- a/Prowl.Runtime/GUI/Gui.Interaction.cs +++ b/Prowl.Runtime/GUI/Gui.Interaction.cs @@ -268,7 +268,7 @@ public struct Interactable public double ZIndex => zIndex; private readonly Gui _gui; - internal ulong _id; + internal readonly ulong _id; internal Rect _rect; internal double zIndex; diff --git a/Prowl.Runtime/GUI/GuiDraw2D.cs b/Prowl.Runtime/GUI/GuiDraw2D.cs index 7d8e47c45..6f3cc4747 100644 --- a/Prowl.Runtime/GUI/GuiDraw2D.cs +++ b/Prowl.Runtime/GUI/GuiDraw2D.cs @@ -12,7 +12,7 @@ public class GuiDraw2D { public UIDrawList DrawList => _drawList[currentZIndex]; - internal Dictionary _drawList = new(); + internal readonly Dictionary _drawList = new(); private int currentZIndex => _gui.CurrentZIndex; diff --git a/Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs b/Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs index 1bd2825d8..c11f8ee05 100644 --- a/Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs +++ b/Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs @@ -56,8 +56,8 @@ public readonly Vector2 GlobalPosition // Keep the Scrolls cached public double VScroll = node.VScroll; public double HScroll = node.HScroll; - public bool ShowVScroll = node._showVScroll; - public bool ShowHScroll = node._showHScroll; + public readonly bool ShowVScroll = node._showVScroll; + public readonly bool ShowHScroll = node._showHScroll; } public bool HasLayoutData => _data._node == this; @@ -126,7 +126,7 @@ public double HScroll internal int ZIndex = 0; - internal List Children = new List(); + internal readonly List Children = new List(); public LayoutNode(LayoutNode? parent, Gui gui, ulong storageHash) { diff --git a/Prowl.Runtime/GUI/Layout/Offset.cs b/Prowl.Runtime/GUI/Layout/Offset.cs index f8f51c3c4..4f54e2053 100644 --- a/Prowl.Runtime/GUI/Layout/Offset.cs +++ b/Prowl.Runtime/GUI/Layout/Offset.cs @@ -11,9 +11,9 @@ public struct Offset private bool isLerp = false; - public double Value; + public readonly double Value; public double PixelOffset; - public LayoutValueType Type; + public readonly LayoutValueType Type; private double _lerpValue; private double _lerpPixelOffset; diff --git a/Prowl.Runtime/GUI/Layout/Size.cs b/Prowl.Runtime/GUI/Layout/Size.cs index 70f2b95aa..05ee847dc 100644 --- a/Prowl.Runtime/GUI/Layout/Size.cs +++ b/Prowl.Runtime/GUI/Layout/Size.cs @@ -11,9 +11,9 @@ public struct Size private bool isLerp = false; - public double Value; - public double PixelOffset; - public LayoutValueType Type; + public readonly double Value; + public readonly double PixelOffset; + public readonly LayoutValueType Type; private double _lerpValue; private double _lerpPixelOffset; diff --git a/Prowl.Runtime/GUI/Layout/Spacing.cs b/Prowl.Runtime/GUI/Layout/Spacing.cs index 7cac19637..e5e2e50e6 100644 --- a/Prowl.Runtime/GUI/Layout/Spacing.cs +++ b/Prowl.Runtime/GUI/Layout/Spacing.cs @@ -8,10 +8,10 @@ namespace Prowl.Runtime.GUI; public struct Spacing { - public double Left; - public double Right; - public double Top; - public double Bottom; + public readonly double Left; + public readonly double Right; + public readonly double Top; + public readonly double Bottom; public readonly double Horizontal => Left + Right; public readonly double Vertical => Top + Bottom; diff --git a/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs b/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs index 50496102f..d8d18d05a 100644 --- a/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs +++ b/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs @@ -55,7 +55,7 @@ public float GetWidth(int index) public int SelectEnd; public int SelectStart; public bool SingleLine; - public UndoState UndoData = new(); + public readonly UndoState UndoData = new(); } public static class StbTextEdit @@ -849,10 +849,10 @@ public class UndoState { public int redo_char_point; public short redo_point; - public int[] undo_char = new int[999]; + public readonly int[] undo_char = new int[999]; public int undo_char_point; public short undo_point; - public UndoRecord[] undo_rec = new UndoRecord[99]; + public readonly UndoRecord[] undo_rec = new UndoRecord[99]; public void FlushRedo() { diff --git a/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs b/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs index 0a0aa5dd7..825e9386c 100644 --- a/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs +++ b/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs @@ -83,8 +83,8 @@ public class TransformGizmo public bool IsOver => hoveredGizmo != null || focusedGizmo != null; public Rect Viewport; - public double GizmoSize = 75.0; - public double StrokeWidth = 4.0; + public readonly double GizmoSize = 75.0; + public readonly double StrokeWidth = 4.0; public Vector3 ViewForward; public Vector3 ViewUp; @@ -110,7 +110,7 @@ public enum GizmoOrientation { Global, Local } // internal Matrix4x4 InverseModelViewProjection; private readonly List _subGizmos = []; - internal Gui _gui; + internal readonly Gui _gui; internal TransformGizmoMode mode; private ISubGizmo? hoveredGizmo; diff --git a/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs b/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs index 82df3ecdb..e83063ed8 100644 --- a/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs +++ b/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs @@ -37,8 +37,8 @@ public struct WidgetStyle public float BorderThickness; public float Roundness; public AssetRef Font; - public float FontSize; - public float ItemSize; + public readonly float FontSize; + public readonly float ItemSize; public WidgetStyle(float itemSize) { diff --git a/Prowl.Runtime/GameObject/Attributes/InspectorUIAttribute.cs b/Prowl.Runtime/GameObject/Attributes/InspectorUIAttribute.cs index 256872e45..128e025db 100644 --- a/Prowl.Runtime/GameObject/Attributes/InspectorUIAttribute.cs +++ b/Prowl.Runtime/GameObject/Attributes/InspectorUIAttribute.cs @@ -23,7 +23,7 @@ public class SpaceAttribute : Attribute, InspectorUIAttribute [AttributeUsage(T.Field, AllowMultiple = true)] public class TextAttribute(string text) : Attribute, InspectorUIAttribute { - public string text = text; + public readonly string text = text; public GuiAttribType AttribType() => GuiAttribType.Text; } @@ -36,22 +36,22 @@ public class SeparatorAttribute : Attribute, InspectorUIAttribute [AttributeUsage(T.Field, AllowMultiple = false)] public class TooltipAttribute(string text) : Attribute, InspectorUIAttribute { - public string tooltip = text; + public readonly string tooltip = text; public GuiAttribType AttribType() => GuiAttribType.Tooltip; } [AttributeUsage(T.Field | T.Property, AllowMultiple = false)] public class ShowIfAttribute(string propertyName, bool inverted = false) : Attribute, InspectorUIAttribute { - public string propertyName = propertyName; - public bool inverted = inverted; + public readonly string propertyName = propertyName; + public readonly bool inverted = inverted; public GuiAttribType AttribType() => GuiAttribType.ShowIf; } [AttributeUsage(T.Method, AllowMultiple = false)] public class GUIButtonAttribute(string text) : Attribute { - public string buttonText = text; + public readonly string buttonText = text; } [AttributeUsage(T.Field, AllowMultiple = false)] diff --git a/Prowl.Runtime/GameObject/TagLayerManager.cs b/Prowl.Runtime/GameObject/TagLayerManager.cs index f375241ec..1a622bb8f 100644 --- a/Prowl.Runtime/GameObject/TagLayerManager.cs +++ b/Prowl.Runtime/GameObject/TagLayerManager.cs @@ -12,7 +12,7 @@ namespace Prowl.Runtime; [FilePath("TagAndLayers.setting", FilePathAttribute.Location.Setting)] public class TagLayerManager : ScriptableSingleton { - public List tags = + public readonly List tags = [ "Untagged", "Main Camera", @@ -23,7 +23,7 @@ public class TagLayerManager : ScriptableSingleton "Game Controller" ]; - public string[] layers = + public readonly string[] layers = [ "Default", "TransparentFX", diff --git a/Prowl.Runtime/Physics.cs b/Prowl.Runtime/Physics.cs index ec625aa5d..88e230a81 100644 --- a/Prowl.Runtime/Physics.cs +++ b/Prowl.Runtime/Physics.cs @@ -24,12 +24,12 @@ namespace Prowl.Runtime; public class PhysicsSetting : ScriptableSingleton { public Vector3 Gravity = new Vector3(0, -9.81f, 0); - public int Iterations = 8; - public int Substep = 1; - public int TargetFrameRate = 50; - public bool UseMultithreading = true; - public bool EnhancedDeterminism = false; - public bool AutoSyncTransforms = true; + public readonly int Iterations = 8; + public readonly int Substep = 1; + public readonly int TargetFrameRate = 50; + public readonly bool UseMultithreading = true; + public readonly bool EnhancedDeterminism = false; + public readonly bool AutoSyncTransforms = true; } diff --git a/Prowl.Runtime/Rendering/CommandBuffer.cs b/Prowl.Runtime/Rendering/CommandBuffer.cs index 1e37084a4..bd17a57da 100644 --- a/Prowl.Runtime/Rendering/CommandBuffer.cs +++ b/Prowl.Runtime/Rendering/CommandBuffer.cs @@ -12,7 +12,7 @@ public class CommandBuffer : IDisposable { private static Material s_blit; - internal CommandList _commandList; + internal readonly CommandList _commandList; private bool _isRecording = false; private Framebuffer _activeFramebuffer; diff --git a/Prowl.Runtime/Rendering/Material.cs b/Prowl.Runtime/Rendering/Material.cs index 42a00d945..7621cc913 100644 --- a/Prowl.Runtime/Rendering/Material.cs +++ b/Prowl.Runtime/Rendering/Material.cs @@ -13,10 +13,10 @@ namespace Prowl.Runtime; public sealed class Material : EngineObject { public AssetRef Shader; - public PropertyState Properties; + public readonly PropertyState Properties; [NonSerialized] - public KeywordState LocalKeywords; + public readonly KeywordState LocalKeywords; internal Material() : base("New Material") { diff --git a/Prowl.Runtime/Rendering/PropertyState.cs b/Prowl.Runtime/Rendering/PropertyState.cs index a689cc35d..f9658c09c 100644 --- a/Prowl.Runtime/Rendering/PropertyState.cs +++ b/Prowl.Runtime/Rendering/PropertyState.cs @@ -51,10 +51,10 @@ public class PropertyState public bool IsEmpty => _values.Count == 0 && _buffers.Count == 0; - [SerializeField] internal Dictionary _values; + [SerializeField] internal readonly Dictionary _values; - internal Dictionary _rawTextures; - internal Dictionary _buffers; + internal readonly Dictionary _rawTextures; + internal readonly Dictionary _buffers; diff --git a/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs b/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs index cf2858c63..17a4597e7 100644 --- a/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs +++ b/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs @@ -20,7 +20,7 @@ public class DefaultRenderPipeline : RenderPipeline private static Mesh s_skyDome; private static Texture2D s_whiteTexture; - public static DefaultRenderPipeline Default = new(); + public static readonly DefaultRenderPipeline Default = new(); private static void ValidateDefaults() diff --git a/Prowl.Runtime/Rendering/Shader/ShaderUniform.cs b/Prowl.Runtime/Rendering/Shader/ShaderUniform.cs index 3b73fc940..3caee3737 100644 --- a/Prowl.Runtime/Rendering/Shader/ShaderUniform.cs +++ b/Prowl.Runtime/Rendering/Shader/ShaderUniform.cs @@ -42,9 +42,9 @@ private static string CleanseName(string rawName) public readonly string name; public readonly uint binding; - public uint size; + public readonly uint size; - public ShaderUniformMember[] members; + public readonly ShaderUniformMember[] members; private ShaderUniform() { } diff --git a/Prowl.Runtime/Rendering/Texture/RenderTexture.cs b/Prowl.Runtime/Rendering/Texture/RenderTexture.cs index be0b7d4ba..3c5f5ce08 100644 --- a/Prowl.Runtime/Rendering/Texture/RenderTexture.cs +++ b/Prowl.Runtime/Rendering/Texture/RenderTexture.cs @@ -12,16 +12,16 @@ namespace Prowl.Runtime; public struct RenderTextureDescription { - public uint width; - public uint height; + public readonly uint width; + public readonly uint height; - public PixelFormat[] colorBufferFormats; + public readonly PixelFormat[] colorBufferFormats; public PixelFormat? depthBufferFormat; - public bool sampled; - public bool enableRandomWrite; + public readonly bool sampled; + public readonly bool enableRandomWrite; - public TextureSampleCount sampleCount; + public readonly TextureSampleCount sampleCount; public RenderTextureDescription( uint width, uint height, diff --git a/Prowl.Runtime/Rendering/Texture/Texture.cs b/Prowl.Runtime/Rendering/Texture/Texture.cs index 2647ba1b3..f2a32bf6d 100644 --- a/Prowl.Runtime/Rendering/Texture/Texture.cs +++ b/Prowl.Runtime/Rendering/Texture/Texture.cs @@ -37,7 +37,7 @@ public abstract class Texture : EngineObject, ISerializable public bool IsMipmappable => Usage.HasFlag(TextureUsage.GenerateMipmaps); /// The sampler for this - public TextureSampler Sampler = TextureSampler.CreateLinear(); + public readonly TextureSampler Sampler = TextureSampler.CreateLinear(); /// The multisample count of this public TextureSampleCount SampleCount => InternalTexture.SampleCount; diff --git a/Prowl.Runtime/Rendering/Texture/Texture2D.cs b/Prowl.Runtime/Rendering/Texture/Texture2D.cs index ad7be51f4..33c912d81 100644 --- a/Prowl.Runtime/Rendering/Texture/Texture2D.cs +++ b/Prowl.Runtime/Rendering/Texture/Texture2D.cs @@ -18,10 +18,10 @@ public sealed class Texture2D : Texture /// The height of this . public uint Height => InternalTexture.Height; - public static Texture2D EmptyWhite = CreateDefaultTex(1, 1, [Color.white]); + public static readonly Texture2D EmptyWhite = CreateDefaultTex(1, 1, [Color.white]); - public static Texture2D Empty = CreateDefaultTex(1, 1, [Color.clear]); - public static Texture2D EmptyRW = CreateDefaultTex(1, 1, [Color.black], TextureUsage.Storage); + public static readonly Texture2D Empty = CreateDefaultTex(1, 1, [Color.clear]); + public static readonly Texture2D EmptyRW = CreateDefaultTex(1, 1, [Color.black], TextureUsage.Storage); public static Texture2D Checker => CreateDefaultTex(4, 4, [ Color.white, diff --git a/Prowl.Runtime/SceneManager.cs b/Prowl.Runtime/SceneManager.cs index ea9bd36b7..3deb07fad 100644 --- a/Prowl.Runtime/SceneManager.cs +++ b/Prowl.Runtime/SceneManager.cs @@ -12,7 +12,7 @@ namespace Prowl.Runtime.SceneManagement; public static class SceneManager { private static readonly List _gameObjects = new(); - internal static HashSet _dontDestroyOnLoad = new(); + internal static readonly HashSet _dontDestroyOnLoad = new(); public static Scene MainScene { get; private set; } = new(); diff --git a/Prowl.Runtime/Serializer/Serializer.cs b/Prowl.Runtime/Serializer/Serializer.cs index cc8f1f9ef..dd8ec4b00 100644 --- a/Prowl.Runtime/Serializer/Serializer.cs +++ b/Prowl.Runtime/Serializer/Serializer.cs @@ -42,11 +42,11 @@ public static class Serializer { public class SerializationContext { - public Dictionary objectToId = new(ReferenceEqualityComparer.Instance); - public Dictionary idToObject = []; + public readonly Dictionary objectToId = new(ReferenceEqualityComparer.Instance); + public readonly Dictionary idToObject = []; public int nextId = 1; private int dependencyCounter = 0; - public HashSet dependencies = []; + public readonly HashSet dependencies = []; public SerializationContext() { diff --git a/Prowl.Runtime/Utils/NodeSystem/Node.cs b/Prowl.Runtime/Utils/NodeSystem/Node.cs index 0e88f7651..af3c3fa42 100644 --- a/Prowl.Runtime/Utils/NodeSystem/Node.cs +++ b/Prowl.Runtime/Utils/NodeSystem/Node.cs @@ -260,11 +260,11 @@ public void ClearConnections() [AttributeUsage(AttributeTargets.Field)] public class InputAttribute : Attribute { - public ShowBackingValue backingValue; - public ConnectionType connectionType; - public bool dynamicPortList; - public TypeConstraint typeConstraint; - public bool onHeader; + public readonly ShowBackingValue backingValue; + public readonly ConnectionType connectionType; + public readonly bool dynamicPortList; + public readonly TypeConstraint typeConstraint; + public readonly bool onHeader; /// Mark a serializable field as an input port. You can access this through /// Should we display the backing value for this port as an editor field? @@ -286,10 +286,10 @@ public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnect [AttributeUsage(AttributeTargets.Field)] public class OutputAttribute : Attribute { - public ConnectionType connectionType; - public bool dynamicPortList; - public TypeConstraint typeConstraint; - public bool onHeader; + public readonly ConnectionType connectionType; + public readonly bool dynamicPortList; + public readonly TypeConstraint typeConstraint; + public readonly bool onHeader; /// Mark a serializable field as an output port. You can access this through /// Should we allow multiple connections? @@ -308,9 +308,9 @@ public OutputAttribute(ConnectionType connectionType = ConnectionType.Multiple, [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class NodeAttribute(string menuName) : Attribute { - public string catagory = menuName; + public readonly string catagory = menuName; - public static MultiValueDictionary nodeCatagories = new MultiValueDictionary(); + public static readonly MultiValueDictionary nodeCatagories = new MultiValueDictionary(); [OnAssemblyLoad] public static void OnAssemblyLoad() @@ -337,7 +337,7 @@ public static void OnAssemblyUnload() [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class DisallowMultipleNodesAttribute : Attribute { - public int max; + public readonly int max; /// Prevents Node of the same type to be added more than once (configurable) to a NodeGraph /// How many nodes to allow. Defaults to 1. public DisallowMultipleNodesAttribute(int max = 1) diff --git a/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs b/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs index ee97e3eaa..1c71dacc6 100644 --- a/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs +++ b/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs @@ -41,13 +41,13 @@ public abstract class NodeGraph : ScriptableObject, ISerializationCallbackReceiv /// All nodes in the graph. /// See: - public List nodes = []; + public readonly List nodes = []; public virtual (string, Type)[] NodeTypes { get; } = []; public virtual (string, Type)[] NodeReflectionTypes { get; } = []; public abstract string[] NodeCategories { get; } - public List parameters = []; + public readonly List parameters = []; public void Validate() { @@ -196,7 +196,7 @@ public override void OnAfterDeserialize() [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class RequireNodeAttribute(params Type[] type) : Attribute { - public Type[] types = type; + public readonly Type[] types = type; public bool Requires(Type type) { diff --git a/Prowl.Runtime/Utils/NodeSystem/Nodes/Flow Control/ForLoopNode.cs b/Prowl.Runtime/Utils/NodeSystem/Nodes/Flow Control/ForLoopNode.cs index a1769377d..02d4d7b3b 100644 --- a/Prowl.Runtime/Utils/NodeSystem/Nodes/Flow Control/ForLoopNode.cs +++ b/Prowl.Runtime/Utils/NodeSystem/Nodes/Flow Control/ForLoopNode.cs @@ -17,8 +17,8 @@ public class ForLoopNode : InOutFlowNode [Output, SerializeIgnore] public int Index; - [Input] public int FirstIndex = 0; - [Input] public int LastIndex = 10; + [Input] public readonly int FirstIndex = 0; + [Input] public readonly int LastIndex = 10; private int currentIndex; diff --git a/Prowl.Runtime/Utils/NodeSystem/Nodes/Operations/String Nodes.cs b/Prowl.Runtime/Utils/NodeSystem/Nodes/Operations/String Nodes.cs index f6bc92cb1..7deff4d71 100644 --- a/Prowl.Runtime/Utils/NodeSystem/Nodes/Operations/String Nodes.cs +++ b/Prowl.Runtime/Utils/NodeSystem/Nodes/Operations/String Nodes.cs @@ -43,7 +43,7 @@ public class String_Contains_Node : Node [Output, SerializeIgnore] public bool Contains; - public System.StringComparison Mode = System.StringComparison.Ordinal; + public readonly System.StringComparison Mode = System.StringComparison.Ordinal; public override object GetValue(NodePort port) => GetInputValue("In", In).Contains(GetInputValue("Has", Has), Mode); } @@ -59,7 +59,7 @@ public class String_StartsWith_Node : Node [Output, SerializeIgnore] public string Result; - public System.StringComparison Mode = System.StringComparison.Ordinal; + public readonly System.StringComparison Mode = System.StringComparison.Ordinal; public override object GetValue(NodePort port) => GetInputValue("In", In).StartsWith(GetInputValue("StartsWith", StartsWith), Mode); } @@ -75,7 +75,7 @@ public class String_EndsWith_Node : Node [Output, SerializeIgnore] public string Result; - public System.StringComparison Mode = System.StringComparison.Ordinal; + public readonly System.StringComparison Mode = System.StringComparison.Ordinal; public override object GetValue(NodePort port) => GetInputValue("In", In).EndsWith(GetInputValue("EndsWith", EndsWith), Mode); } @@ -199,7 +199,7 @@ public class String_IsEqual_Node : Node [Output, SerializeIgnore] public bool IsEqual; - public System.StringComparison Mode = System.StringComparison.Ordinal; + public readonly System.StringComparison Mode = System.StringComparison.Ordinal; public override object GetValue(NodePort port) => GetInputValue("A", A).Equals(GetInputValue("B", B), Mode); } diff --git a/Prowl.Runtime/Utils/NodeSystem/PortTypeOverrideAttribute.cs b/Prowl.Runtime/Utils/NodeSystem/PortTypeOverrideAttribute.cs index b0a0e872d..9d0bfaffc 100644 --- a/Prowl.Runtime/Utils/NodeSystem/PortTypeOverrideAttribute.cs +++ b/Prowl.Runtime/Utils/NodeSystem/PortTypeOverrideAttribute.cs @@ -10,7 +10,7 @@ namespace Prowl.Runtime.NodeSystem; [AttributeUsage(AttributeTargets.Field)] public class PortTypeOverrideAttribute : Attribute { - public Type type; + public readonly Type type; /// Overrides the ValueType of the Port /// ValueType of the Port public PortTypeOverrideAttribute(Type type) diff --git a/Prowl.Runtime/Utils/SerializedAsset.cs b/Prowl.Runtime/Utils/SerializedAsset.cs index 8a8af1a46..bb588abdb 100644 --- a/Prowl.Runtime/Utils/SerializedAsset.cs +++ b/Prowl.Runtime/Utils/SerializedAsset.cs @@ -12,7 +12,7 @@ namespace Prowl.Runtime.Utils; public class SerializedAsset { public EngineObject? Main; - public List SubAssets = new(); + public readonly List SubAssets = new(); [SerializeIgnore] public Guid Guid; diff --git a/Prowl.Runtime/Utils/Tokenizer.cs b/Prowl.Runtime/Utils/Tokenizer.cs index 2c570a715..fd79e9328 100644 --- a/Prowl.Runtime/Utils/Tokenizer.cs +++ b/Prowl.Runtime/Utils/Tokenizer.cs @@ -18,8 +18,8 @@ public class Tokenizer public int CurrentLine { get; set; } = 1; public int CurrentColumn { get; set; } - public Func IsWhitespace; - public Func IsQuote; + public readonly Func IsWhitespace; + public readonly Func IsQuote; public Tokenizer(ReadOnlyMemory input, Func? isWhitespace = null, Func? isQuote = null) { From 792893fd37a324d582e5be58cab2099bb46e5158 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 19:45:59 -0500 Subject: [PATCH 28/31] refactor: some extra fixes --- Prowl.Editor/SelectHandler.cs | 4 +-- Prowl.Editor/Utilities/CreateAssetMenu.cs | 10 ++++--- Prowl.Editor/Utilities/EditorUtils.cs | 2 +- Prowl.Editor/Utilities/MenuItem.cs | 26 ++++++++----------- Prowl.Editor/Utilities/ProjectCache.cs | 3 +-- .../ShaderCompiler/ShaderCompiler.cs | 2 +- .../Utilities/ShaderCompiler/ShaderParser.cs | 15 +++++------ .../ShaderCompiler/UniformReflector.cs | 2 +- .../ShaderCompiler/VertexInputReflector.cs | 2 +- Prowl.Editor/Utilities/Texture2DLoader.cs | 2 +- Prowl.Runtime/AnimationCurve.cs | 8 +++--- Prowl.Runtime/Application.cs | 2 +- Prowl.Runtime/AssetRef.cs | 6 ++--- 13 files changed, 40 insertions(+), 44 deletions(-) diff --git a/Prowl.Editor/SelectHandler.cs b/Prowl.Editor/SelectHandler.cs index b9141f02b..b45158d4a 100644 --- a/Prowl.Editor/SelectHandler.cs +++ b/Prowl.Editor/SelectHandler.cs @@ -61,7 +61,7 @@ public void StartFrame() if (lastSelectedIndex == -1 && selected.Count > 0) { - SetSelectedIndex((T)selected[0]); + SetSelectedIndex(Selected[0]); } } @@ -105,7 +105,7 @@ public void Foreach(Action value) var copy = new List(selected); copy.ForEach((weak) => { - value?.Invoke((T)weak); + value.Invoke((T)weak); }); } diff --git a/Prowl.Editor/Utilities/CreateAssetMenu.cs b/Prowl.Editor/Utilities/CreateAssetMenu.cs index 16d13f0ee..04c40ab68 100644 --- a/Prowl.Editor/Utilities/CreateAssetMenu.cs +++ b/Prowl.Editor/Utilities/CreateAssetMenu.cs @@ -20,19 +20,21 @@ public static void FindAllMenus() List<(string, Type)> values = new(); foreach (var assembly in assemblies) { - Type[] types = null; try { - types = assembly.GetTypes(); + Type[] types = assembly.GetTypes(); foreach (var type in types) - if (type != null && type.IsAssignableTo(typeof(ScriptableObject))) + if (type.IsAssignableTo(typeof(ScriptableObject))) { var attribute = type.GetCustomAttribute(); if (attribute != null) values.Add(("Assets/" + attribute.Name, type)); } } - catch { } + catch + { + // ignored + } } foreach (var value in values) diff --git a/Prowl.Editor/Utilities/EditorUtils.cs b/Prowl.Editor/Utilities/EditorUtils.cs index 482ca9945..77653af0f 100644 --- a/Prowl.Editor/Utilities/EditorUtils.cs +++ b/Prowl.Editor/Utilities/EditorUtils.cs @@ -29,7 +29,7 @@ public static List GetDerivedTypes(Type baseType, Assembly assembly) return derivedTypes; } - public static bool IsSubclassOf(Type type, Type baseType) + public static bool IsSubclassOf(Type? type, Type? baseType) { if (type == null || baseType == null || type == baseType) return false; diff --git a/Prowl.Editor/Utilities/MenuItem.cs b/Prowl.Editor/Utilities/MenuItem.cs index 5ed0cbb9f..71279452d 100644 --- a/Prowl.Editor/Utilities/MenuItem.cs +++ b/Prowl.Editor/Utilities/MenuItem.cs @@ -57,20 +57,21 @@ public static void FindAllMenus() var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in assemblies) { - Type[] types = null; try { - types = assembly.GetTypes(); + Type[] types = assembly.GetTypes(); foreach (var type in types) - if (type != null) - foreach (MethodInfo method in type.GetMethods()) - { - var attribute = method.GetCustomAttribute(); - if (attribute != null) - values.Add(new MenuPath(attribute.Path, () => method.Invoke(null, null))); - } + foreach (MethodInfo method in type.GetMethods()) + { + var attribute = method.GetCustomAttribute(); + if (attribute != null) + values.Add(new MenuPath(attribute.Path, () => method.Invoke(null, null))); + } + } + catch + { + // ignored } - catch { } } // values is now a list of all methods with the Menu Paths @@ -105,16 +106,12 @@ public static void FindAllMenus() public static MenuPath? GetMenuPath(string root) { - if (Menus == null) return null; - if (root == null) return null; if (!Menus.ContainsKey(root)) return null; return Menus[root]; } public static bool DrawMenuRoot(string root, bool simpleRoot = false, Size? rootSize = null) { - if (Menus == null) return false; - if (root == null) return false; if (!Menus.ContainsKey(root)) return false; var node = Menus[root]; if (node.Children.Count == 0) return false; @@ -128,7 +125,6 @@ public static bool DrawMenuRoot(string root, bool simpleRoot = false, Size? root public static bool DrawMenu(MenuPath menu, bool simpleRoot, int depth, Size? rootSize = null) { - if (menu == null) return false; if (menu.Children.Count == 0) { if (EditorGUI.StyledButton(menu.Path)) diff --git a/Prowl.Editor/Utilities/ProjectCache.cs b/Prowl.Editor/Utilities/ProjectCache.cs index 4a1283b3d..360d36e49 100644 --- a/Prowl.Editor/Utilities/ProjectCache.cs +++ b/Prowl.Editor/Utilities/ProjectCache.cs @@ -92,7 +92,7 @@ public int Compare(Project? a, Project? b) */ - public Project? GetProject(int index) + public Project GetProject(int index) { Project project = _projectCache[index]; project.Refresh(); @@ -115,7 +115,6 @@ public void OnBeforeSerialize() public void OnAfterDeserialize() { - _serializedProjects ??= []; _projectCache = []; foreach (string path in _serializedProjects) diff --git a/Prowl.Editor/Utilities/ShaderCompiler/ShaderCompiler.cs b/Prowl.Editor/Utilities/ShaderCompiler/ShaderCompiler.cs index bbd4c22ce..fdbd5ea0b 100644 --- a/Prowl.Editor/Utilities/ShaderCompiler/ShaderCompiler.cs +++ b/Prowl.Editor/Utilities/ShaderCompiler/ShaderCompiler.cs @@ -149,7 +149,7 @@ public static ShaderVariant GenerateVariant(Context ctx, ShaderCreationArgs args ShaderDescription[] compiledSPIRV = Compile(args, state, includer, messages); foreach (ShaderDescription desc in compiledSPIRV) - if (desc.ShaderBytes == null || desc.ShaderBytes.Length == 0) + if (desc.ShaderBytes.Length == 0) return null; ReflectedResourceInfo info = Reflect(ctx, compiledSPIRV); diff --git a/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs b/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs index 06bcd96b7..986160e6a 100644 --- a/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs +++ b/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. See the LICENSE file in the project root for details. using System.Text; -using System.Text.RegularExpressions; using Prowl.Runtime; using Prowl.Runtime.Utils; @@ -30,7 +29,7 @@ public enum ShaderToken Quote } - static Dictionary> symbolHandlers = new() + private static readonly Dictionary> s_symbolHandlers = new() { {'{', (ctx) => HandleSingleCharToken(ctx, ShaderToken.OpenCurlBrace)}, {'}', (ctx) => HandleSingleCharToken(ctx, ShaderToken.CloseCurlBrace)}, @@ -46,7 +45,7 @@ private static Tokenizer CreateTokenizer(string input) { return new( input.AsMemory(), - symbolHandlers, + s_symbolHandlers, "{}()=,".Contains, ShaderToken.Identifier, ShaderToken.None, @@ -61,13 +60,13 @@ public static bool ParseShader(string input, FileIncluder includer, out Runtime. Tokenizer tokenizer = CreateTokenizer(input); - string name = ""; + string name; List properties = []; ParsedPass? globalDefaults = null; List parsedPasses = []; - string? fallback = null; + // string? fallback = null; try { @@ -100,7 +99,7 @@ public static bool ParseShader(string input, FileIncluder includer, out Runtime. case "Fallback": tokenizer.MoveNext(); // Move to string - fallback = tokenizer.ParseQuotedStringValue(); + // fallback = tokenizer.ParseQuotedStringValue(); break; default: @@ -199,7 +198,7 @@ private static bool LogCompilationMessages(string shaderName, List(string file, bool generateMipmaps = fal { if (Path.GetExtension(file).Equals(".dds", StringComparison.OrdinalIgnoreCase)) { - var texture = SixLabors.ImageSharp.Textures.Texture.Load(file, out var format); + var texture = SixLabors.ImageSharp.Textures.Texture.Load(file, out _); if (texture is SixLabors.ImageSharp.Textures.TextureFormats.FlatTexture flat) { var i = flat.MipMaps[0].GetImage(); diff --git a/Prowl.Runtime/AnimationCurve.cs b/Prowl.Runtime/AnimationCurve.cs index 73e2d89bc..f7168d83b 100644 --- a/Prowl.Runtime/AnimationCurve.cs +++ b/Prowl.Runtime/AnimationCurve.cs @@ -412,10 +412,10 @@ public KeyFrame(double position, double value, double tangentIn = 0, double tang if (Equals(value2, null)) return Equals(value1, null); - return (MathD.ApproximatelyEquals(value1.Position, value2.Position)) - && (MathD.ApproximatelyEquals(value1.Value, value2.Value)) - && (MathD.ApproximatelyEquals(value1.TangentIn, value2.TangentIn)) - && (MathD.ApproximatelyEquals(value1.TangentOut, value2.TangentOut)) + return (value1.Position == value2.Position) + && (value1.Value == value2.Value) + && (value1.TangentIn == value2.TangentIn) + && (value1.TangentOut == value2.TangentOut) && (value1.Continuity == value2.Continuity); } diff --git a/Prowl.Runtime/Application.cs b/Prowl.Runtime/Application.cs index 56d7b82a8..007573d0c 100644 --- a/Prowl.Runtime/Application.cs +++ b/Prowl.Runtime/Application.cs @@ -120,7 +120,7 @@ static void AppUpdate() static void AppClose() { - IsRunning = false; + isRunning = false; Quitting?.Invoke(); Graphics.Dispose(); Physics.Dispose(); diff --git a/Prowl.Runtime/AssetRef.cs b/Prowl.Runtime/AssetRef.cs index aa4335ed2..e54f1b516 100644 --- a/Prowl.Runtime/AssetRef.cs +++ b/Prowl.Runtime/AssetRef.cs @@ -28,8 +28,8 @@ public T? Res } set { - assetID = value == null ? Guid.Empty : value.AssetID; - fileID = value == null ? (ushort)0 : value.FileID; + assetID = value?.AssetID ?? Guid.Empty; + fileID = value?.FileID ?? 0; instance = value; } } @@ -212,7 +212,7 @@ public override string ToString() else stateChar = '_'; - return string.Format("[{2}] {0}", resType.Name, stateChar); + return string.Format("[{1}] {0}", resType.Name, stateChar); } public override bool Equals(object? obj) From 4c695f1cf41f7d076c0b9b49ad36de38ecd07f6b Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 20:07:49 -0500 Subject: [PATCH 29/31] Revert "fix: call Dispose() directly is obsolete. Using .Destroy()" This reverts commit 1dd6a7395ebf483467454826aab1b3748cdbe008. --- Prowl.Editor/Editor/GameWindow.cs | 2 +- Prowl.Editor/Editor/NodeEditor/NodeEditor.cs | 2 +- Prowl.Editor/Editor/SceneViewWindow.cs | 2 +- Prowl.Editor/Utilities/Texture2DLoader.cs | 2 +- Prowl.Runtime/EngineObject.cs | 4 ++-- Prowl.Runtime/GameObject/GameObject.cs | 4 ++-- Prowl.Runtime/Rendering/Texture/Texture.cs | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Prowl.Editor/Editor/GameWindow.cs b/Prowl.Editor/Editor/GameWindow.cs index 1d68e0486..8b630aa13 100644 --- a/Prowl.Editor/Editor/GameWindow.cs +++ b/Prowl.Editor/Editor/GameWindow.cs @@ -61,7 +61,7 @@ public GameWindow() : base() public void RefreshRenderTexture() { - RenderTarget?.Destroy(); + RenderTarget?.Dispose(); RenderTarget = new RenderTexture( (uint)GeneralPreferences.Instance.CurrentWidth, diff --git a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs index 6b6dbf149..c114c2699 100644 --- a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs +++ b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs @@ -613,7 +613,7 @@ public NodeEditor(NodeGraph graph) public void RefreshRenderTexture(Vector2 renderSize) { - RenderTarget?.Destroy(); + RenderTarget?.Dispose(); RenderTarget = new RenderTexture( (uint)renderSize.x, diff --git a/Prowl.Editor/Editor/SceneViewWindow.cs b/Prowl.Editor/Editor/SceneViewWindow.cs index cd0249ba2..0b3211ea6 100644 --- a/Prowl.Editor/Editor/SceneViewWindow.cs +++ b/Prowl.Editor/Editor/SceneViewWindow.cs @@ -55,7 +55,7 @@ public SceneViewWindow() : base() public void RefreshRenderTexture(int width, int height) { - RenderTarget?.Destroy(); + RenderTarget?.Dispose(); RenderTarget = new RenderTexture( (uint)width, (uint)height, diff --git a/Prowl.Editor/Utilities/Texture2DLoader.cs b/Prowl.Editor/Utilities/Texture2DLoader.cs index 785ae7c65..e4e7c6d97 100644 --- a/Prowl.Editor/Utilities/Texture2DLoader.cs +++ b/Prowl.Editor/Utilities/Texture2DLoader.cs @@ -88,7 +88,7 @@ public static Texture2D FromImage(Image image, bool generateMipm } catch { - texture.Destroy(); + texture.Dispose(); throw; } } diff --git a/Prowl.Runtime/EngineObject.cs b/Prowl.Runtime/EngineObject.cs index 2f2547843..8866113ff 100644 --- a/Prowl.Runtime/EngineObject.cs +++ b/Prowl.Runtime/EngineObject.cs @@ -98,7 +98,7 @@ public static void DestroyImmediate(EngineObject obj) { if (obj.IsDestroyed) throw new Exception(obj.Name + " is already destroyed."); obj.IsDestroyed = true; - obj.Destroy(); + obj.Dispose(); } public static void HandleDestroyed() @@ -106,7 +106,7 @@ public static void HandleDestroyed() while (destroyed.TryPop(out var obj)) { if (!obj.IsDestroyed) continue; - obj.Destroy(); + obj.Dispose(); } CleanupAllObjects(); diff --git a/Prowl.Runtime/GameObject/GameObject.cs b/Prowl.Runtime/GameObject/GameObject.cs index d1410cfe3..0b6fa90ed 100644 --- a/Prowl.Runtime/GameObject/GameObject.cs +++ b/Prowl.Runtime/GameObject/GameObject.cs @@ -560,13 +560,13 @@ public override void OnDispose() // Internal_DestroyCommitted removes the child from the parent // Hense why we do a while loop on the first element instead of a foreach/for while (children.Count > 0) - children[0].Destroy(); + children[0].Dispose(); foreach (var component in _components) { if (component.EnabledInHierarchy) component.Do(component.OnDisable); if (component.HasStarted) component.Do(component.OnDestroy); // OnDestroy is only called if the component has previously been active - component.Destroy(); + component.Dispose(); } _components.Clear(); _componentCache.Clear(); diff --git a/Prowl.Runtime/Rendering/Texture/Texture.cs b/Prowl.Runtime/Rendering/Texture/Texture.cs index f2a32bf6d..6e644721a 100644 --- a/Prowl.Runtime/Rendering/Texture/Texture.cs +++ b/Prowl.Runtime/Rendering/Texture/Texture.cs @@ -83,7 +83,7 @@ public override void OnDispose() TextureView = null; stagingTexture = null; - Sampler?.Destroy(); + Sampler?.Dispose(); } public void GenerateMipmaps(bool waitForCompletion = false) From 100488f96b101f60d75b0b710bc6e0490d71d6f8 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Mon, 16 Sep 2024 20:14:52 -0500 Subject: [PATCH 30/31] fix: reverting replacement of Dispose() to Destroy() --- Prowl.Runtime/Application.cs | 12 ++++++------ Prowl.Runtime/AssetRef.cs | 5 +++-- Prowl.Runtime/Audio/AudioSystem.cs | 10 +++++----- Prowl.Runtime/EngineObject.cs | 1 + 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/Prowl.Runtime/Application.cs b/Prowl.Runtime/Application.cs index 007573d0c..0f805c5bb 100644 --- a/Prowl.Runtime/Application.cs +++ b/Prowl.Runtime/Application.cs @@ -42,7 +42,7 @@ public static class Application GraphicsBackend.OpenGLES, ]; - private static readonly GraphicsBackend[] s_preferredMacBackends = // Covers MacOS/Apple + private static readonly GraphicsBackend[] s_preferredMacBackends = // Covers macOS/Apple [ GraphicsBackend.Metal, GraphicsBackend.OpenGL, @@ -77,9 +77,9 @@ public static void Run(string title, int width, int height, IAssetProvider asset Screen.Closing += AppClose; IsRunning = true; - IsPlaying = true; // Base application is not the editor, isplaying is always true + IsPlaying = true; // Base application is not the editor, IsPlaying is always true - Screen.Start($"{title} - {GetBackend()}", new Vector2Int(width, height), new Vector2Int(100, 100), WindowState.Normal); + Screen.Start($"{title} - {GetBackend()}", new Vector2Int(width, height), new Vector2Int(100, 100)); } static void AppInitialize() @@ -88,7 +88,7 @@ static void AppInitialize() SceneManager.Initialize(); AudioSystem.Initialize(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AssemblyManager.Initialize(); @@ -120,8 +120,8 @@ static void AppUpdate() static void AppClose() { - isRunning = false; - Quitting?.Invoke(); + IsRunning = false; + Quitting.Invoke(); Graphics.Dispose(); Physics.Dispose(); AudioSystem.Dispose(); diff --git a/Prowl.Runtime/AssetRef.cs b/Prowl.Runtime/AssetRef.cs index e54f1b516..d29090bbf 100644 --- a/Prowl.Runtime/AssetRef.cs +++ b/Prowl.Runtime/AssetRef.cs @@ -139,6 +139,7 @@ public AssetRef(Guid id) /// the specified alias. /// /// + /// public AssetRef(Guid id, ushort fileId) { instance = null; @@ -152,8 +153,8 @@ public AssetRef(Guid id, ushort fileId) public AssetRef(T? res) { instance = res; - assetID = res != null ? res.AssetID : Guid.Empty; - fileID = res != null ? res.FileID : (ushort)0; + assetID = res?.AssetID ?? Guid.Empty; + fileID = res?.FileID ?? 0; } public object? GetInstance() diff --git a/Prowl.Runtime/Audio/AudioSystem.cs b/Prowl.Runtime/Audio/AudioSystem.cs index 24c1d867a..e37482059 100644 --- a/Prowl.Runtime/Audio/AudioSystem.cs +++ b/Prowl.Runtime/Audio/AudioSystem.cs @@ -18,9 +18,9 @@ public static class AudioSystem private static readonly List _active = []; private static readonly List _pool = []; - private static AudioListener _listener; + private static AudioListener? s_listener; - public static AudioListener Listener => _listener; + public static AudioListener Listener => s_listener; public static AudioEngine Engine => _engine; @@ -75,17 +75,17 @@ public static void UpdatePool() public static void RegisterListener(AudioListener audioListener) { - if (_listener != null) + if (s_listener != null) { Debug.LogWarning("Audio listener already registered, only the first in the scene will work as intended! Please destroy that one first before instantiating a new Listener."); return; } - _listener = audioListener; + s_listener = audioListener; } public static void UnregisterListener(AudioListener audioListener) { - _listener = null; + s_listener = null; } public static AudioBuffer GetAudioBuffer(AudioClip clip) diff --git a/Prowl.Runtime/EngineObject.cs b/Prowl.Runtime/EngineObject.cs index 8866113ff..c135b12eb 100644 --- a/Prowl.Runtime/EngineObject.cs +++ b/Prowl.Runtime/EngineObject.cs @@ -130,6 +130,7 @@ public static EngineObject Instantiate(EngineObject obj, bool keepAssetID = fals /// Force the object to dispose immediately /// You are advised to not use this! Use Destroy() Instead. /// + /// TODO: FIXME: replacing GameObject and EngineObject calls crashes the app [Obsolete("You are advised to not use this! Use Destroy() Instead.")] public void Dispose() { From 079146918e2a9efb966d7315620abec5ddcccf75 Mon Sep 17 00:00:00 2001 From: Bruno Massa Date: Wed, 18 Sep 2024 21:39:03 -0500 Subject: [PATCH 31/31] Revert "refactor: readonly on several fields/properties that are never reassigned (typical for collections)" This reverts commit aca944c8f34b0c09778ba24912a004915e9c063b. --- Prowl.Editor/Assets/AssetDatabase.Packages.cs | 4 +-- Prowl.Editor/Assets/AssetDirectoryCache.cs | 12 +++---- Prowl.Editor/Assets/ImporterAttribute.cs | 8 ++--- Prowl.Editor/Assets/Importers/FontImporter.cs | 2 +- .../Assets/Importers/TextureImporter.cs | 2 +- Prowl.Editor/Build/Desktop_Player.cs | 6 ++-- Prowl.Editor/Editor/Docking/DockContainer.cs | 2 +- Prowl.Editor/Editor/NodeEditor/NodeEditor.cs | 4 +-- .../Preferences/AssetPipelinePreferences.cs | 4 +-- .../Editor/Preferences/GeneralPreferences.cs | 32 ++++++++--------- .../Preferences/PackageManagerPreferences.cs | 8 ++--- .../Preferences/SceneViewPreferences.cs | 24 ++++++------- Prowl.Editor/Editor/Widgets/FileDialog.cs | 2 +- Prowl.Editor/EditorGuiManager.cs | 2 +- Prowl.Editor/Project.cs | 20 +++++------ .../Utilities/ShaderCompiler/FileIncluder.cs | 2 +- .../Utilities/ShaderCompiler/ShaderParser.cs | 4 +-- Prowl.Runtime/Components/Animation.cs | 16 ++++----- Prowl.Runtime/Components/Audio/AudioSource.cs | 8 ++--- Prowl.Runtime/Components/Camera.cs | 6 ++-- .../Components/Navmesh/NavMeshAgent.cs | 16 ++++----- .../Components/Navmesh/NavMeshSurface.cs | 36 +++++++++---------- .../Components/Physics/CharacterController.cs | 12 +++---- Prowl.Runtime/Components/UI/GUICanvas.cs | 2 +- Prowl.Runtime/EngineObject.cs | 2 +- Prowl.Runtime/GUI/Graphics/UIDrawList.cs | 4 +-- Prowl.Runtime/GUI/Gui.Core.cs | 8 ++--- Prowl.Runtime/GUI/Gui.Input.cs | 18 +++++----- Prowl.Runtime/GUI/Gui.Interaction.cs | 2 +- Prowl.Runtime/GUI/GuiDraw2D.cs | 2 +- Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs | 6 ++-- Prowl.Runtime/GUI/Layout/Offset.cs | 4 +-- Prowl.Runtime/GUI/Layout/Size.cs | 6 ++-- Prowl.Runtime/GUI/Layout/Spacing.cs | 8 ++--- Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs | 6 ++-- .../GUI/Widgets/Gizmo/TransformGizmo.cs | 6 ++-- Prowl.Runtime/GUI/Widgets/Gui.InputField.cs | 4 +-- .../Attributes/InspectorUIAttribute.cs | 10 +++--- Prowl.Runtime/GameObject/TagLayerManager.cs | 4 +-- Prowl.Runtime/Physics.cs | 12 +++---- Prowl.Runtime/Rendering/CommandBuffer.cs | 2 +- Prowl.Runtime/Rendering/Material.cs | 4 +-- Prowl.Runtime/Rendering/PropertyState.cs | 6 ++-- .../RenderPipeline/DefaultRenderPipeline.cs | 2 +- .../Rendering/Shader/ShaderUniform.cs | 4 +-- .../Rendering/Texture/RenderTexture.cs | 12 +++---- Prowl.Runtime/Rendering/Texture/Texture.cs | 2 +- Prowl.Runtime/Rendering/Texture/Texture2D.cs | 6 ++-- Prowl.Runtime/SceneManager.cs | 2 +- Prowl.Runtime/Serializer/Serializer.cs | 6 ++-- Prowl.Runtime/Utils/NodeSystem/Node.cs | 24 ++++++------- Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs | 6 ++-- .../Nodes/Flow Control/ForLoopNode.cs | 4 +-- .../Nodes/Operations/String Nodes.cs | 8 ++--- .../NodeSystem/PortTypeOverrideAttribute.cs | 2 +- Prowl.Runtime/Utils/SerializedAsset.cs | 2 +- Prowl.Runtime/Utils/Tokenizer.cs | 4 +-- 57 files changed, 216 insertions(+), 216 deletions(-) diff --git a/Prowl.Editor/Assets/AssetDatabase.Packages.cs b/Prowl.Editor/Assets/AssetDatabase.Packages.cs index 72f3169e3..234616a33 100644 --- a/Prowl.Editor/Assets/AssetDatabase.Packages.cs +++ b/Prowl.Editor/Assets/AssetDatabase.Packages.cs @@ -28,9 +28,9 @@ public static partial class AssetDatabase /// Key: Package ID /// Value: Package Version /// - public static readonly Dictionary DesiredPackages = []; + public static Dictionary DesiredPackages = []; - public static readonly List Packages = []; + public static List Packages = []; #region Public Methods diff --git a/Prowl.Editor/Assets/AssetDirectoryCache.cs b/Prowl.Editor/Assets/AssetDirectoryCache.cs index 63054b146..84838d91a 100644 --- a/Prowl.Editor/Assets/AssetDirectoryCache.cs +++ b/Prowl.Editor/Assets/AssetDirectoryCache.cs @@ -7,17 +7,17 @@ public class AssetDirectoryCache(DirectoryInfo root) { public class DirNode(DirectoryInfo directory, DirNode? parent) { - public readonly DirectoryInfo Directory = directory; - public readonly DirNode? Parent = parent; - public readonly List SubDirectories = []; - public readonly List Files = []; + public DirectoryInfo Directory = directory; + public DirNode? Parent = parent; + public List SubDirectories = []; + public List Files = []; } public class FileNode { - public readonly FileInfo File; + public FileInfo File; public Guid AssetID; - public readonly AssetDatabase.SubAssetCache[] SubAssets; + public AssetDatabase.SubAssetCache[] SubAssets; public FileNode(FileInfo file) { diff --git a/Prowl.Editor/Assets/ImporterAttribute.cs b/Prowl.Editor/Assets/ImporterAttribute.cs index 2dfb8241e..c88fda272 100644 --- a/Prowl.Editor/Assets/ImporterAttribute.cs +++ b/Prowl.Editor/Assets/ImporterAttribute.cs @@ -20,9 +20,9 @@ public ImporterAttribute(string fileIcon, Type generalType, params string[] exte GeneralType = generalType; } - public static readonly Dictionary extToGeneralType = new(StringComparer.OrdinalIgnoreCase); - public static readonly Dictionary extToImporter = new(StringComparer.OrdinalIgnoreCase); - public static readonly Dictionary extToIcon = new(StringComparer.OrdinalIgnoreCase); + public static Dictionary extToGeneralType = new(StringComparer.OrdinalIgnoreCase); + public static Dictionary extToImporter = new(StringComparer.OrdinalIgnoreCase); + public static Dictionary extToIcon = new(StringComparer.OrdinalIgnoreCase); [OnAssemblyLoad] public static void GenerateLookUp() @@ -96,7 +96,7 @@ public CustomEditorAttribute(Type type) Type = type; } - public static readonly Dictionary typeToEditor = new(); + public static Dictionary typeToEditor = new(); [OnAssemblyLoad] public static void GenerateLookUp() diff --git a/Prowl.Editor/Assets/Importers/FontImporter.cs b/Prowl.Editor/Assets/Importers/FontImporter.cs index 4490ac367..6306e3d2c 100644 --- a/Prowl.Editor/Assets/Importers/FontImporter.cs +++ b/Prowl.Editor/Assets/Importers/FontImporter.cs @@ -12,7 +12,7 @@ namespace Prowl.Editor.Assets; [Importer("FileIcon.png", typeof(Font), ".ttf")] public class FontImporter : ScriptedImporter { - public readonly List characterRanges = [Font.CharacterRange.BasicLatin]; + public List characterRanges = [Font.CharacterRange.BasicLatin]; public float fontSize = 20; public int width = 1024; public int height = 1024; diff --git a/Prowl.Editor/Assets/Importers/TextureImporter.cs b/Prowl.Editor/Assets/Importers/TextureImporter.cs index 5198adf1d..8a60277c1 100644 --- a/Prowl.Editor/Assets/Importers/TextureImporter.cs +++ b/Prowl.Editor/Assets/Importers/TextureImporter.cs @@ -19,7 +19,7 @@ public class TextureImporter : ScriptedImporter public FilterType textureMinFilter = FilterType.Linear; public FilterType textureMagFilter = FilterType.Linear; - public readonly FilterType textureMipFilter = FilterType.Linear; + public FilterType textureMipFilter = FilterType.Linear; public override void Import(SerializedAsset ctx, FileInfo assetPath) { diff --git a/Prowl.Editor/Build/Desktop_Player.cs b/Prowl.Editor/Build/Desktop_Player.cs index 09c0f308f..fbe70a9bd 100644 --- a/Prowl.Editor/Build/Desktop_Player.cs +++ b/Prowl.Editor/Build/Desktop_Player.cs @@ -26,21 +26,21 @@ public enum Target Universal } - public readonly Target target = Target.win_x64; + public Target target = Target.win_x64; public enum Configuration { Debug, Release } - public readonly Configuration configuration = Configuration.Release; + public Configuration configuration = Configuration.Release; public enum AssetPacking { [Text("All Assets")] All, [Text("Used Assets")] Used } - public readonly AssetPacking assetPacking = AssetPacking.Used; + public AssetPacking assetPacking = AssetPacking.Used; protected override void Build(AssetRef[] scenes, DirectoryInfo output) diff --git a/Prowl.Editor/Editor/Docking/DockContainer.cs b/Prowl.Editor/Editor/Docking/DockContainer.cs index cc8a33444..bd2c18acf 100644 --- a/Prowl.Editor/Editor/Docking/DockContainer.cs +++ b/Prowl.Editor/Editor/Docking/DockContainer.cs @@ -9,7 +9,7 @@ namespace Prowl.Editor.Docking; public class DockContainer { - public readonly DockNode Root = new(); + public DockNode Root = new(); private Vector2 PaddedMins => new(0, 0); public void Update(Rect root) diff --git a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs index c114c2699..c84c00641 100644 --- a/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs +++ b/Prowl.Editor/Editor/NodeEditor/NodeEditor.cs @@ -20,7 +20,7 @@ public class NodeEditorAttribute(Type type) : Attribute { public Type Type { get; private set; } = type; - public static readonly Dictionary nodeEditors = []; + public static Dictionary nodeEditors = []; [OnAssemblyLoad] public static void GenerateLookUp() @@ -576,7 +576,7 @@ public class NodeEditor private RenderTexture RenderTarget; internal NodePort? draggingPort; - internal readonly List reroutePoints = []; + internal List reroutePoints = []; internal Vector2? dragSelectionStart; internal Rect dragSelection; diff --git a/Prowl.Editor/Editor/Preferences/AssetPipelinePreferences.cs b/Prowl.Editor/Editor/Preferences/AssetPipelinePreferences.cs index a3bca17c8..efab4a581 100644 --- a/Prowl.Editor/Editor/Preferences/AssetPipelinePreferences.cs +++ b/Prowl.Editor/Editor/Preferences/AssetPipelinePreferences.cs @@ -10,8 +10,8 @@ namespace Prowl.Editor.Preferences; public class AssetPipelinePreferences : ScriptableSingleton { [Text("Asset Browser:")] - public readonly bool HideExtensions = true; - public readonly float ThumbnailSize = 0.0f; + public bool HideExtensions = true; + public float ThumbnailSize = 0.0f; [Text("Pipeline:")] public bool AutoImport = true; } diff --git a/Prowl.Editor/Editor/Preferences/GeneralPreferences.cs b/Prowl.Editor/Editor/Preferences/GeneralPreferences.cs index dba2f0112..cf8c9ebe0 100644 --- a/Prowl.Editor/Editor/Preferences/GeneralPreferences.cs +++ b/Prowl.Editor/Editor/Preferences/GeneralPreferences.cs @@ -10,11 +10,11 @@ namespace Prowl.Editor.Preferences; public class GeneralPreferences : ScriptableSingleton { [Text("General:")] - public readonly bool LockFPS = false; + public bool LockFPS = false; [ShowIf("LockFPS")] - public readonly int TargetFPS = 0; + public int TargetFPS = 0; [ShowIf("LockFPS", true)] - public readonly bool VSync = true; + public bool VSync = true; [Text("Debugging:")] public bool ShowDebugLogs = true; @@ -23,8 +23,8 @@ public class GeneralPreferences : ScriptableSingleton public bool ShowDebugSuccess = true; [Text("Game View:")] - public readonly bool AutoFocusGameView = true; - public readonly bool AutoRefreshGameView = true; + public bool AutoFocusGameView = true; + public bool AutoRefreshGameView = true; public GameWindow.Resolutions Resolution = GameWindow.Resolutions.fit; [HideInInspector] public int CurrentWidth = 1280; @@ -37,18 +37,18 @@ public class GeneralPreferences : ScriptableSingleton public class EditorPreferences : ScriptableSingleton { [Text("UI:")] - public readonly bool AntiAliasing = true; + public bool AntiAliasing = true; [Text("File Editor:")] - public readonly string fileEditor = ""; // code - public readonly string fileEditorArgs = ""; // "${ProjectDirectory}" -g "${File}":${Line}:${Character} + public string fileEditor = ""; // code + public string fileEditorArgs = ""; // "${ProjectDirectory}" -g "${File}":${Line}:${Character} } [FilePath("EditorStyle.pref", FilePathAttribute.Location.EditorPreference)] public class EditorStylePrefs : ScriptableSingleton { [Text("Colors:")] - public readonly double Disabled = 0.7; + public double Disabled = 0.7; public Color LesserText = new(110, 110, 120); public Color Background = new(15, 15, 18); public Color WindowBGOne = new(31, 33, 40); @@ -68,17 +68,17 @@ public class EditorStylePrefs : ScriptableSingleton public double DockSpacing = 4; [Text("Rounding:")] - public readonly double WindowRoundness = 4; - public readonly double TabRoundness = 4; - public readonly double AssetRoundness = 4; - public readonly double ButtonRoundness = 4; + public double WindowRoundness = 4; + public double TabRoundness = 4; + public double AssetRoundness = 4; + public double ButtonRoundness = 4; public enum NoodlePath { Straight, Curvy, Angled, ShaderLab } public enum NoodleStroke { Basic, Dashed } [Text("Node Editor:")] - public readonly NoodlePath NoodlePathType = NoodlePath.Curvy; - public readonly NoodleStroke NoodleStrokeType = NoodleStroke.Basic; - public readonly double NoodleStrokeWidth = 4; + public NoodlePath NoodlePathType = NoodlePath.Curvy; + public NoodleStroke NoodleStrokeType = NoodleStroke.Basic; + public double NoodleStrokeWidth = 4; // Base Colors public static Color Black => new(0, 0, 0, 255); diff --git a/Prowl.Editor/Editor/Preferences/PackageManagerPreferences.cs b/Prowl.Editor/Editor/Preferences/PackageManagerPreferences.cs index 2279d87fc..85efc6977 100644 --- a/Prowl.Editor/Editor/Preferences/PackageManagerPreferences.cs +++ b/Prowl.Editor/Editor/Preferences/PackageManagerPreferences.cs @@ -10,12 +10,12 @@ public class PackageManagerPreferences : ScriptableSingleton Sources = [new("Nuget", "https://api.nuget.org/v3/index.json", true)]; + public List Sources = [new("Nuget", "https://api.nuget.org/v3/index.json", true)]; public bool IncludePrerelease = true; // True for the time being untill we have a stable 1.0 release } diff --git a/Prowl.Editor/Editor/Preferences/SceneViewPreferences.cs b/Prowl.Editor/Editor/Preferences/SceneViewPreferences.cs index 13c6ef071..99519bb6b 100644 --- a/Prowl.Editor/Editor/Preferences/SceneViewPreferences.cs +++ b/Prowl.Editor/Editor/Preferences/SceneViewPreferences.cs @@ -10,27 +10,27 @@ namespace Prowl.Editor.Preferences; public class SceneViewPreferences : ScriptableSingleton { [Text("Controls:")] - public readonly float LookSensitivity = 1f; - public readonly float PanSensitivity = 1f; - public readonly float ZoomSensitivity = 1f; + public float LookSensitivity = 1f; + public float PanSensitivity = 1f; + public float ZoomSensitivity = 1f; - public readonly bool InvertLook = false; + public bool InvertLook = false; - public readonly double SnapDistance = 0.5f; - public readonly double SnapAngle = 10f; + public double SnapDistance = 0.5f; + public double SnapAngle = 10f; [Space, Text("Rendering:")] public SceneViewWindow.GridType GridType = SceneViewWindow.GridType.XZ; - public readonly bool ShowFPS = true; + public bool ShowFPS = true; [Space] - public readonly float NearClip = 0.02f; - public readonly float FarClip = 10000f; + public float NearClip = 0.02f; + public float FarClip = 10000f; public float RenderResolution = 1f; [Text("Grid:")] - public readonly float LineWidth = 0.02f; - public readonly float PrimaryGridSize = 1f; - public readonly float SecondaryGridSize = 5f; + public float LineWidth = 0.02f; + public float PrimaryGridSize = 1f; + public float SecondaryGridSize = 5f; public Color GridColor = new Color(1.0f, 1.0f, 1.0f, 0.5f); } diff --git a/Prowl.Editor/Editor/Widgets/FileDialog.cs b/Prowl.Editor/Editor/Widgets/FileDialog.cs index 708879084..a6294d235 100644 --- a/Prowl.Editor/Editor/Widgets/FileDialog.cs +++ b/Prowl.Editor/Editor/Widgets/FileDialog.cs @@ -57,7 +57,7 @@ internal void UpdateCache() public class FileDialog : EditorWindow { - public readonly FileDialogContext Dialog; + public FileDialogContext Dialog; private FileDialogSortBy _sortBy = FileDialogSortBy.None; diff --git a/Prowl.Editor/EditorGuiManager.cs b/Prowl.Editor/EditorGuiManager.cs index ce37ff5be..e86048c0f 100644 --- a/Prowl.Editor/EditorGuiManager.cs +++ b/Prowl.Editor/EditorGuiManager.cs @@ -27,7 +27,7 @@ public static class EditorGuiManager public static WeakReference? FocusedWindow; - public static readonly List Windows = []; + public static List Windows = []; static readonly List WindowsToRemove = []; diff --git a/Prowl.Editor/Project.cs b/Prowl.Editor/Project.cs index b7029d90f..0486265c7 100644 --- a/Prowl.Editor/Project.cs +++ b/Prowl.Editor/Project.cs @@ -17,22 +17,22 @@ public class Project { #region Public Properties - public readonly DirectoryInfo ProjectDirectory; + public DirectoryInfo ProjectDirectory; public bool Exists => ProjectDirectory.Exists; public string Name => ProjectDirectory.Name; public string ProjectPath => ProjectDirectory.FullName; - public readonly DirectoryInfo AssetDirectory; - public readonly DirectoryInfo LibraryDirectory; - public readonly DirectoryInfo DefaultsDirectory; - public readonly DirectoryInfo PackagesDirectory; - public readonly DirectoryInfo TempDirectory; + public DirectoryInfo AssetDirectory; + public DirectoryInfo LibraryDirectory; + public DirectoryInfo DefaultsDirectory; + public DirectoryInfo PackagesDirectory; + public DirectoryInfo TempDirectory; - public readonly FileInfo Assembly_Proj; - public readonly FileInfo Assembly_DLL; + public FileInfo Assembly_Proj; + public FileInfo Assembly_DLL; - public readonly FileInfo Editor_Assembly_Proj; - public readonly FileInfo Editor_Assembly_DLL; + public FileInfo Editor_Assembly_Proj; + public FileInfo Editor_Assembly_DLL; public static event Action OnProjectChanged; diff --git a/Prowl.Editor/Utilities/ShaderCompiler/FileIncluder.cs b/Prowl.Editor/Utilities/ShaderCompiler/FileIncluder.cs index fb3e74e63..3857b4a8c 100644 --- a/Prowl.Editor/Utilities/ShaderCompiler/FileIncluder.cs +++ b/Prowl.Editor/Utilities/ShaderCompiler/FileIncluder.cs @@ -7,7 +7,7 @@ namespace Prowl.Editor.Utilities; public class FileIncluder { - public readonly string SourceFile; + public string SourceFile; public string SourceFilePath => Path.Join(_searchDirectories[0].FullName, SourceFile); private readonly string _relativeDirectory; diff --git a/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs b/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs index 986160e6a..dc83ae15c 100644 --- a/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs +++ b/Prowl.Editor/Utilities/ShaderCompiler/ShaderParser.cs @@ -848,8 +848,8 @@ public class ParsedPass public struct EntryPoint(ShaderStages stages, string name) { - public readonly ShaderStages Stage = stages; - public readonly string Name = name; + public ShaderStages Stage = stages; + public string Name = name; } diff --git a/Prowl.Runtime/Components/Animation.cs b/Prowl.Runtime/Components/Animation.cs index 1b7e78506..e11c70281 100644 --- a/Prowl.Runtime/Components/Animation.cs +++ b/Prowl.Runtime/Components/Animation.cs @@ -12,10 +12,10 @@ namespace Prowl.Runtime; public class Animation : MonoBehaviour { - public readonly List> Clips = []; + public List> Clips = []; public AssetRef DefaultClip; - public readonly bool PlayAutomatically = true; - public readonly double Speed = 1.0; + public bool PlayAutomatically = true; + public double Speed = 1.0; private readonly List _states = new List(); private readonly Dictionary _stateDictionary = new Dictionary(); @@ -208,8 +208,8 @@ public void RemoveClip(string stateName) public class AnimationState { - public readonly string Name; - public readonly AnimationClip Clip; + public string Name; + public AnimationClip Clip; public bool Enabled; public double Length => Clip.Duration; public double NormalizedTime => Time / Length; @@ -219,9 +219,9 @@ public class AnimationState public double MoveWeightSpeed = 1.0; public double TargetWeight = 1.0; - public readonly AnimationWrapMode Wrap = AnimationWrapMode.Loop; + public AnimationWrapMode Wrap = AnimationWrapMode.Loop; - public readonly HashSet MixingTransforms = new HashSet(); + public HashSet MixingTransforms = new HashSet(); public enum BlendMode { @@ -229,7 +229,7 @@ public enum BlendMode Additive, } - public readonly BlendMode Blend = BlendMode.Blend; + public BlendMode Blend = BlendMode.Blend; public AnimationState(string name, AnimationClip clip) { diff --git a/Prowl.Runtime/Components/Audio/AudioSource.cs b/Prowl.Runtime/Components/Audio/AudioSource.cs index 494a2082f..f1b4fe0e4 100644 --- a/Prowl.Runtime/Components/Audio/AudioSource.cs +++ b/Prowl.Runtime/Components/Audio/AudioSource.cs @@ -12,10 +12,10 @@ namespace Prowl.Runtime; public sealed class AudioSource : MonoBehaviour { public AssetRef Clip; - public readonly bool PlayOnAwake = true; - public readonly bool Looping = false; - public readonly float Volume = 1f; - public readonly float MaxDistance = 32f; + public bool PlayOnAwake = true; + public bool Looping = false; + public float Volume = 1f; + public float MaxDistance = 32f; private ActiveAudio _source; private AudioBuffer _buffer; diff --git a/Prowl.Runtime/Components/Camera.cs b/Prowl.Runtime/Components/Camera.cs index 8417c7bac..e4b92ca4d 100644 --- a/Prowl.Runtime/Components/Camera.cs +++ b/Prowl.Runtime/Components/Camera.cs @@ -21,10 +21,10 @@ public class Camera : MonoBehaviour { public LayerMask LayerMask = LayerMask.Everything; - public readonly CameraClearMode ClearMode = CameraClearMode.Skybox; + public CameraClearMode ClearMode = CameraClearMode.Skybox; public Color ClearColor = new Color(0f, 0f, 0f, 1f); - public readonly float FieldOfView = 60f; - public readonly float OrthographicSize = 0.5f; + public float FieldOfView = 60f; + public float OrthographicSize = 0.5f; public int DrawOrder = 0; public Rect Viewrect = new Rect(0, 0, 1, 1); public float NearClip = 0.01f; diff --git a/Prowl.Runtime/Components/Navmesh/NavMeshAgent.cs b/Prowl.Runtime/Components/Navmesh/NavMeshAgent.cs index db0e641bb..6760d5995 100644 --- a/Prowl.Runtime/Components/Navmesh/NavMeshAgent.cs +++ b/Prowl.Runtime/Components/Navmesh/NavMeshAgent.cs @@ -25,14 +25,14 @@ public NavMeshSurface Surface [SerializeField, HideInInspector] private NavMeshSurface surface; - public readonly float radius = 0.5f; - public readonly float height = 1f; - public readonly float maxAcceleration = 8.0f; - public readonly float maxSpeed = 3.5f; - public readonly float collisionQueryRange = 5f; - public readonly float pathOptimizationRange = 15f; - - public readonly DtCrowdAgentConfig crowdConfig = new(); + public float radius = 0.5f; + public float height = 1f; + public float maxAcceleration = 8.0f; + public float maxSpeed = 3.5f; + public float collisionQueryRange = 5f; + public float pathOptimizationRange = 15f; + + public DtCrowdAgentConfig crowdConfig = new(); public DtCrowdAgent? InternalAgent { get; internal set; } = null; diff --git a/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs b/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs index f765fb804..ee243e106 100644 --- a/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs +++ b/Prowl.Runtime/Components/Navmesh/NavMeshSurface.cs @@ -21,14 +21,14 @@ public class NavMeshSurface : MonoBehaviour { #region Public - Inspector - public readonly bool useStaticGeometry = true; + public bool useStaticGeometry = true; public LayerMask GeometryLayers; [ShowIf("useStaticGeometry")] - public readonly List staticGeometry = new(); + public List staticGeometry = new(); [ShowIf("useStaticGeometry", true)] - public readonly List meshGeometry = new(); + public List meshGeometry = new(); public BuildSettings navSettings = new(); @@ -454,25 +454,25 @@ public void Append(Collider collider) public struct BuildSettings { - public readonly float cellSize = 0.3f; - public readonly float cellHeight = 0.2f; + public float cellSize = 0.3f; + public float cellHeight = 0.2f; - public readonly float agentHeight = 1f; - public readonly float agentRadius = 0.5f; - public readonly float agentMaxClimb = 0.9f; - public readonly float agentMaxSlope = 45f; - public readonly float agentMaxAcceleration = 8f; - public readonly float agentMaxSpeed = 3.5f; + public float agentHeight = 1f; + public float agentRadius = 0.5f; + public float agentMaxClimb = 0.9f; + public float agentMaxSlope = 45f; + public float agentMaxAcceleration = 8f; + public float agentMaxSpeed = 3.5f; - public readonly int minRegionSize = 8; - public readonly int mergedRegionSize = 20; + public int minRegionSize = 8; + public int mergedRegionSize = 20; - public readonly bool filterLowHangingObstacles = true; - public readonly bool filterLedgeSpans = true; - public readonly bool filterWalkableLowHeightSpans = true; + public bool filterLowHangingObstacles = true; + public bool filterLedgeSpans = true; + public bool filterWalkableLowHeightSpans = true; - public readonly bool tiled; - public readonly int tileSize = 32; + public bool tiled; + public int tileSize = 32; public BuildSettings() { diff --git a/Prowl.Runtime/Components/Physics/CharacterController.cs b/Prowl.Runtime/Components/Physics/CharacterController.cs index 9460b425e..9262a22c7 100644 --- a/Prowl.Runtime/Components/Physics/CharacterController.cs +++ b/Prowl.Runtime/Components/Physics/CharacterController.cs @@ -14,12 +14,12 @@ namespace Prowl.Runtime; public sealed class CharacterController : Rigidbody { public float speed = 4f; - public readonly float jumpVelocity = 6f; - public readonly float maxSlope = (MathF.PI * 0.25f).ToDeg(); - public readonly float maxVerticalForce = 100; - public readonly float maxHoriztonalForce = 20; - public readonly float supportDepth = -0.05f; - public readonly float supportContinuationDepth = -0.1f; + public float jumpVelocity = 6f; + public float maxSlope = (MathF.PI * 0.25f).ToDeg(); + public float maxVerticalForce = 100; + public float maxHoriztonalForce = 20; + public float supportDepth = -0.05f; + public float supportContinuationDepth = -0.1f; [ShowInInspector] public Vector2 TargetVelocity { get; set; } = Vector2.zero; diff --git a/Prowl.Runtime/Components/UI/GUICanvas.cs b/Prowl.Runtime/Components/UI/GUICanvas.cs index 4d43b9633..d998a3105 100644 --- a/Prowl.Runtime/Components/UI/GUICanvas.cs +++ b/Prowl.Runtime/Components/UI/GUICanvas.cs @@ -14,7 +14,7 @@ public class GUICanvas : MonoBehaviour public enum Space { Screen } public Space space = Space.Screen; public Camera TargetCamera; - public readonly bool DoAntiAliasing = true; + public bool DoAntiAliasing = true; private Gui gui; diff --git a/Prowl.Runtime/EngineObject.cs b/Prowl.Runtime/EngineObject.cs index c135b12eb..adca636d4 100644 --- a/Prowl.Runtime/EngineObject.cs +++ b/Prowl.Runtime/EngineObject.cs @@ -15,7 +15,7 @@ public class EngineObject : IDisposable static int NextID = 1; - protected readonly int _instanceID; + protected int _instanceID; public int InstanceID => _instanceID; // Asset path if we have one diff --git a/Prowl.Runtime/GUI/Graphics/UIDrawList.cs b/Prowl.Runtime/GUI/Graphics/UIDrawList.cs index ad0fd20a8..b1f021065 100644 --- a/Prowl.Runtime/GUI/Graphics/UIDrawList.cs +++ b/Prowl.Runtime/GUI/Graphics/UIDrawList.cs @@ -67,8 +67,8 @@ public class UIDrawList // This is what you have to render internal List _commandList; // Commands. Typically 1 command = 1 gpu draw call. - internal List _indices; // Index buffer. Each command consume ImDrawCmd::ElemCount of those - internal readonly List _vertices; // Vertex buffer. + internal List _indices; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + internal List _vertices; // Vertex buffer. private uint _currentVertexIndex; // == _vertices.Count private int _vertexWritePos; // point within _vertices after each add command (to avoid using the ImVector<> operators too much) diff --git a/Prowl.Runtime/GUI/Gui.Core.cs b/Prowl.Runtime/GUI/Gui.Core.cs index 59bf838ec..55ed7ec84 100644 --- a/Prowl.Runtime/GUI/Gui.Core.cs +++ b/Prowl.Runtime/GUI/Gui.Core.cs @@ -11,7 +11,7 @@ namespace Prowl.Runtime.GUI; public partial class Gui { - public static readonly Stack ActiveGUIStack = []; + public static Stack ActiveGUIStack = []; public static Gui ActiveGUI => ActiveGUIStack.Count > 0 ? ActiveGUIStack.Peek() : null; public Rect ScreenRect { get; private set; } @@ -24,8 +24,8 @@ public partial class Gui public readonly GuiDraw2D Draw2D; public readonly GuiDraw3D Draw3D; - internal readonly LinkedList layoutNodeScopes = new(); - internal readonly Stack IDStack = new(); + internal LinkedList layoutNodeScopes = new(); + internal Stack IDStack = new(); internal bool layoutDirty = false; internal ulong frameCount = 0; internal readonly List ScollableNodes = new(); @@ -214,7 +214,7 @@ public enum ClipType { None, Inner, Outer } public class LayoutNodeScope : IDisposable { - public readonly LayoutNode _node; + public LayoutNode _node; public LayoutNodeScope(LayoutNode node) { diff --git a/Prowl.Runtime/GUI/Gui.Input.cs b/Prowl.Runtime/GUI/Gui.Input.cs index 69e13db4c..c3994ced6 100644 --- a/Prowl.Runtime/GUI/Gui.Input.cs +++ b/Prowl.Runtime/GUI/Gui.Input.cs @@ -13,17 +13,17 @@ public partial class Gui public event Action OnPointerPosSet; public event Action OnCursorVisibilitySet; - internal readonly bool[] KeyCurState = new bool[KeyValues.Length]; - internal readonly bool[] KeyPreState = new bool[KeyValues.Length]; + internal bool[] KeyCurState = new bool[KeyValues.Length]; + internal bool[] KeyPreState = new bool[KeyValues.Length]; - internal readonly double[] KeyPressedTime = new double[KeyValues.Length]; + internal double[] KeyPressedTime = new double[KeyValues.Length]; internal Key KeyCode = Key.Unknown; - internal readonly bool[] PointerCurState = new bool[MouseValues.Length]; - internal readonly bool[] PointerPreState = new bool[MouseValues.Length]; + internal bool[] PointerCurState = new bool[MouseValues.Length]; + internal bool[] PointerPreState = new bool[MouseValues.Length]; - internal readonly double[] PointerPressedTime = new double[MouseValues.Length]; - internal readonly Vector2[] PointerClickPos = new Vector2[MouseValues.Length]; + internal double[] PointerPressedTime = new double[MouseValues.Length]; + internal Vector2[] PointerClickPos = new Vector2[MouseValues.Length]; internal MouseButton PointerButton = (MouseButton)(-1); public Vector2 PreviousPointerPos = Vector2.zero; @@ -42,8 +42,8 @@ public Vector2 PointerPos public Vector2 PointerDelta => PointerPos - PreviousPointerPos; public bool IsPointerMoving => PointerDelta.sqrMagnitude > 0; - public readonly double[] PointerLastClickTime = new double[MouseValues.Length]; - public readonly Vector2[] PointerLastClickPos = new Vector2[MouseValues.Length]; + public double[] PointerLastClickTime = new double[MouseValues.Length]; + public Vector2[] PointerLastClickPos = new Vector2[MouseValues.Length]; public const double MaxDoubleClickTime = 0.25; private Vector2 frameBufferScale; diff --git a/Prowl.Runtime/GUI/Gui.Interaction.cs b/Prowl.Runtime/GUI/Gui.Interaction.cs index 489b73a75..6db3f21d8 100644 --- a/Prowl.Runtime/GUI/Gui.Interaction.cs +++ b/Prowl.Runtime/GUI/Gui.Interaction.cs @@ -268,7 +268,7 @@ public struct Interactable public double ZIndex => zIndex; private readonly Gui _gui; - internal readonly ulong _id; + internal ulong _id; internal Rect _rect; internal double zIndex; diff --git a/Prowl.Runtime/GUI/GuiDraw2D.cs b/Prowl.Runtime/GUI/GuiDraw2D.cs index 6f3cc4747..7d8e47c45 100644 --- a/Prowl.Runtime/GUI/GuiDraw2D.cs +++ b/Prowl.Runtime/GUI/GuiDraw2D.cs @@ -12,7 +12,7 @@ public class GuiDraw2D { public UIDrawList DrawList => _drawList[currentZIndex]; - internal readonly Dictionary _drawList = new(); + internal Dictionary _drawList = new(); private int currentZIndex => _gui.CurrentZIndex; diff --git a/Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs b/Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs index c11f8ee05..1bd2825d8 100644 --- a/Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs +++ b/Prowl.Runtime/GUI/Layout/LayoutNode.Core.cs @@ -56,8 +56,8 @@ public readonly Vector2 GlobalPosition // Keep the Scrolls cached public double VScroll = node.VScroll; public double HScroll = node.HScroll; - public readonly bool ShowVScroll = node._showVScroll; - public readonly bool ShowHScroll = node._showHScroll; + public bool ShowVScroll = node._showVScroll; + public bool ShowHScroll = node._showHScroll; } public bool HasLayoutData => _data._node == this; @@ -126,7 +126,7 @@ public double HScroll internal int ZIndex = 0; - internal readonly List Children = new List(); + internal List Children = new List(); public LayoutNode(LayoutNode? parent, Gui gui, ulong storageHash) { diff --git a/Prowl.Runtime/GUI/Layout/Offset.cs b/Prowl.Runtime/GUI/Layout/Offset.cs index 4f54e2053..f8f51c3c4 100644 --- a/Prowl.Runtime/GUI/Layout/Offset.cs +++ b/Prowl.Runtime/GUI/Layout/Offset.cs @@ -11,9 +11,9 @@ public struct Offset private bool isLerp = false; - public readonly double Value; + public double Value; public double PixelOffset; - public readonly LayoutValueType Type; + public LayoutValueType Type; private double _lerpValue; private double _lerpPixelOffset; diff --git a/Prowl.Runtime/GUI/Layout/Size.cs b/Prowl.Runtime/GUI/Layout/Size.cs index 05ee847dc..70f2b95aa 100644 --- a/Prowl.Runtime/GUI/Layout/Size.cs +++ b/Prowl.Runtime/GUI/Layout/Size.cs @@ -11,9 +11,9 @@ public struct Size private bool isLerp = false; - public readonly double Value; - public readonly double PixelOffset; - public readonly LayoutValueType Type; + public double Value; + public double PixelOffset; + public LayoutValueType Type; private double _lerpValue; private double _lerpPixelOffset; diff --git a/Prowl.Runtime/GUI/Layout/Spacing.cs b/Prowl.Runtime/GUI/Layout/Spacing.cs index e5e2e50e6..7cac19637 100644 --- a/Prowl.Runtime/GUI/Layout/Spacing.cs +++ b/Prowl.Runtime/GUI/Layout/Spacing.cs @@ -8,10 +8,10 @@ namespace Prowl.Runtime.GUI; public struct Spacing { - public readonly double Left; - public readonly double Right; - public readonly double Top; - public readonly double Bottom; + public double Left; + public double Right; + public double Top; + public double Bottom; public readonly double Horizontal => Left + Right; public readonly double Vertical => Top + Bottom; diff --git a/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs b/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs index d8d18d05a..50496102f 100644 --- a/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs +++ b/Prowl.Runtime/GUI/TextEdit/StbTextEdit.cs @@ -55,7 +55,7 @@ public float GetWidth(int index) public int SelectEnd; public int SelectStart; public bool SingleLine; - public readonly UndoState UndoData = new(); + public UndoState UndoData = new(); } public static class StbTextEdit @@ -849,10 +849,10 @@ public class UndoState { public int redo_char_point; public short redo_point; - public readonly int[] undo_char = new int[999]; + public int[] undo_char = new int[999]; public int undo_char_point; public short undo_point; - public readonly UndoRecord[] undo_rec = new UndoRecord[99]; + public UndoRecord[] undo_rec = new UndoRecord[99]; public void FlushRedo() { diff --git a/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs b/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs index 825e9386c..0a0aa5dd7 100644 --- a/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs +++ b/Prowl.Runtime/GUI/Widgets/Gizmo/TransformGizmo.cs @@ -83,8 +83,8 @@ public class TransformGizmo public bool IsOver => hoveredGizmo != null || focusedGizmo != null; public Rect Viewport; - public readonly double GizmoSize = 75.0; - public readonly double StrokeWidth = 4.0; + public double GizmoSize = 75.0; + public double StrokeWidth = 4.0; public Vector3 ViewForward; public Vector3 ViewUp; @@ -110,7 +110,7 @@ public enum GizmoOrientation { Global, Local } // internal Matrix4x4 InverseModelViewProjection; private readonly List _subGizmos = []; - internal readonly Gui _gui; + internal Gui _gui; internal TransformGizmoMode mode; private ISubGizmo? hoveredGizmo; diff --git a/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs b/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs index e83063ed8..82df3ecdb 100644 --- a/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs +++ b/Prowl.Runtime/GUI/Widgets/Gui.InputField.cs @@ -37,8 +37,8 @@ public struct WidgetStyle public float BorderThickness; public float Roundness; public AssetRef Font; - public readonly float FontSize; - public readonly float ItemSize; + public float FontSize; + public float ItemSize; public WidgetStyle(float itemSize) { diff --git a/Prowl.Runtime/GameObject/Attributes/InspectorUIAttribute.cs b/Prowl.Runtime/GameObject/Attributes/InspectorUIAttribute.cs index 128e025db..256872e45 100644 --- a/Prowl.Runtime/GameObject/Attributes/InspectorUIAttribute.cs +++ b/Prowl.Runtime/GameObject/Attributes/InspectorUIAttribute.cs @@ -23,7 +23,7 @@ public class SpaceAttribute : Attribute, InspectorUIAttribute [AttributeUsage(T.Field, AllowMultiple = true)] public class TextAttribute(string text) : Attribute, InspectorUIAttribute { - public readonly string text = text; + public string text = text; public GuiAttribType AttribType() => GuiAttribType.Text; } @@ -36,22 +36,22 @@ public class SeparatorAttribute : Attribute, InspectorUIAttribute [AttributeUsage(T.Field, AllowMultiple = false)] public class TooltipAttribute(string text) : Attribute, InspectorUIAttribute { - public readonly string tooltip = text; + public string tooltip = text; public GuiAttribType AttribType() => GuiAttribType.Tooltip; } [AttributeUsage(T.Field | T.Property, AllowMultiple = false)] public class ShowIfAttribute(string propertyName, bool inverted = false) : Attribute, InspectorUIAttribute { - public readonly string propertyName = propertyName; - public readonly bool inverted = inverted; + public string propertyName = propertyName; + public bool inverted = inverted; public GuiAttribType AttribType() => GuiAttribType.ShowIf; } [AttributeUsage(T.Method, AllowMultiple = false)] public class GUIButtonAttribute(string text) : Attribute { - public readonly string buttonText = text; + public string buttonText = text; } [AttributeUsage(T.Field, AllowMultiple = false)] diff --git a/Prowl.Runtime/GameObject/TagLayerManager.cs b/Prowl.Runtime/GameObject/TagLayerManager.cs index 1a622bb8f..f375241ec 100644 --- a/Prowl.Runtime/GameObject/TagLayerManager.cs +++ b/Prowl.Runtime/GameObject/TagLayerManager.cs @@ -12,7 +12,7 @@ namespace Prowl.Runtime; [FilePath("TagAndLayers.setting", FilePathAttribute.Location.Setting)] public class TagLayerManager : ScriptableSingleton { - public readonly List tags = + public List tags = [ "Untagged", "Main Camera", @@ -23,7 +23,7 @@ public class TagLayerManager : ScriptableSingleton "Game Controller" ]; - public readonly string[] layers = + public string[] layers = [ "Default", "TransparentFX", diff --git a/Prowl.Runtime/Physics.cs b/Prowl.Runtime/Physics.cs index 88e230a81..ec625aa5d 100644 --- a/Prowl.Runtime/Physics.cs +++ b/Prowl.Runtime/Physics.cs @@ -24,12 +24,12 @@ namespace Prowl.Runtime; public class PhysicsSetting : ScriptableSingleton { public Vector3 Gravity = new Vector3(0, -9.81f, 0); - public readonly int Iterations = 8; - public readonly int Substep = 1; - public readonly int TargetFrameRate = 50; - public readonly bool UseMultithreading = true; - public readonly bool EnhancedDeterminism = false; - public readonly bool AutoSyncTransforms = true; + public int Iterations = 8; + public int Substep = 1; + public int TargetFrameRate = 50; + public bool UseMultithreading = true; + public bool EnhancedDeterminism = false; + public bool AutoSyncTransforms = true; } diff --git a/Prowl.Runtime/Rendering/CommandBuffer.cs b/Prowl.Runtime/Rendering/CommandBuffer.cs index bd17a57da..1e37084a4 100644 --- a/Prowl.Runtime/Rendering/CommandBuffer.cs +++ b/Prowl.Runtime/Rendering/CommandBuffer.cs @@ -12,7 +12,7 @@ public class CommandBuffer : IDisposable { private static Material s_blit; - internal readonly CommandList _commandList; + internal CommandList _commandList; private bool _isRecording = false; private Framebuffer _activeFramebuffer; diff --git a/Prowl.Runtime/Rendering/Material.cs b/Prowl.Runtime/Rendering/Material.cs index 7621cc913..42a00d945 100644 --- a/Prowl.Runtime/Rendering/Material.cs +++ b/Prowl.Runtime/Rendering/Material.cs @@ -13,10 +13,10 @@ namespace Prowl.Runtime; public sealed class Material : EngineObject { public AssetRef Shader; - public readonly PropertyState Properties; + public PropertyState Properties; [NonSerialized] - public readonly KeywordState LocalKeywords; + public KeywordState LocalKeywords; internal Material() : base("New Material") { diff --git a/Prowl.Runtime/Rendering/PropertyState.cs b/Prowl.Runtime/Rendering/PropertyState.cs index f9658c09c..a689cc35d 100644 --- a/Prowl.Runtime/Rendering/PropertyState.cs +++ b/Prowl.Runtime/Rendering/PropertyState.cs @@ -51,10 +51,10 @@ public class PropertyState public bool IsEmpty => _values.Count == 0 && _buffers.Count == 0; - [SerializeField] internal readonly Dictionary _values; + [SerializeField] internal Dictionary _values; - internal readonly Dictionary _rawTextures; - internal readonly Dictionary _buffers; + internal Dictionary _rawTextures; + internal Dictionary _buffers; diff --git a/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs b/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs index 17a4597e7..cf2858c63 100644 --- a/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs +++ b/Prowl.Runtime/Rendering/RenderPipeline/DefaultRenderPipeline.cs @@ -20,7 +20,7 @@ public class DefaultRenderPipeline : RenderPipeline private static Mesh s_skyDome; private static Texture2D s_whiteTexture; - public static readonly DefaultRenderPipeline Default = new(); + public static DefaultRenderPipeline Default = new(); private static void ValidateDefaults() diff --git a/Prowl.Runtime/Rendering/Shader/ShaderUniform.cs b/Prowl.Runtime/Rendering/Shader/ShaderUniform.cs index 3caee3737..3b73fc940 100644 --- a/Prowl.Runtime/Rendering/Shader/ShaderUniform.cs +++ b/Prowl.Runtime/Rendering/Shader/ShaderUniform.cs @@ -42,9 +42,9 @@ private static string CleanseName(string rawName) public readonly string name; public readonly uint binding; - public readonly uint size; + public uint size; - public readonly ShaderUniformMember[] members; + public ShaderUniformMember[] members; private ShaderUniform() { } diff --git a/Prowl.Runtime/Rendering/Texture/RenderTexture.cs b/Prowl.Runtime/Rendering/Texture/RenderTexture.cs index 3c5f5ce08..be0b7d4ba 100644 --- a/Prowl.Runtime/Rendering/Texture/RenderTexture.cs +++ b/Prowl.Runtime/Rendering/Texture/RenderTexture.cs @@ -12,16 +12,16 @@ namespace Prowl.Runtime; public struct RenderTextureDescription { - public readonly uint width; - public readonly uint height; + public uint width; + public uint height; - public readonly PixelFormat[] colorBufferFormats; + public PixelFormat[] colorBufferFormats; public PixelFormat? depthBufferFormat; - public readonly bool sampled; - public readonly bool enableRandomWrite; + public bool sampled; + public bool enableRandomWrite; - public readonly TextureSampleCount sampleCount; + public TextureSampleCount sampleCount; public RenderTextureDescription( uint width, uint height, diff --git a/Prowl.Runtime/Rendering/Texture/Texture.cs b/Prowl.Runtime/Rendering/Texture/Texture.cs index 6e644721a..21a022b81 100644 --- a/Prowl.Runtime/Rendering/Texture/Texture.cs +++ b/Prowl.Runtime/Rendering/Texture/Texture.cs @@ -37,7 +37,7 @@ public abstract class Texture : EngineObject, ISerializable public bool IsMipmappable => Usage.HasFlag(TextureUsage.GenerateMipmaps); /// The sampler for this - public readonly TextureSampler Sampler = TextureSampler.CreateLinear(); + public TextureSampler Sampler = TextureSampler.CreateLinear(); /// The multisample count of this public TextureSampleCount SampleCount => InternalTexture.SampleCount; diff --git a/Prowl.Runtime/Rendering/Texture/Texture2D.cs b/Prowl.Runtime/Rendering/Texture/Texture2D.cs index 33c912d81..ad7be51f4 100644 --- a/Prowl.Runtime/Rendering/Texture/Texture2D.cs +++ b/Prowl.Runtime/Rendering/Texture/Texture2D.cs @@ -18,10 +18,10 @@ public sealed class Texture2D : Texture /// The height of this . public uint Height => InternalTexture.Height; - public static readonly Texture2D EmptyWhite = CreateDefaultTex(1, 1, [Color.white]); + public static Texture2D EmptyWhite = CreateDefaultTex(1, 1, [Color.white]); - public static readonly Texture2D Empty = CreateDefaultTex(1, 1, [Color.clear]); - public static readonly Texture2D EmptyRW = CreateDefaultTex(1, 1, [Color.black], TextureUsage.Storage); + public static Texture2D Empty = CreateDefaultTex(1, 1, [Color.clear]); + public static Texture2D EmptyRW = CreateDefaultTex(1, 1, [Color.black], TextureUsage.Storage); public static Texture2D Checker => CreateDefaultTex(4, 4, [ Color.white, diff --git a/Prowl.Runtime/SceneManager.cs b/Prowl.Runtime/SceneManager.cs index 3deb07fad..ea9bd36b7 100644 --- a/Prowl.Runtime/SceneManager.cs +++ b/Prowl.Runtime/SceneManager.cs @@ -12,7 +12,7 @@ namespace Prowl.Runtime.SceneManagement; public static class SceneManager { private static readonly List _gameObjects = new(); - internal static readonly HashSet _dontDestroyOnLoad = new(); + internal static HashSet _dontDestroyOnLoad = new(); public static Scene MainScene { get; private set; } = new(); diff --git a/Prowl.Runtime/Serializer/Serializer.cs b/Prowl.Runtime/Serializer/Serializer.cs index dd8ec4b00..cc8f1f9ef 100644 --- a/Prowl.Runtime/Serializer/Serializer.cs +++ b/Prowl.Runtime/Serializer/Serializer.cs @@ -42,11 +42,11 @@ public static class Serializer { public class SerializationContext { - public readonly Dictionary objectToId = new(ReferenceEqualityComparer.Instance); - public readonly Dictionary idToObject = []; + public Dictionary objectToId = new(ReferenceEqualityComparer.Instance); + public Dictionary idToObject = []; public int nextId = 1; private int dependencyCounter = 0; - public readonly HashSet dependencies = []; + public HashSet dependencies = []; public SerializationContext() { diff --git a/Prowl.Runtime/Utils/NodeSystem/Node.cs b/Prowl.Runtime/Utils/NodeSystem/Node.cs index af3c3fa42..0e88f7651 100644 --- a/Prowl.Runtime/Utils/NodeSystem/Node.cs +++ b/Prowl.Runtime/Utils/NodeSystem/Node.cs @@ -260,11 +260,11 @@ public void ClearConnections() [AttributeUsage(AttributeTargets.Field)] public class InputAttribute : Attribute { - public readonly ShowBackingValue backingValue; - public readonly ConnectionType connectionType; - public readonly bool dynamicPortList; - public readonly TypeConstraint typeConstraint; - public readonly bool onHeader; + public ShowBackingValue backingValue; + public ConnectionType connectionType; + public bool dynamicPortList; + public TypeConstraint typeConstraint; + public bool onHeader; /// Mark a serializable field as an input port. You can access this through /// Should we display the backing value for this port as an editor field? @@ -286,10 +286,10 @@ public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnect [AttributeUsage(AttributeTargets.Field)] public class OutputAttribute : Attribute { - public readonly ConnectionType connectionType; - public readonly bool dynamicPortList; - public readonly TypeConstraint typeConstraint; - public readonly bool onHeader; + public ConnectionType connectionType; + public bool dynamicPortList; + public TypeConstraint typeConstraint; + public bool onHeader; /// Mark a serializable field as an output port. You can access this through /// Should we allow multiple connections? @@ -308,9 +308,9 @@ public OutputAttribute(ConnectionType connectionType = ConnectionType.Multiple, [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class NodeAttribute(string menuName) : Attribute { - public readonly string catagory = menuName; + public string catagory = menuName; - public static readonly MultiValueDictionary nodeCatagories = new MultiValueDictionary(); + public static MultiValueDictionary nodeCatagories = new MultiValueDictionary(); [OnAssemblyLoad] public static void OnAssemblyLoad() @@ -337,7 +337,7 @@ public static void OnAssemblyUnload() [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class DisallowMultipleNodesAttribute : Attribute { - public readonly int max; + public int max; /// Prevents Node of the same type to be added more than once (configurable) to a NodeGraph /// How many nodes to allow. Defaults to 1. public DisallowMultipleNodesAttribute(int max = 1) diff --git a/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs b/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs index 1c71dacc6..ee97e3eaa 100644 --- a/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs +++ b/Prowl.Runtime/Utils/NodeSystem/NodeGraph.cs @@ -41,13 +41,13 @@ public abstract class NodeGraph : ScriptableObject, ISerializationCallbackReceiv /// All nodes in the graph. /// See: - public readonly List nodes = []; + public List nodes = []; public virtual (string, Type)[] NodeTypes { get; } = []; public virtual (string, Type)[] NodeReflectionTypes { get; } = []; public abstract string[] NodeCategories { get; } - public readonly List parameters = []; + public List parameters = []; public void Validate() { @@ -196,7 +196,7 @@ public override void OnAfterDeserialize() [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class RequireNodeAttribute(params Type[] type) : Attribute { - public readonly Type[] types = type; + public Type[] types = type; public bool Requires(Type type) { diff --git a/Prowl.Runtime/Utils/NodeSystem/Nodes/Flow Control/ForLoopNode.cs b/Prowl.Runtime/Utils/NodeSystem/Nodes/Flow Control/ForLoopNode.cs index 02d4d7b3b..a1769377d 100644 --- a/Prowl.Runtime/Utils/NodeSystem/Nodes/Flow Control/ForLoopNode.cs +++ b/Prowl.Runtime/Utils/NodeSystem/Nodes/Flow Control/ForLoopNode.cs @@ -17,8 +17,8 @@ public class ForLoopNode : InOutFlowNode [Output, SerializeIgnore] public int Index; - [Input] public readonly int FirstIndex = 0; - [Input] public readonly int LastIndex = 10; + [Input] public int FirstIndex = 0; + [Input] public int LastIndex = 10; private int currentIndex; diff --git a/Prowl.Runtime/Utils/NodeSystem/Nodes/Operations/String Nodes.cs b/Prowl.Runtime/Utils/NodeSystem/Nodes/Operations/String Nodes.cs index 7deff4d71..f6bc92cb1 100644 --- a/Prowl.Runtime/Utils/NodeSystem/Nodes/Operations/String Nodes.cs +++ b/Prowl.Runtime/Utils/NodeSystem/Nodes/Operations/String Nodes.cs @@ -43,7 +43,7 @@ public class String_Contains_Node : Node [Output, SerializeIgnore] public bool Contains; - public readonly System.StringComparison Mode = System.StringComparison.Ordinal; + public System.StringComparison Mode = System.StringComparison.Ordinal; public override object GetValue(NodePort port) => GetInputValue("In", In).Contains(GetInputValue("Has", Has), Mode); } @@ -59,7 +59,7 @@ public class String_StartsWith_Node : Node [Output, SerializeIgnore] public string Result; - public readonly System.StringComparison Mode = System.StringComparison.Ordinal; + public System.StringComparison Mode = System.StringComparison.Ordinal; public override object GetValue(NodePort port) => GetInputValue("In", In).StartsWith(GetInputValue("StartsWith", StartsWith), Mode); } @@ -75,7 +75,7 @@ public class String_EndsWith_Node : Node [Output, SerializeIgnore] public string Result; - public readonly System.StringComparison Mode = System.StringComparison.Ordinal; + public System.StringComparison Mode = System.StringComparison.Ordinal; public override object GetValue(NodePort port) => GetInputValue("In", In).EndsWith(GetInputValue("EndsWith", EndsWith), Mode); } @@ -199,7 +199,7 @@ public class String_IsEqual_Node : Node [Output, SerializeIgnore] public bool IsEqual; - public readonly System.StringComparison Mode = System.StringComparison.Ordinal; + public System.StringComparison Mode = System.StringComparison.Ordinal; public override object GetValue(NodePort port) => GetInputValue("A", A).Equals(GetInputValue("B", B), Mode); } diff --git a/Prowl.Runtime/Utils/NodeSystem/PortTypeOverrideAttribute.cs b/Prowl.Runtime/Utils/NodeSystem/PortTypeOverrideAttribute.cs index 9d0bfaffc..b0a0e872d 100644 --- a/Prowl.Runtime/Utils/NodeSystem/PortTypeOverrideAttribute.cs +++ b/Prowl.Runtime/Utils/NodeSystem/PortTypeOverrideAttribute.cs @@ -10,7 +10,7 @@ namespace Prowl.Runtime.NodeSystem; [AttributeUsage(AttributeTargets.Field)] public class PortTypeOverrideAttribute : Attribute { - public readonly Type type; + public Type type; /// Overrides the ValueType of the Port /// ValueType of the Port public PortTypeOverrideAttribute(Type type) diff --git a/Prowl.Runtime/Utils/SerializedAsset.cs b/Prowl.Runtime/Utils/SerializedAsset.cs index bb588abdb..8a8af1a46 100644 --- a/Prowl.Runtime/Utils/SerializedAsset.cs +++ b/Prowl.Runtime/Utils/SerializedAsset.cs @@ -12,7 +12,7 @@ namespace Prowl.Runtime.Utils; public class SerializedAsset { public EngineObject? Main; - public readonly List SubAssets = new(); + public List SubAssets = new(); [SerializeIgnore] public Guid Guid; diff --git a/Prowl.Runtime/Utils/Tokenizer.cs b/Prowl.Runtime/Utils/Tokenizer.cs index fd79e9328..2c570a715 100644 --- a/Prowl.Runtime/Utils/Tokenizer.cs +++ b/Prowl.Runtime/Utils/Tokenizer.cs @@ -18,8 +18,8 @@ public class Tokenizer public int CurrentLine { get; set; } = 1; public int CurrentColumn { get; set; } - public readonly Func IsWhitespace; - public readonly Func IsQuote; + public Func IsWhitespace; + public Func IsQuote; public Tokenizer(ReadOnlyMemory input, Func? isWhitespace = null, Func? isQuote = null) {