From 162b71f3097fe1f433859a9b8985cbd1f455970b Mon Sep 17 00:00:00 2001 From: Misaki Date: Wed, 25 Feb 2026 19:08:54 +0900 Subject: [PATCH] Refactor render graph error handling and resource APIs - RenderGraph.Compile/Execute now return Error for better failure detection; error handling is propagated throughout compiler and executor. - Renamed ScheduleReleaseResource to ReleaseResource for clarity; updated all usages. - ResourceManager now calls ReleaseResource directly on Mesh, Material, and Shader types. - Camera exposes Actual/Virtual size properties and Render returns Error. - RenderingContext now uses IResourceManager for mesh/resource ops. - Replaced custom BinaryWriter with BufferWriter in RenderGraphHasher. - Improved variable naming, interface signatures, and code formatting. - Added Error extension for IsSuccess/IsFailure. - Minor FMOD/native interop and test code cleanups. - No breaking API changes except for new Error return values on some methods. --- .../ShaderCompiler/DSLShaderCompiler.cs | 3 +- .../Ghost.DSL/ShaderParser/ShaderVisitor.cs | 2 +- .../AssetHandler/TextureAsset.cs | 15 +-- .../Contracts/IInspectable.cs | 6 +- .../Contracts/INavigationAware.cs | 4 +- .../Contracts/INotificationService.cs | 4 +- .../Contracts/IProgressService.cs | 8 +- .../Controls/Menu/ContextFlyout.cs | 3 +- src/Editor/Ghost.Editor/ActivationHandler.cs | 3 - src/Editor/Ghost.Editor/App.xaml.cs | 1 - .../Ghost.Editor/Models/LaunchArguments.cs | 2 +- .../Vector3ToQuaternionConverter.cs | 2 - .../View/Controls/Hierarchy.xaml.cs | 13 -- .../View/Controls/ProjectBrowser.Menu.cs | 2 +- .../View/Windows/EngineEditorWindow.xaml.cs | 1 - .../Controls/ProjectBrowserViewModel.cs | 1 - .../Pages/EngineEditor/HierarchyViewModel.cs | 2 - .../Pages/EngineEditor/ProjectViewModel.cs | 2 - src/Runtime/Ghost.Core/Handle.cs | 16 +-- src/Runtime/Ghost.Core/Result.cs | 14 +- .../Ghost.Core/Utilities/BinaryWriter.cs | 41 ------ .../Ghost.Core/Utilities/BufferWriter.cs | 53 ++++++++ .../Ghost.Core/Utilities/EnumUtility.cs | 4 - src/Runtime/Ghost.Core/Utilities/Hash.cs | 18 +-- .../Ghost.Core/Utilities/Win32Utility.cs | 2 - .../Ghost.Engine/Resources/EngineData.cs | 2 +- src/Runtime/Ghost.Entities/Archetype.cs | 18 +-- src/Runtime/Ghost.Entities/Component.cs | 2 +- src/Runtime/Ghost.Entities/Query.cs | 2 +- src/Runtime/Ghost.Entities/System.cs | 6 +- .../Templates/EntityQuery.ForEach.gen.cs | 32 ++--- .../Templates/EntityQuery.JobEntity.gen.cs | 16 +-- .../ComponentRegistrationGenerator.cs | 12 +- .../D3D12CommandAllocator.cs | 1 - .../D3D12CommandBuffer.cs | 50 ++++++- .../Ghost.Graphics.D3D12/D3D12CommandQueue.cs | 1 - .../Ghost.Graphics.D3D12/D3D12DebugLayer.cs | 2 - .../D3D12DescriptorAllocator.cs | 2 +- .../D3D12ResourceAllocator.cs | 10 +- .../D3D12ResourceDatabase.cs | 3 +- .../Ghost.Graphics.D3D12/D3D12SwapChain.cs | 2 +- src/Runtime/Ghost.Graphics.RHI/Common.cs | 4 +- .../Ghost.Graphics.RHI/ICommandQueue.cs | 14 +- .../Ghost.Graphics.RHI/IRenderDevice.cs | 8 +- .../Ghost.Graphics.RHI/IResourceAllocator.cs | 2 - .../Ghost.Graphics.RHI/IResourceDatabase.cs | 2 +- src/Runtime/Ghost.Graphics/Core/Camera.cs | 17 ++- src/Runtime/Ghost.Graphics/Core/Material.cs | 9 +- src/Runtime/Ghost.Graphics/Core/Mesh.cs | 8 +- .../Ghost.Graphics/Core/RenderingContext.cs | 15 ++- src/Runtime/Ghost.Graphics/Core/Shader.cs | 8 +- .../GPUResourceLeakException.cs | 2 - .../RenderGraphModule/RenderGraph.cs | 23 ++-- .../RenderGraphModule/RenderGraphAliasing.cs | 26 ++-- .../RenderGraphModule/RenderGraphBarriers.cs | 11 +- .../RenderGraphModule/RenderGraphBuilder.cs | 6 +- .../RenderGraphCompilationCache.cs | 20 +-- .../RenderGraphModule/RenderGraphCompiler.cs | 71 +++++----- .../RenderGraphModule/RenderGraphContext.cs | 4 +- .../RenderGraphModule/RenderGraphExecutor.cs | 44 +++++-- .../RenderGraphModule/RenderGraphHasher.cs | 123 ++++++------------ .../RenderGraphNativePass.cs | 14 +- .../RenderGraphModule/RenderGraphPass.cs | 2 +- .../RenderGraphResourcePool.cs | 29 ++--- .../RenderGraphModule/RenderGraphTypes.cs | 43 +++--- .../RenderPasses/MeshRenderPass.cs | 10 +- src/Runtime/Ghost.Graphics/ResourceManager.cs | 25 ++-- .../Ghost.Entities.Test/EntityQueryTest.cs | 2 +- src/Test/Ghost.Entities.Test/Program.cs | 2 - src/Test/Ghost.Entities.Test/SystemTest.cs | 2 +- .../Controls/DebugConsole.xaml.cs | 4 +- .../Windows/GraphicsTestWindow.xaml.cs | 1 - src/Test/Ghost.MicroTest/NvttBindingTest.cs | 42 +++--- src/Test/Ghost.MicroTest/Program.cs | 2 +- src/Test/Ghost.Shader.Test/Program.cs | 1 - src/Test/Ghost.Test.Core/ITest.cs | 6 +- .../AssetDatabaseIntegrationTest.cs | 4 +- src/Test/Ghost.UnitTest/AssetMetaTest.cs | 2 - src/ThridParty/Ghost.FMOD/Core/fmod.cs | 28 ++-- .../Ghost.FMOD/Studio/fmod_studio.cs | 51 +++----- .../Ghost.MeshOptimizer/meshopt_Allocator.cs | 1 - .../Ghost.MeshOptimizer/meshopt_Bounds.cs | 1 - .../meshopt_CoverageStatistics.cs | 1 - .../Ghost.MeshOptimizer/meshopt_Meshlet.cs | 2 - .../meshopt_OverdrawStatistics.cs | 2 - .../Ghost.MeshOptimizer/meshopt_Stream.cs | 2 - .../meshopt_VertexCacheStatistics.cs | 2 - .../meshopt_VertexFetchStatistics.cs | 2 - .../Native/NativeAnnotationAttribute.cs | 1 - .../Native/NativeTypeNameAttribute.cs | 1 - .../Ghost.Nvtt/NvttOutputOptions.cs | 24 ++-- src/ThridParty/Ghost.Nvtt/NvttSurface.cs | 19 ++- .../Ghost.Nvtt/NvttTimingContext.cs | 2 +- 93 files changed, 537 insertions(+), 593 deletions(-) delete mode 100644 src/Runtime/Ghost.Core/Utilities/BinaryWriter.cs create mode 100644 src/Runtime/Ghost.Core/Utilities/BufferWriter.cs diff --git a/src/Editor/Ghost.DSL/ShaderCompiler/DSLShaderCompiler.cs b/src/Editor/Ghost.DSL/ShaderCompiler/DSLShaderCompiler.cs index 31a2d3b..cdf67a3 100644 --- a/src/Editor/Ghost.DSL/ShaderCompiler/DSLShaderCompiler.cs +++ b/src/Editor/Ghost.DSL/ShaderCompiler/DSLShaderCompiler.cs @@ -1,7 +1,6 @@ using Ghost.Core; using Ghost.Core.Graphics; using Ghost.DSL.ShaderParser; -using System.Runtime.CompilerServices; using System.Text; namespace Ghost.DSL.ShaderCompiler; @@ -107,7 +106,7 @@ internal static class DSLShaderCompiler if (semantics.passes != null) { descriptor.passes = new PassDescriptor[semantics.passes.Count]; - for (int i = 0; i < semantics.passes.Count; i++) + for (var i = 0; i < semantics.passes.Count; i++) { var pass = semantics.passes[i]; var localPipeline = MeragePipeline(pass.localPipeline, PipelineState.Default); diff --git a/src/Editor/Ghost.DSL/ShaderParser/ShaderVisitor.cs b/src/Editor/Ghost.DSL/ShaderParser/ShaderVisitor.cs index 34f13cd..0a10370 100644 --- a/src/Editor/Ghost.DSL/ShaderParser/ShaderVisitor.cs +++ b/src/Editor/Ghost.DSL/ShaderParser/ShaderVisitor.cs @@ -205,7 +205,7 @@ public class ShaderVisitor : GhostShaderParserBaseVisitor // Get the text between the braces var start = context.LBRACE().Symbol.StopIndex + 1; var stop = context.RBRACE().Symbol.StartIndex - 1; - + if (stop >= start) { var input = context.Start.InputStream; diff --git a/src/Editor/Ghost.Editor.Core/AssetHandler/TextureAsset.cs b/src/Editor/Ghost.Editor.Core/AssetHandler/TextureAsset.cs index adfdc52..762328e 100644 --- a/src/Editor/Ghost.Editor.Core/AssetHandler/TextureAsset.cs +++ b/src/Editor/Ghost.Editor.Core/AssetHandler/TextureAsset.cs @@ -1,13 +1,10 @@ using Ghost.Core; using Ghost.Editor.Core.Contracts; -using Ghost.Graphics.Core; using Ghost.Graphics.RHI; using Misaki.HighPerformance.Image; using System.Buffers; -using System.Configuration; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using TerraFX.Interop.Windows; using static Ghost.Editor.Core.AssetHandler.TextureAssetSettings; namespace Ghost.Editor.Core.AssetHandler; @@ -150,7 +147,7 @@ public class TextureAssetSettings : IAssetSettings { get; set; } = new Color128(0, 0, 0, 0); - + public bool ZeroAlphaBorder { get; set; @@ -228,7 +225,7 @@ internal class TextureAssetHandler : IImportableAssetHandler try { - ref byte address = ref MemoryMarshal.GetReference(tempArray); + ref var address = ref MemoryMarshal.GetReference(tempArray); Unsafe.WriteUnaligned(ref address, settings.Basic); Unsafe.WriteUnaligned(ref Unsafe.Add(ref address, Unsafe.SizeOf()), settings.Advanced); Unsafe.WriteUnaligned(ref Unsafe.Add(ref address, Unsafe.SizeOf() + Unsafe.SizeOf()), settings.Sampler); @@ -295,8 +292,8 @@ internal class TextureAssetHandler : IImportableAssetHandler } var isFloat = info.BitsPerChannel > 8; - var width = info.Width; - var height = info.Height; + var width = info.Width; + var height = info.Height; var colorComponents = info.ColorComponents; // ---- 2. Decode pixels into a managed byte[] ---------------------------- @@ -356,9 +353,9 @@ internal class TextureAssetHandler : IImportableAssetHandler // byte[] pixelBytes const int _CONTENT_HEADER_SIZE = 4 + 4 + 1 + 4; // 13 bytes - header.SettingsSize = sizeResult.Value; + header.SettingsSize = sizeResult.Value; header.ContentOffset = header.SettingsOffset + sizeResult.Value; - header.ContentSize = _CONTENT_HEADER_SIZE + pixelBytes.Length; + header.ContentSize = _CONTENT_HEADER_SIZE + pixelBytes.Length; // Write raw image content targetStream.Seek(header.ContentOffset, SeekOrigin.Begin); diff --git a/src/Editor/Ghost.Editor.Core/Contracts/IInspectable.cs b/src/Editor/Ghost.Editor.Core/Contracts/IInspectable.cs index 16cf03b..d3b9dcc 100644 --- a/src/Editor/Ghost.Editor.Core/Contracts/IInspectable.cs +++ b/src/Editor/Ghost.Editor.Core/Contracts/IInspectable.cs @@ -5,9 +5,9 @@ namespace Ghost.Editor.Core.Contracts; public interface IInspectable { - public IconSource? CreateIcon(); + IconSource? CreateIcon(); - public UIElement? CreateHeader(); + UIElement? CreateHeader(); - public UIElement? CreateInspector(); + UIElement? CreateInspector(); } \ No newline at end of file diff --git a/src/Editor/Ghost.Editor.Core/Contracts/INavigationAware.cs b/src/Editor/Ghost.Editor.Core/Contracts/INavigationAware.cs index 5066f32..8528f58 100644 --- a/src/Editor/Ghost.Editor.Core/Contracts/INavigationAware.cs +++ b/src/Editor/Ghost.Editor.Core/Contracts/INavigationAware.cs @@ -2,6 +2,6 @@ namespace Ghost.Editor.Core.Contracts; public interface INavigationAware { - public void OnNavigatedTo(object? parameter); - public void OnNavigatedFrom(); + void OnNavigatedTo(object? parameter); + void OnNavigatedFrom(); } \ No newline at end of file diff --git a/src/Editor/Ghost.Editor.Core/Contracts/INotificationService.cs b/src/Editor/Ghost.Editor.Core/Contracts/INotificationService.cs index f96a633..f5e267b 100644 --- a/src/Editor/Ghost.Editor.Core/Contracts/INotificationService.cs +++ b/src/Editor/Ghost.Editor.Core/Contracts/INotificationService.cs @@ -5,6 +5,6 @@ namespace Ghost.Editor.Core.Contracts; public interface INotificationService { - public void ShowNotification(string? message, MessageType type, int duration = 5, string? title = null); - public void ShowNotification(Notification notification); + void ShowNotification(string? message, MessageType type, int duration = 5, string? title = null); + void ShowNotification(Notification notification); } diff --git a/src/Editor/Ghost.Editor.Core/Contracts/IProgressService.cs b/src/Editor/Ghost.Editor.Core/Contracts/IProgressService.cs index 3cb8a3a..9b2061f 100644 --- a/src/Editor/Ghost.Editor.Core/Contracts/IProgressService.cs +++ b/src/Editor/Ghost.Editor.Core/Contracts/IProgressService.cs @@ -2,8 +2,8 @@ namespace Ghost.Editor.Core.Contracts; public interface IProgressService { - public void ShowProgress(string message, double progress = 0.0); - public void ShowIndeterminateProgress(string message); - public void SetProgress(double progress); - public void HideProgress(); + void ShowProgress(string message, double progress = 0.0); + void ShowIndeterminateProgress(string message); + void SetProgress(double progress); + void HideProgress(); } \ No newline at end of file diff --git a/src/Editor/Ghost.Editor.Core/Controls/Menu/ContextFlyout.cs b/src/Editor/Ghost.Editor.Core/Controls/Menu/ContextFlyout.cs index 1dd633b..29a6694 100644 --- a/src/Editor/Ghost.Editor.Core/Controls/Menu/ContextFlyout.cs +++ b/src/Editor/Ghost.Editor.Core/Controls/Menu/ContextFlyout.cs @@ -1,7 +1,6 @@ using Ghost.Editor.Core.Utilities; using Microsoft.UI.Xaml.Controls; using System.Reflection; -using System.Runtime.InteropServices; namespace Ghost.Editor.Core.Controls; @@ -93,7 +92,7 @@ public sealed partial class ContextFlyout : MenuFlyout return; } - int currentGroup = nodes[0].EffectiveGroup; + var currentGroup = nodes[0].EffectiveGroup; foreach (var node in nodes) { diff --git a/src/Editor/Ghost.Editor/ActivationHandler.cs b/src/Editor/Ghost.Editor/ActivationHandler.cs index 94a7045..5c8b31b 100644 --- a/src/Editor/Ghost.Editor/ActivationHandler.cs +++ b/src/Editor/Ghost.Editor/ActivationHandler.cs @@ -1,9 +1,6 @@ -using Ghost.Editor.Core; -using Ghost.Editor.Core.Contracts; using Ghost.Editor.Core.Utilities; using Ghost.Editor.Models; using Ghost.Engine; -using Microsoft.UI.Xaml; using System.Reflection; namespace Ghost.Editor; diff --git a/src/Editor/Ghost.Editor/App.xaml.cs b/src/Editor/Ghost.Editor/App.xaml.cs index f14ff4c..f76e075 100644 --- a/src/Editor/Ghost.Editor/App.xaml.cs +++ b/src/Editor/Ghost.Editor/App.xaml.cs @@ -1,6 +1,5 @@ using Ghost.Core; using Ghost.Editor.Core; -using Ghost.Editor.Core.AssetHandle; using Ghost.Editor.Core.Contracts; using Ghost.Editor.Core.Services; using Ghost.Editor.View.Pages.EngineEditor; diff --git a/src/Editor/Ghost.Editor/Models/LaunchArguments.cs b/src/Editor/Ghost.Editor/Models/LaunchArguments.cs index 630dbeb..e7efa29 100644 --- a/src/Editor/Ghost.Editor/Models/LaunchArguments.cs +++ b/src/Editor/Ghost.Editor/Models/LaunchArguments.cs @@ -5,7 +5,7 @@ internal sealed class ArgumentNameAttribute : Attribute { public string Name { - get; + get; } public ArgumentNameAttribute(string name) diff --git a/src/Editor/Ghost.Editor/Utilities/Converters/Vector3ToQuaternionConverter.cs b/src/Editor/Ghost.Editor/Utilities/Converters/Vector3ToQuaternionConverter.cs index 4c930d5..822e051 100644 --- a/src/Editor/Ghost.Editor/Utilities/Converters/Vector3ToQuaternionConverter.cs +++ b/src/Editor/Ghost.Editor/Utilities/Converters/Vector3ToQuaternionConverter.cs @@ -1,7 +1,5 @@ -using Ghost.Engine.Utilities; using Microsoft.UI.Xaml.Data; using Misaki.HighPerformance.Mathematics; -using System.Numerics; namespace Ghost.Editor.Utilities.Converters; diff --git a/src/Editor/Ghost.Editor/View/Controls/Hierarchy.xaml.cs b/src/Editor/Ghost.Editor/View/Controls/Hierarchy.xaml.cs index 3ef3073..dc7fe48 100644 --- a/src/Editor/Ghost.Editor/View/Controls/Hierarchy.xaml.cs +++ b/src/Editor/Ghost.Editor/View/Controls/Hierarchy.xaml.cs @@ -1,17 +1,4 @@ -using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Controls.Primitives; -using Microsoft.UI.Xaml.Data; -using Microsoft.UI.Xaml.Input; -using Microsoft.UI.Xaml.Media; -using Microsoft.UI.Xaml.Navigation; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Foundation.Collections; // To learn more about WinUI, the WinUI project structure, // and more about our project templates, see: http://aka.ms/winui-project-info. diff --git a/src/Editor/Ghost.Editor/View/Controls/ProjectBrowser.Menu.cs b/src/Editor/Ghost.Editor/View/Controls/ProjectBrowser.Menu.cs index 9782fae..f825dcc 100644 --- a/src/Editor/Ghost.Editor/View/Controls/ProjectBrowser.Menu.cs +++ b/src/Editor/Ghost.Editor/View/Controls/ProjectBrowser.Menu.cs @@ -31,7 +31,7 @@ internal partial class ProjectBrowser { return; } - + var currentDir = viewModel.CurrentDirectoryPath; if (!Directory.Exists(currentDir)) { diff --git a/src/Editor/Ghost.Editor/View/Windows/EngineEditorWindow.xaml.cs b/src/Editor/Ghost.Editor/View/Windows/EngineEditorWindow.xaml.cs index c02ff94..a0f8668 100644 --- a/src/Editor/Ghost.Editor/View/Windows/EngineEditorWindow.xaml.cs +++ b/src/Editor/Ghost.Editor/View/Windows/EngineEditorWindow.xaml.cs @@ -2,7 +2,6 @@ using Ghost.Editor.Core; using Ghost.Editor.Core.Contracts; using Ghost.Editor.Core.Services; using Ghost.Editor.ViewModels.Windows; -using System.Diagnostics; using Windows.ApplicationModel; using WinUIEx; diff --git a/src/Editor/Ghost.Editor/ViewModels/Controls/ProjectBrowserViewModel.cs b/src/Editor/Ghost.Editor/ViewModels/Controls/ProjectBrowserViewModel.cs index cb61fb2..c2912d9 100644 --- a/src/Editor/Ghost.Editor/ViewModels/Controls/ProjectBrowserViewModel.cs +++ b/src/Editor/Ghost.Editor/ViewModels/Controls/ProjectBrowserViewModel.cs @@ -1,6 +1,5 @@ using CommunityToolkit.Mvvm.ComponentModel; using Ghost.Editor.Core; -using Ghost.Editor.Core.AssetHandle; using Ghost.Editor.Core.Contracts; using Ghost.Editor.Core.Utilities; using Ghost.Editor.Models; diff --git a/src/Editor/Ghost.Editor/ViewModels/Pages/EngineEditor/HierarchyViewModel.cs b/src/Editor/Ghost.Editor/ViewModels/Pages/EngineEditor/HierarchyViewModel.cs index a4bc770..d05145c 100644 --- a/src/Editor/Ghost.Editor/ViewModels/Pages/EngineEditor/HierarchyViewModel.cs +++ b/src/Editor/Ghost.Editor/ViewModels/Pages/EngineEditor/HierarchyViewModel.cs @@ -1,7 +1,5 @@ using CommunityToolkit.Mvvm.ComponentModel; using Ghost.Editor.Core.Contracts; -using Ghost.Editor.Core.SceneGraph; -using System.Collections.ObjectModel; namespace Ghost.Editor.ViewModels.Pages.EngineEditor; diff --git a/src/Editor/Ghost.Editor/ViewModels/Pages/EngineEditor/ProjectViewModel.cs b/src/Editor/Ghost.Editor/ViewModels/Pages/EngineEditor/ProjectViewModel.cs index 1b612cd..287083e 100644 --- a/src/Editor/Ghost.Editor/ViewModels/Pages/EngineEditor/ProjectViewModel.cs +++ b/src/Editor/Ghost.Editor/ViewModels/Pages/EngineEditor/ProjectViewModel.cs @@ -1,7 +1,5 @@ using CommunityToolkit.Mvvm.ComponentModel; using Ghost.Editor.Core; -using Ghost.Editor.Core.AssetHandle; -using Ghost.Editor.Core.Contracts; using Ghost.Editor.Models; using System.Collections.ObjectModel; diff --git a/src/Runtime/Ghost.Core/Handle.cs b/src/Runtime/Ghost.Core/Handle.cs index 029eee1..964c0b3 100644 --- a/src/Runtime/Ghost.Core/Handle.cs +++ b/src/Runtime/Ghost.Core/Handle.cs @@ -23,12 +23,12 @@ public readonly struct Handle : IEquatable> public readonly bool IsValid => this != Invalid; public readonly bool IsInvalid => this == Invalid; - public readonly override int GetHashCode() + public override readonly int GetHashCode() { return ID + (Generation << 16); } - public readonly override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { return obj is Handle id && Equals(id); } @@ -76,12 +76,12 @@ public readonly struct Identifier : IEquatable> public readonly bool IsValid => this != Invalid; public readonly bool IsInvalid => this == Invalid; - public readonly override int GetHashCode() + public override readonly int GetHashCode() { return Value; } - public readonly override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { return obj is Identifier id && Equals(id); } @@ -152,7 +152,7 @@ public readonly struct Key64 : IEquatable> public bool IsValid => this != Invalid; public bool IsInvalid => this == Invalid; - public readonly override int GetHashCode() + public override readonly int GetHashCode() { return Value.GetHashCode(); } @@ -167,7 +167,7 @@ public readonly struct Key64 : IEquatable> return Value.CompareTo(other.Value); } - public readonly override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { return obj is Key64 id && Equals(id); } @@ -205,7 +205,7 @@ public readonly struct Key128 : IEquatable> public bool IsValid => this != Invalid; public bool IsInvalid => this == Invalid; - public readonly override int GetHashCode() + public override readonly int GetHashCode() { return Value.GetHashCode(); } @@ -220,7 +220,7 @@ public readonly struct Key128 : IEquatable> return Value.CompareTo(other.Value); } - public readonly override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { return obj is Key128 id && Equals(id); } diff --git a/src/Runtime/Ghost.Core/Result.cs b/src/Runtime/Ghost.Core/Result.cs index 9b21761..de9ed0a 100644 --- a/src/Runtime/Ghost.Core/Result.cs +++ b/src/Runtime/Ghost.Core/Result.cs @@ -66,7 +66,7 @@ public readonly struct Result private readonly bool _isSuccess; /// - /// Gets the value. Undefined if the result is a failure. + /// Gets the value. Undefined behavior if the result is a failure. /// public T Value { @@ -141,7 +141,7 @@ public readonly struct Result private readonly E _error; /// - /// Gets the value. Undefined if the result is a failure. + /// Gets the value. Undefined behavior if the result is a failure. /// public T Value { @@ -194,10 +194,10 @@ public readonly ref struct RefResult where E : struct, Enum { private readonly ref T _value; - private readonly E _error; + private readonly E _error; /// - /// Gets a reference to the value. Undefined if the result is a failure. + /// Gets a reference to the value. Undefined behavior if the result is a failure. /// public ref T Value { @@ -249,6 +249,12 @@ public readonly ref struct RefResult public static class ResultExtensions { + extension(Error error) + { + public bool IsSuccess => error == Error.None; + public bool IsFailure => error != Error.None; + } + public static void ThrowIfFailed(this Error result, [CallerArgumentExpression(nameof(result))] string? op = null) { if (result != Error.None) diff --git a/src/Runtime/Ghost.Core/Utilities/BinaryWriter.cs b/src/Runtime/Ghost.Core/Utilities/BinaryWriter.cs deleted file mode 100644 index 49380e0..0000000 --- a/src/Runtime/Ghost.Core/Utilities/BinaryWriter.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Runtime.CompilerServices; - -namespace Ghost.Core.Utilities; - -public ref struct BinaryWriter -{ - private readonly Span _buffer; - private int _position; - - public int Position - { - readonly get => _position; - set => _position = value; - } - - public BinaryWriter(Span buffer) - { - _buffer = buffer; - _position = 0; - } - - public unsafe void Write(scoped ref readonly T value) - where T : unmanaged - { - Unsafe.WriteUnaligned(ref _buffer[_position], value); - _position += sizeof(T); - } - - public void WriteBytes(ReadOnlySpan data) - { - data.CopyTo(_buffer.Slice(_position, data.Length)); - _position += data.Length; - } - - public Span GetSpan(int length) - { - var span = _buffer.Slice(_position, length); - _position += length; - return span; - } -} diff --git a/src/Runtime/Ghost.Core/Utilities/BufferWriter.cs b/src/Runtime/Ghost.Core/Utilities/BufferWriter.cs new file mode 100644 index 0000000..9b60971 --- /dev/null +++ b/src/Runtime/Ghost.Core/Utilities/BufferWriter.cs @@ -0,0 +1,53 @@ +using Misaki.HighPerformance.LowLevel.Buffer; +using Misaki.HighPerformance.LowLevel.Collections; +using System.Runtime.CompilerServices; + +namespace Ghost.Core.Utilities; + +public struct BufferWriter : IDisposable +{ + private UnsafeList _buffer; + private int _position; + + public int Position + { + readonly get => _position; + set => _position = value; + } + + public BufferWriter(int initialCapacity, AllocationHandle allocationHandle) + { + _buffer = new UnsafeList(initialCapacity, allocationHandle); + _position = 0; + } + + public unsafe void Write(T value) + where T : unmanaged + { + Unsafe.WriteUnaligned(ref _buffer[_position], value); + _position += sizeof(T); + } + + public void WriteBytes(ReadOnlySpan data) + { + data.CopyTo(_buffer.AsSpan().Slice(_position, data.Length)); + _position += data.Length; + } + + public Span ReserveSpan(int length) + { + var span = _buffer.AsSpan().Slice(_position, length); + _position += length; + return span; + } + + public readonly Span AsSpan() + { + return _buffer.AsSpan(); + } + + public void Dispose() + { + _buffer.Dispose(); + } +} diff --git a/src/Runtime/Ghost.Core/Utilities/EnumUtility.cs b/src/Runtime/Ghost.Core/Utilities/EnumUtility.cs index d6bb648..d354bc2 100644 --- a/src/Runtime/Ghost.Core/Utilities/EnumUtility.cs +++ b/src/Runtime/Ghost.Core/Utilities/EnumUtility.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; - namespace Ghost.Core.Utilities; internal class EnumUtility diff --git a/src/Runtime/Ghost.Core/Utilities/Hash.cs b/src/Runtime/Ghost.Core/Utilities/Hash.cs index 521b93c..f2eacea 100644 --- a/src/Runtime/Ghost.Core/Utilities/Hash.cs +++ b/src/Runtime/Ghost.Core/Utilities/Hash.cs @@ -18,11 +18,11 @@ public static class Hash [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong Hash64(ulong a, ulong b, ulong c) { - ulong h1 = a * _PRIME1; - ulong h2 = b * _PRIME2; - ulong h3 = c * _PRIME3; + var h1 = a * _PRIME1; + var h2 = b * _PRIME2; + var h3 = c * _PRIME3; - ulong h = h1 ^ h2 ^ h3; + var h = h1 ^ h2 ^ h3; h = (h ^ (h >> 33)) * _PRIME4; return h ^ (h >> 29); @@ -31,12 +31,12 @@ public static class Hash [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong Hash64(ulong a, ulong b, ulong c, ulong d) { - ulong h1 = a * _PRIME1; - ulong h2 = b * _PRIME2; - ulong h3 = c * _PRIME3; - ulong h4 = d * _PRIME4; + var h1 = a * _PRIME1; + var h2 = b * _PRIME2; + var h3 = c * _PRIME3; + var h4 = d * _PRIME4; - ulong h = h1 ^ h2 ^ h3 ^ h4; + var h = h1 ^ h2 ^ h3 ^ h4; h = (h ^ (h >> 33)) * _PRIME1; return h ^ (h >> 29); diff --git a/src/Runtime/Ghost.Core/Utilities/Win32Utility.cs b/src/Runtime/Ghost.Core/Utilities/Win32Utility.cs index a4d38e1..d629eae 100644 --- a/src/Runtime/Ghost.Core/Utilities/Win32Utility.cs +++ b/src/Runtime/Ghost.Core/Utilities/Win32Utility.cs @@ -1,6 +1,4 @@ using Misaki.HighPerformance.LowLevel; -using System.ComponentModel; -using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using TerraFX.Interop.Windows; diff --git a/src/Runtime/Ghost.Engine/Resources/EngineData.cs b/src/Runtime/Ghost.Engine/Resources/EngineData.cs index aabce8a..53bd377 100644 --- a/src/Runtime/Ghost.Engine/Resources/EngineData.cs +++ b/src/Runtime/Ghost.Engine/Resources/EngineData.cs @@ -4,5 +4,5 @@ internal class EngineData { public const string ENGINE_NAME = "Ghost Engine"; - public readonly static Version EngineVersion = new(0, 1, 0); + public static readonly Version EngineVersion = new(0, 1, 0); } \ No newline at end of file diff --git a/src/Runtime/Ghost.Entities/Archetype.cs b/src/Runtime/Ghost.Entities/Archetype.cs index e01113a..7b39efc 100644 --- a/src/Runtime/Ghost.Entities/Archetype.cs +++ b/src/Runtime/Ghost.Entities/Archetype.cs @@ -7,7 +7,7 @@ using System.Runtime.CompilerServices; namespace Ghost.Entities; -internal unsafe sealed class ChunkDebugView +internal sealed unsafe class ChunkDebugView { [DebuggerDisplay("{Name,nq}: {Data}")] internal class ComponentArrayView @@ -541,27 +541,27 @@ internal unsafe struct Archetype : IDisposable ref var chunk = ref _chunks[chunkIndex]; - int oldCount = chunk._count; - int removeCount = sortedIndicesToRemove.Length; - int newCount = oldCount - removeCount; // The boundary between "Keep" and "Drop" + var oldCount = chunk._count; + var removeCount = sortedIndicesToRemove.Length; + var newCount = oldCount - removeCount; // The boundary between "Keep" and "Drop" var chunkBase = chunk.GetUnsafePtr(); var world = World.GetWorldUncheck(_worldID); // Typo fixed from 'wrold' // Pointers for the swap logic // 1. 'holePtr' tracks which index in the sorted list we are processing - int holePtr = 0; + var holePtr = 0; // 2. 'candidateIndex' starts at the end of the OLD array and moves backward - int candidateIndex = oldCount - 1; + var candidateIndex = oldCount - 1; // 3. 'removalTailPtr' tracks removals at the end of the array to skip them - int removalTailPtr = sortedIndicesToRemove.Length - 1; + var removalTailPtr = sortedIndicesToRemove.Length - 1; // Iterate through the holes that are strictly INSIDE the new valid range while (holePtr < removeCount) { - int holeIndex = sortedIndicesToRemove[holePtr]; + var holeIndex = sortedIndicesToRemove[holePtr]; // If the current hole is beyond the new count, it's in the "Drop Zone". // Since the list is sorted, all subsequent holes are also in the drop zone. @@ -574,7 +574,7 @@ internal unsafe struct Archetype : IDisposable while (candidateIndex >= newCount) { // Check if the current candidate is actually marked for removal - bool isCandidateRemoved = false; + var isCandidateRemoved = false; // Because sortedIndices is sorted, we check the end of the list // to see if the candidateIndex matches a removal request. diff --git a/src/Runtime/Ghost.Entities/Component.cs b/src/Runtime/Ghost.Entities/Component.cs index fe29d3b..29e21e9 100644 --- a/src/Runtime/Ghost.Entities/Component.cs +++ b/src/Runtime/Ghost.Entities/Component.cs @@ -181,7 +181,7 @@ public class ComponentManager : IDisposable _archetypes.Add(new Archetype(arcID, _world.ID, componentTypeIDs)); _archetypeLookup.Add(signatureHash, arcID); - for (int i = 0; i < _entityQueries.Count; i++) + for (var i = 0; i < _entityQueries.Count; i++) { ref var query = ref _entityQueries[i]; query.AddArchetypeIfMatch(in _archetypes[arcID.Value]); diff --git a/src/Runtime/Ghost.Entities/Query.cs b/src/Runtime/Ghost.Entities/Query.cs index a933ea1..f4a6625 100644 --- a/src/Runtime/Ghost.Entities/Query.cs +++ b/src/Runtime/Ghost.Entities/Query.cs @@ -455,7 +455,7 @@ public unsafe partial struct EntityQuery : IDisposable return 0; } - for(var i = 0; i < _matchingArchetypes.Count; i++) + for (var i = 0; i < _matchingArchetypes.Count; i++) { var archetypeID = _matchingArchetypes[i]; ref var archetype = ref world.ComponentManager.GetArchetypeReference(archetypeID); diff --git a/src/Runtime/Ghost.Entities/System.cs b/src/Runtime/Ghost.Entities/System.cs index fcd7477..e75b29a 100644 --- a/src/Runtime/Ghost.Entities/System.cs +++ b/src/Runtime/Ghost.Entities/System.cs @@ -204,7 +204,7 @@ public abstract class SystemGroup : ISystem foreach (var sys in systems) { var type = sys.GetType(); - if (!dependencies.TryGetValue(type, out HashSet? value)) + if (!dependencies.TryGetValue(type, out var value)) { value = []; dependencies[type] = value; @@ -234,7 +234,7 @@ public abstract class SystemGroup : ISystem // We loop until we have sorted everyone while (sortedList.Count < systems.Count) { - bool addedAny = false; + var addedAny = false; foreach (var sys in systems) { @@ -242,7 +242,7 @@ public abstract class SystemGroup : ISystem if (visited.Contains(type)) continue; // Check if all dependencies for this system are already visited/sorted - bool canRun = true; + var canRun = true; if (dependencies.TryGetValue(type, out var deps)) { foreach (var dep in deps) diff --git a/src/Runtime/Ghost.Entities/Templates/EntityQuery.ForEach.gen.cs b/src/Runtime/Ghost.Entities/Templates/EntityQuery.ForEach.gen.cs index 7f185c6..e36ff01 100644 --- a/src/Runtime/Ghost.Entities/Templates/EntityQuery.ForEach.gen.cs +++ b/src/Runtime/Ghost.Entities/Templates/EntityQuery.ForEach.gen.cs @@ -24,7 +24,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == compTypeIDs[i]) { @@ -111,7 +111,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 2; i++) + for (var i = 0; i < 2; i++) { if (id == compTypeIDs[i]) { @@ -202,7 +202,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 3; i++) + for (var i = 0; i < 3; i++) { if (id == compTypeIDs[i]) { @@ -297,7 +297,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 4; i++) + for (var i = 0; i < 4; i++) { if (id == compTypeIDs[i]) { @@ -396,7 +396,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 5; i++) + for (var i = 0; i < 5; i++) { if (id == compTypeIDs[i]) { @@ -499,7 +499,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 6; i++) + for (var i = 0; i < 6; i++) { if (id == compTypeIDs[i]) { @@ -606,7 +606,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 7; i++) + for (var i = 0; i < 7; i++) { if (id == compTypeIDs[i]) { @@ -717,7 +717,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 8; i++) + for (var i = 0; i < 8; i++) { if (id == compTypeIDs[i]) { @@ -808,7 +808,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == compTypeIDs[i]) { @@ -896,7 +896,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 2; i++) + for (var i = 0; i < 2; i++) { if (id == compTypeIDs[i]) { @@ -988,7 +988,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 3; i++) + for (var i = 0; i < 3; i++) { if (id == compTypeIDs[i]) { @@ -1084,7 +1084,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 4; i++) + for (var i = 0; i < 4; i++) { if (id == compTypeIDs[i]) { @@ -1184,7 +1184,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 5; i++) + for (var i = 0; i < 5; i++) { if (id == compTypeIDs[i]) { @@ -1288,7 +1288,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 6; i++) + for (var i = 0; i < 6; i++) { if (id == compTypeIDs[i]) { @@ -1396,7 +1396,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 7; i++) + for (var i = 0; i < 7; i++) { if (id == compTypeIDs[i]) { @@ -1508,7 +1508,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 8; i++) + for (var i = 0; i < 8; i++) { if (id == compTypeIDs[i]) { diff --git a/src/Runtime/Ghost.Entities/Templates/EntityQuery.JobEntity.gen.cs b/src/Runtime/Ghost.Entities/Templates/EntityQuery.JobEntity.gen.cs index cb8f21e..8426889 100644 --- a/src/Runtime/Ghost.Entities/Templates/EntityQuery.JobEntity.gen.cs +++ b/src/Runtime/Ghost.Entities/Templates/EntityQuery.JobEntity.gen.cs @@ -1168,7 +1168,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == runner.componentIDs[i]) { @@ -1324,7 +1324,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == runner.componentIDs[i]) { @@ -1507,7 +1507,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == runner.componentIDs[i]) { @@ -1717,7 +1717,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == runner.componentIDs[i]) { @@ -1954,7 +1954,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == runner.componentIDs[i]) { @@ -2218,7 +2218,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == runner.componentIDs[i]) { @@ -2509,7 +2509,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == runner.componentIDs[i]) { @@ -2827,7 +2827,7 @@ public unsafe partial struct EntityQuery var it = _mask.writeAccess.GetIterator(); while (it.Next(out var id)) { - for (var i =0; i < 1; i++) + for (var i = 0; i < 1; i++) { if (id == runner.componentIDs[i]) { diff --git a/src/Runtime/Ghost.Generator/ComponentRegistrationGenerator.cs b/src/Runtime/Ghost.Generator/ComponentRegistrationGenerator.cs index c8e972a..c50190f 100644 --- a/src/Runtime/Ghost.Generator/ComponentRegistrationGenerator.cs +++ b/src/Runtime/Ghost.Generator/ComponentRegistrationGenerator.cs @@ -71,15 +71,15 @@ internal static class {name} public static void RegisterIComponentTypes() {{"); - foreach (var symbol in components.Distinct(SymbolEqualityComparer.Default)) - { - if (symbol is null) continue; + foreach (var symbol in components.Distinct(SymbolEqualityComparer.Default)) + { + if (symbol is null) continue; - sb.Append($@" + sb.Append($@" global::Ghost.Entities.ComponentRegistry.GetOrRegisterComponentID<{symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>();"); - } + } - sb.Append(@" + sb.Append(@" } }"); diff --git a/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandAllocator.cs b/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandAllocator.cs index b282d0c..318e5ea 100644 --- a/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandAllocator.cs +++ b/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandAllocator.cs @@ -1,4 +1,3 @@ -using Ghost.Core.Utilities; using Ghost.Graphics.D3D12.Utilities; using Ghost.Graphics.RHI; using Misaki.HighPerformance.LowLevel; diff --git a/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandBuffer.cs b/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandBuffer.cs index d5ab7ef..04fb650 100644 --- a/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandBuffer.cs +++ b/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandBuffer.cs @@ -1,5 +1,4 @@ using Ghost.Core; -using Ghost.Core.Utilities; using Ghost.Graphics.D3D12.Utilities; using Ghost.Graphics.RHI; using Misaki.HighPerformance.LowLevel; @@ -869,8 +868,11 @@ internal unsafe class D3D12CommandBuffer : ICommandBuffer #endif IncrementCommandCount(); + var resource = _resourceDatabase.GetResource(argumentBuffer.AsResource()); var countResource = _resourceDatabase.GetResource(countBuffer.AsResource()); + + // TODO _commandList.Get()->ExecuteIndirect(null, 0, resource, argumentOffset, countResource, countBufferOffset); @@ -947,7 +949,7 @@ internal unsafe class D3D12CommandBuffer : ICommandBuffer d3d12Subresources); } - public void CopyBuffer(Handle dest, Handle src, ulong destOffset = 0, ulong srcOffset = 0, ulong numBytes = 0) + public void CopyBuffer(Handle dst, Handle src, ulong dstOffset = 0, ulong srcOffset = 0, ulong numBytes = 0) { ThrowIfDisposed(); ThrowIfNotRecording(); @@ -957,11 +959,16 @@ internal unsafe class D3D12CommandBuffer : ICommandBuffer return; } #endif + if (dst == src) + { + return; + } + IncrementCommandCount(); - var pDestResource = _resourceDatabase.GetResource(dest.AsResource()); + var pDstResource = _resourceDatabase.GetResource(dst.AsResource()); var pSrcResource = _resourceDatabase.GetResource(src.AsResource()); - if (pSrcResource == null || pDestResource == null) + if (pSrcResource == null || pDstResource == null) { RecordError(nameof(CopyBuffer), Error.InvalidArgument); return; @@ -969,14 +976,45 @@ internal unsafe class D3D12CommandBuffer : ICommandBuffer if (numBytes == 0) { - _commandList.Get()->CopyResource(pDestResource, pSrcResource); + _commandList.Get()->CopyResource(pDstResource, pSrcResource); } else { - _commandList.Get()->CopyBufferRegion(pDestResource, destOffset, pSrcResource, srcOffset, numBytes); + _commandList.Get()->CopyBufferRegion(pDstResource, dstOffset, pSrcResource, srcOffset, numBytes); } } + public void CopyTexture(Handle dst, Handle src) + { + throw new NotImplementedException(); + + ThrowIfDisposed(); + ThrowIfNotRecording(); +#if !DEBUG + if (_lastError.Status != Error.None) + { + return; + } +#endif + if (dst == src) + { + return; + } + + IncrementCommandCount(); + + var pDstResource = _resourceDatabase.GetResource(dst.AsResource()); + var pSrcResource = _resourceDatabase.GetResource(src.AsResource()); + if (pSrcResource == null || pDstResource == null) + { + RecordError(nameof(CopyTexture), Error.InvalidArgument); + return; + } + + // TODO + _commandList.Get()->CopyTextureRegion(null, 0, 0, 0, null, null); + } + public void Dispose() { if (_disposed) diff --git a/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandQueue.cs b/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandQueue.cs index 6085477..11309eb 100644 --- a/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandQueue.cs +++ b/src/Runtime/Ghost.Graphics.D3D12/D3D12CommandQueue.cs @@ -1,4 +1,3 @@ -using Ghost.Core.Utilities; using Ghost.Graphics.D3D12.Utilities; using Ghost.Graphics.RHI; using Misaki.HighPerformance.LowLevel; diff --git a/src/Runtime/Ghost.Graphics.D3D12/D3D12DebugLayer.cs b/src/Runtime/Ghost.Graphics.D3D12/D3D12DebugLayer.cs index ff203ca..94dc962 100644 --- a/src/Runtime/Ghost.Graphics.D3D12/D3D12DebugLayer.cs +++ b/src/Runtime/Ghost.Graphics.D3D12/D3D12DebugLayer.cs @@ -1,8 +1,6 @@ -using Ghost.Core.Utilities; using Ghost.Graphics.D3D12.Utilities; using Misaki.HighPerformance.LowLevel; using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; using static TerraFX.Aliases.DXGI_Alias; diff --git a/src/Runtime/Ghost.Graphics.D3D12/D3D12DescriptorAllocator.cs b/src/Runtime/Ghost.Graphics.D3D12/D3D12DescriptorAllocator.cs index ad424f5..4ef5bed 100644 --- a/src/Runtime/Ghost.Graphics.D3D12/D3D12DescriptorAllocator.cs +++ b/src/Runtime/Ghost.Graphics.D3D12/D3D12DescriptorAllocator.cs @@ -95,7 +95,7 @@ internal unsafe class D3D12DescriptorAllocator : IDisposable #region DSV Methods - public Identifier AllocateDSV() + public Identifier AllocateDSV() { ObjectDisposedException.ThrowIf(_disposed, this); diff --git a/src/Runtime/Ghost.Graphics.D3D12/D3D12ResourceAllocator.cs b/src/Runtime/Ghost.Graphics.D3D12/D3D12ResourceAllocator.cs index 79cdda8..330cd54 100644 --- a/src/Runtime/Ghost.Graphics.D3D12/D3D12ResourceAllocator.cs +++ b/src/Runtime/Ghost.Graphics.D3D12/D3D12ResourceAllocator.cs @@ -1,10 +1,7 @@ using Ghost.Core; -using Ghost.Core.Graphics; -using Ghost.Core.Utilities; using Ghost.Graphics.D3D12.Utilities; using Ghost.Graphics.RHI; using Misaki.HighPerformance.LowLevel; -using Misaki.HighPerformance.LowLevel.Collections; using System.Runtime.CompilerServices; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -504,6 +501,11 @@ internal sealed unsafe partial class D3D12ResourceAllocator : IResourceAllocator private Handle TrackAllocation(D3D12MA_Allocation* allocation, ResourceBarrierData barrierData, ResourceViewGroup resourceDescriptor, ResourceDesc desc, string name, bool isTemp) { var handle = _resourceDatabase.AddAllocation(allocation, barrierData, resourceDescriptor, desc, name); + if (isTemp) + { + _resourceDatabase.ReleaseResource(handle); + } + return handle; } @@ -830,7 +832,7 @@ internal sealed unsafe partial class D3D12ResourceAllocator : IResourceAllocator offset = 0; var handle = CreateBuffer(in bufferDesc, "TempUploadBuffer", options); - _resourceDatabase.ScheduleReleaseResource(handle.AsResource()); + _resourceDatabase.ReleaseResource(handle.AsResource()); return handle; } } diff --git a/src/Runtime/Ghost.Graphics.D3D12/D3D12ResourceDatabase.cs b/src/Runtime/Ghost.Graphics.D3D12/D3D12ResourceDatabase.cs index 8a8f543..c879509 100644 --- a/src/Runtime/Ghost.Graphics.D3D12/D3D12ResourceDatabase.cs +++ b/src/Runtime/Ghost.Graphics.D3D12/D3D12ResourceDatabase.cs @@ -1,7 +1,6 @@ using Ghost.Core; using Ghost.Graphics.D3D12.Utilities; using Ghost.Graphics.RHI; -using Misaki.HighPerformance.Collections; using Misaki.HighPerformance.LowLevel; using Misaki.HighPerformance.LowLevel.Buffer; using Misaki.HighPerformance.LowLevel.Collections; @@ -279,7 +278,7 @@ internal class D3D12ResourceDatabase : IResourceDatabase return null; } - public void ScheduleReleaseResource(Handle handle) + public void ReleaseResource(Handle handle) { ObjectDisposedException.ThrowIf(_disposed, this); diff --git a/src/Runtime/Ghost.Graphics.D3D12/D3D12SwapChain.cs b/src/Runtime/Ghost.Graphics.D3D12/D3D12SwapChain.cs index a096360..ab21f1a 100644 --- a/src/Runtime/Ghost.Graphics.D3D12/D3D12SwapChain.cs +++ b/src/Runtime/Ghost.Graphics.D3D12/D3D12SwapChain.cs @@ -249,7 +249,7 @@ internal unsafe class D3D12SwapChain : ISwapChain for (var i = 0; i < _backBuffers.Count; i++) { - _resourceDatabase.ScheduleReleaseResource(_backBuffers[i].AsResource()); + _resourceDatabase.ReleaseResource(_backBuffers[i].AsResource()); } _backBuffers.Dispose(); diff --git a/src/Runtime/Ghost.Graphics.RHI/Common.cs b/src/Runtime/Ghost.Graphics.RHI/Common.cs index 00f0b78..226fa77 100644 --- a/src/Runtime/Ghost.Graphics.RHI/Common.cs +++ b/src/Runtime/Ghost.Graphics.RHI/Common.cs @@ -114,7 +114,7 @@ public struct Color128 : IEquatable return obj is Color128 color && Equals(color); } - public readonly override int GetHashCode() + public override readonly int GetHashCode() { return HashCode.Combine(r, g, b, a); } @@ -587,7 +587,7 @@ public struct ResourceDesc } internal resource_union _desc; - + public ResourceType Type { get; init; diff --git a/src/Runtime/Ghost.Graphics.RHI/ICommandQueue.cs b/src/Runtime/Ghost.Graphics.RHI/ICommandQueue.cs index 4d88c2e..4641a0e 100644 --- a/src/Runtime/Ghost.Graphics.RHI/ICommandQueue.cs +++ b/src/Runtime/Ghost.Graphics.RHI/ICommandQueue.cs @@ -8,7 +8,7 @@ public interface ICommandQueue : IDisposable /// /// Type of commands this queue can execute /// - public CommandQueueType Type + CommandQueueType Type { get; } @@ -17,35 +17,35 @@ public interface ICommandQueue : IDisposable /// Submits a single command buffer for execution /// /// Command buffer to submit - public void Submit(ICommandBuffer commandBuffer); + void Submit(ICommandBuffer commandBuffer); /// /// Submits multiple command buffers for execution /// /// Command buffers to submit - public void Submit(params ReadOnlySpan commandBuffers); + void Submit(params ReadOnlySpan commandBuffers); /// /// Signals a fence with the specified Value /// /// Value to signal /// The fence Value that was signaled - public ulong Signal(ulong value); + ulong Signal(ulong value); /// /// Waits for the fence to reach the specified Value /// /// Value to wait for - public void WaitForValue(ulong value); + void WaitForValue(ulong value); /// /// Gets the last completed fence Value /// /// Last completed fence Value - public ulong GetCompletedValue(); + ulong GetCompletedValue(); /// /// Waits until all submitted commands have finished executing /// - public void WaitIdle(); + void WaitIdle(); } \ No newline at end of file diff --git a/src/Runtime/Ghost.Graphics.RHI/IRenderDevice.cs b/src/Runtime/Ghost.Graphics.RHI/IRenderDevice.cs index bf09af1..750cf03 100644 --- a/src/Runtime/Ghost.Graphics.RHI/IRenderDevice.cs +++ b/src/Runtime/Ghost.Graphics.RHI/IRenderDevice.cs @@ -21,7 +21,7 @@ public interface IRenderDevice : IDisposable /// /// Graphics command queue for rendering operations /// - public ICommandQueue GraphicsQueue + ICommandQueue GraphicsQueue { get; } @@ -29,7 +29,7 @@ public interface IRenderDevice : IDisposable /// /// Compute command queue for compute shader operations /// - public ICommandQueue ComputeQueue + ICommandQueue ComputeQueue { get; } @@ -37,12 +37,12 @@ public interface IRenderDevice : IDisposable /// /// Copy command queue for data transfer operations /// - public ICommandQueue CopyQueue + ICommandQueue CopyQueue { get; } - public FeatureSupport FeatureSupport + FeatureSupport FeatureSupport { get; } diff --git a/src/Runtime/Ghost.Graphics.RHI/IResourceAllocator.cs b/src/Runtime/Ghost.Graphics.RHI/IResourceAllocator.cs index 42c28ac..f11751f 100644 --- a/src/Runtime/Ghost.Graphics.RHI/IResourceAllocator.cs +++ b/src/Runtime/Ghost.Graphics.RHI/IResourceAllocator.cs @@ -1,6 +1,4 @@ using Ghost.Core; -using Ghost.Core.Graphics; -using Misaki.HighPerformance.LowLevel.Collections; namespace Ghost.Graphics.RHI; diff --git a/src/Runtime/Ghost.Graphics.RHI/IResourceDatabase.cs b/src/Runtime/Ghost.Graphics.RHI/IResourceDatabase.cs index 6e804e3..0bdb2b5 100644 --- a/src/Runtime/Ghost.Graphics.RHI/IResourceDatabase.cs +++ b/src/Runtime/Ghost.Graphics.RHI/IResourceDatabase.cs @@ -98,7 +98,7 @@ public interface IResourceDatabase : IDisposable /// Releases the GPU resource associated with the specified handle, freeing any resources allocated to it. /// /// The handle of the resource to be removed. - void ScheduleReleaseResource(Handle handle); + void ReleaseResource(Handle handle); /// /// Releases the GPU resource associated with the specified handle immediately, freeing any resources allocated to it. diff --git a/src/Runtime/Ghost.Graphics/Core/Camera.cs b/src/Runtime/Ghost.Graphics/Core/Camera.cs index 6c6b3fc..6f71212 100644 --- a/src/Runtime/Ghost.Graphics/Core/Camera.cs +++ b/src/Runtime/Ghost.Graphics/Core/Camera.cs @@ -8,6 +8,7 @@ public class Camera { private readonly IRenderer _renderer; + // History buffers. private Handle _colorTexture; private Handle _depthTexture; @@ -23,14 +24,17 @@ public class Camera /// Gets the actual width of the camera's render target in pixels. If upscaler is used, this is the width before upscaling. /// public uint ActualWidth => _actualWidth; + /// /// Gets the actual height of the camera's render target in pixels. If upscaler is used, this is the height before upscaling. /// public uint ActualHeight => _actualHeight; + /// /// Gets the virtual width of the camera's render target in pixels. If upscaler is used, this is the width after upscaling. /// public uint VirtualWidth => _virtualWidth; + /// /// Gets the virtual height of the camera's render target in pixels. If upscaler is used, this is the height after upscaling. /// @@ -64,8 +68,17 @@ public class Camera RenderGraph.Reset(); var view = new ViewState(_virtualWidth, _virtualHeight, _actualWidth, _actualHeight); - RenderGraph.Compile(in view); - RenderGraph.Execute(context.CommandBuffer); + var e = RenderGraph.Compile(in view); + if (e != Error.None) + { + return e; + } + + e = RenderGraph.Execute(context.CommandBuffer); + if (e != Error.None) + { + return e; + } return Error.None; } diff --git a/src/Runtime/Ghost.Graphics/Core/Material.cs b/src/Runtime/Ghost.Graphics/Core/Material.cs index ce400dd..e264221 100644 --- a/src/Runtime/Ghost.Graphics/Core/Material.cs +++ b/src/Runtime/Ghost.Graphics/Core/Material.cs @@ -35,7 +35,7 @@ internal struct CBufferCache : IResourceReleasable } _cpuData.Dispose(); - database.ScheduleReleaseResource(_gpuResource.AsResource()); + database.ReleaseResource(_gpuResource.AsResource()); _gpuResource = Handle.Invalid; _size = 0; @@ -144,7 +144,6 @@ public struct Material : IResourceReleasable return _cBufferCache.CpuData.AsSpan(0, (int)_cBufferCache.Size); } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe Error SetPropertyCache(scoped ref readonly T data) where T : unmanaged { @@ -166,7 +165,6 @@ public struct Material : IResourceReleasable return Error.None; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public Error SetRawPropertyCache(ReadOnlySpan data) { if (data.Length != _cBufferCache.Size) @@ -200,7 +198,6 @@ public struct Material : IResourceReleasable _isDirty = true; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public Error SetKeyword(IResourceManager manager, int keywordId, bool enabled) { var r = manager.GetShaderReference(_shader); @@ -222,7 +219,6 @@ public struct Material : IResourceReleasable return Error.None; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly bool IsKeywordEnabled(IResourceManager manager, int keywordId) { var r = manager.GetShaderReference(_shader); @@ -276,8 +272,7 @@ public struct Material : IResourceReleasable cmd.ResourceBarrier(desc); } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - void IResourceReleasable.ReleaseResource(IResourceDatabase database) + public void ReleaseResource(IResourceDatabase database) { _cBufferCache.ReleaseResource(database); _passPipelineOverride.Dispose(); diff --git a/src/Runtime/Ghost.Graphics/Core/Mesh.cs b/src/Runtime/Ghost.Graphics/Core/Mesh.cs index d8f560d..4bf3a3c 100644 --- a/src/Runtime/Ghost.Graphics/Core/Mesh.cs +++ b/src/Runtime/Ghost.Graphics/Core/Mesh.cs @@ -113,13 +113,13 @@ public struct Mesh : IResourceReleasable _indices.Dispose(); } - readonly void IResourceReleasable.ReleaseResource(IResourceDatabase database) + public readonly void ReleaseResource(IResourceDatabase database) { ReleaseCpuResources(); - database.ScheduleReleaseResource(VertexBuffer.AsResource()); - database.ScheduleReleaseResource(IndexBuffer.AsResource()); - database.ScheduleReleaseResource(ObjectDataBuffer.AsResource()); + database.ReleaseResource(VertexBuffer.AsResource()); + database.ReleaseResource(IndexBuffer.AsResource()); + database.ReleaseResource(ObjectDataBuffer.AsResource()); } } diff --git a/src/Runtime/Ghost.Graphics/Core/RenderingContext.cs b/src/Runtime/Ghost.Graphics/Core/RenderingContext.cs index e02a128..191a408 100644 --- a/src/Runtime/Ghost.Graphics/Core/RenderingContext.cs +++ b/src/Runtime/Ghost.Graphics/Core/RenderingContext.cs @@ -10,18 +10,21 @@ namespace Ghost.Graphics.Core; public readonly unsafe ref struct RenderingContext { private readonly IGraphicsEngine _engine; + private readonly IResourceManager _resourceManager; private readonly ICommandBuffer _directCmd; public ICommandBuffer DirectCommandBuffer => _directCmd; public IShaderCompiler ShaderCompiler => _engine.ShaderCompiler; + public IResourceManager ResourceManager => _resourceManager; public IResourceAllocator ResourceAllocator => _engine.ResourceAllocator; public IResourceDatabase ResourceDatabase => _engine.ResourceDatabase; public IPipelineLibrary PipelineLibrary => _engine.PipelineLibrary; - internal RenderingContext(IGraphicsEngine engine, ICommandBuffer directCmd) + internal RenderingContext(IGraphicsEngine engine, IResourceManager resourceManager, ICommandBuffer directCmd) { _engine = engine; + _resourceManager = resourceManager; _directCmd = directCmd; } @@ -82,8 +85,8 @@ public readonly unsafe ref struct RenderingContext public Handle CreateMesh(UnsafeList vertices, UnsafeList indices, bool staticMesh) { - var mesh = ResourceAllocator.CreateMesh(vertices, indices); - var r = ResourceDatabase.GetMeshReference(mesh); + var mesh = _resourceManager.CreateMesh(vertices, indices); + var r = _resourceManager.GetMeshReference(mesh); if (r.IsFailure) { return mesh; @@ -129,7 +132,7 @@ public readonly unsafe ref struct RenderingContext /// Whether to mark the mesh as static. If it's true, the cpu buffer of the mesh will not be avaliable any more public void UploadMesh(Handle mesh, bool markMeshStatic) { - var r = ResourceDatabase.GetMeshReference(mesh); + var r = _resourceManager.GetMeshReference(mesh); if (r.IsFailure) { return; @@ -156,7 +159,7 @@ public readonly unsafe ref struct RenderingContext public void UpdateObjectData(Handle mesh, float4x4 localToWorld) { - var r = ResourceDatabase.GetMeshReference(mesh); + var r = _resourceManager.GetMeshReference(mesh); if (r.IsFailure) { return; @@ -192,7 +195,7 @@ public readonly unsafe ref struct RenderingContext where T : unmanaged { var desc = ResourceDatabase.GetResourceDescription(texture.AsResource()).GetValueOrThrow(); - + //var size = ResourceAllocator.GetSizeInfo(desc).Size; //if ((ulong)(data.Length * sizeof(T)) != ResourceAllocator.GetSizeInfo(desc).Size) //{ diff --git a/src/Runtime/Ghost.Graphics/Core/Shader.cs b/src/Runtime/Ghost.Graphics/Core/Shader.cs index 2d10ba6..0429d2f 100644 --- a/src/Runtime/Ghost.Graphics/Core/Shader.cs +++ b/src/Runtime/Ghost.Graphics/Core/Shader.cs @@ -3,6 +3,7 @@ using Ghost.Core.Graphics; using Ghost.Graphics.RHI; using Misaki.HighPerformance.LowLevel.Buffer; using Misaki.HighPerformance.LowLevel.Collections; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Ghost.Graphics.Core; @@ -136,6 +137,7 @@ public partial struct Shader : IResourceReleasable } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal readonly int GetLocalKeywordIndex(int globalKeywordID) { if (_keywordIDToLocal.TryGetValue(globalKeywordID, out var localIndex)) @@ -146,6 +148,7 @@ public partial struct Shader : IResourceReleasable return -1; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly int GetPassIndex(Identifier passID) { if (_passIDToLocal.TryGetValue(passID.Value, out var index)) @@ -156,6 +159,7 @@ public partial struct Shader : IResourceReleasable return -1; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly int GetPassIndex(string passName) { if (_passIDToLocal.TryGetValue(GetPassID(passName), out var index)) @@ -166,11 +170,13 @@ public partial struct Shader : IResourceReleasable return -1; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly ref ShaderPass GetPassReference(int index) { return ref _shaderPasses[index]; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly Result TryGetPass(Identifier passID, out int passIndex) { if (_passIDToLocal.TryGetValue(passID.Value, out var index)) @@ -183,7 +189,7 @@ public partial struct Shader : IResourceReleasable return _shaderPasses[index]; } - void IResourceReleasable.ReleaseResource(IResourceDatabase database) + public void ReleaseResource(IResourceDatabase database) { _keywordIDToLocal.Dispose(); _shaderPasses.Dispose(); diff --git a/src/Runtime/Ghost.Graphics/GPUResourceLeakException.cs b/src/Runtime/Ghost.Graphics/GPUResourceLeakException.cs index 9a78f0f..dfe8d51 100644 --- a/src/Runtime/Ghost.Graphics/GPUResourceLeakException.cs +++ b/src/Runtime/Ghost.Graphics/GPUResourceLeakException.cs @@ -1,5 +1,3 @@ -using Misaki.HighPerformance.LowLevel; - namespace Ghost.Graphics; internal unsafe class GPUResourceLeakException : Exception diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraph.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraph.cs index f77a752..5ef1c22 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraph.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraph.cs @@ -5,7 +5,6 @@ namespace Ghost.Graphics.RenderGraphModule; /// /// Main render graph class that manages resource allocation and pass execution. -/// Delegates complex operations to specialized components for better organization. /// public sealed class RenderGraph : IDisposable { @@ -172,38 +171,38 @@ public sealed class RenderGraph : IDisposable /// /// Compiles the render graph by culling unused passes and determining resource lifetimes. - /// Delegates to RenderGraphCompiler for the actual compilation work. /// - public void Compile(in ViewState viewState) + public Error Compile(in ViewState viewState) { if (_compiled) { - return; + return Error.None; } - // Resolve texture sizes before computing hash _resources.ResolveTextureSizes(in viewState); - // Compute structural hash for caching var graphHash = RenderGraphHasher.ComputeGraphHash(_passes, _resources); + var error = _compiler.Compile(in viewState, graphHash, _passes, _compiledPasses, _nativePasses, _compiledBarriers); + if (error != Error.None) + { + return error; + } - // Delegate to compiler - _compiler.Compile(in viewState, graphHash, _passes, _compiledPasses, _nativePasses, _compiledBarriers); _compiled = true; + return Error.None; } /// /// Executes all compiled passes using native render passes where possible. - /// Delegates to RenderGraphExecutor for the actual execution work. /// - public void Execute(ICommandBuffer cmd) + public Error Execute(ICommandBuffer cmd) { if (!_compiled) { - throw new InvalidOperationException("Render graph must be compiled before execution. Call Compile(viewState) first."); + return Error.InvalidState; } - _executor.Execute(cmd, _compiledPasses, _nativePasses, _compiledBarriers); + return _executor.Execute(cmd, _compiledPasses, _nativePasses, _compiledBarriers); } public void Dispose() diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphAliasing.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphAliasing.cs index c2d15b9..aa7e6ca 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphAliasing.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphAliasing.cs @@ -94,7 +94,7 @@ internal sealed class ResourceHeap { // Check if this offset range conflicts with ANY existing allocations var canUseOffset = CanPlaceAtOffset(alignedOffset, alignedSize, firstUsePass, lastUsePass); - + if (canUseOffset) { var waste = block.size - alignedSize; @@ -173,7 +173,7 @@ internal sealed class ResourceHeap private bool CanPlaceAtOffset(ulong offset, ulong size, int firstUsePass, int lastUsePass) { var endOffset = offset + size; - + foreach (var block in _blocks) { // Skip free blocks - they don't have lifetime constraints @@ -185,12 +185,12 @@ internal sealed class ResourceHeap // Check if this block's memory range overlaps with our target range var blockEnd = block.offset + block.size; var memoryOverlap = !(offset >= blockEnd || endOffset <= block.offset); - + if (memoryOverlap) { // Memory ranges overlap, check if lifetimes also overlap var lifetimeOverlap = !(firstUsePass > block.lastUsePass || lastUsePass < block.firstUsePass); - + if (lifetimeOverlap) { // Both memory AND lifetime overlap - cannot place here! @@ -198,7 +198,7 @@ internal sealed class ResourceHeap } } } - + return true; } @@ -298,7 +298,7 @@ internal sealed class ResourceAliasingManager private const ulong _DEFAULT_BUFFER_ALIGNMENT = 65536; // 64KB for D3D12 public ResourceHeap Heap => _heap; - + /// /// Helper method to get the size of a resource /// @@ -374,8 +374,8 @@ internal sealed class ResourceAliasingManager foreach (var (logicalIndex, logicalResource) in logicalResources) { var size = GetResourceSize(logicalResource); - var alignment = logicalResource.type == RenderGraphResourceType.Texture - ? _DEFAULT_TEXTURE_ALIGNMENT + var alignment = logicalResource.type == RenderGraphResourceType.Texture + ? _DEFAULT_TEXTURE_ALIGNMENT : _DEFAULT_BUFFER_ALIGNMENT; var (success, offset, block) = simulationHeap.TryAllocate( @@ -393,7 +393,7 @@ internal sealed class ResourceAliasingManager // Get peak usage from simulation var peakMemoryUsage = simulationHeap.GetPeakUsage(); - + // Align peak usage to 64KB (D3D12 requirement) peakMemoryUsage = AlignUp(peakMemoryUsage, _DEFAULT_TEXTURE_ALIGNMENT); @@ -405,8 +405,8 @@ internal sealed class ResourceAliasingManager foreach (var (logicalIndex, logicalResource) in logicalResources) { var size = GetResourceSize(logicalResource); - var alignment = logicalResource.type == RenderGraphResourceType.Texture - ? _DEFAULT_TEXTURE_ALIGNMENT + var alignment = logicalResource.type == RenderGraphResourceType.Texture + ? _DEFAULT_TEXTURE_ALIGNMENT : _DEFAULT_BUFFER_ALIGNMENT; var (success, offset, block) = _heap.TryAllocate( @@ -444,7 +444,7 @@ internal sealed class ResourceAliasingManager for (var i = 0; i < _placedResources.Count; i++) { var placed = _placedResources[i]; - + // Find all logical resources that share the same heap location for (var j = 0; j < _placedResources.Count; j++) { @@ -454,7 +454,7 @@ internal sealed class ResourceAliasingManager } var other = _placedResources[j]; - + // Check if they're at the same offset if (other.heapOffset == placed.heapOffset) { diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphBarriers.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphBarriers.cs index 0e0a662..e1bf798 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphBarriers.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphBarriers.cs @@ -1,6 +1,5 @@ using Ghost.Core; using Ghost.Graphics.RHI; -using System.Runtime.InteropServices; namespace Ghost.Graphics.RenderGraphModule; @@ -49,8 +48,8 @@ internal struct ResourceBarrier public override readonly string ToString() { - return AliasingPredecessor.IsValid - ? $"[Pass {PassIndex}] Aliasing Barrier: {AliasingPredecessor.Value}->{Resource.Value} Target: {TargetState.layout}" + return AliasingPredecessor.IsValid + ? $"[Pass {PassIndex}] Aliasing Barrier: {AliasingPredecessor.Value}->{Resource.Value} Target: {TargetState.layout}" : $"[Pass {PassIndex}] Barrier: {Resource.Value} Target: {TargetState.layout}"; } } @@ -87,8 +86,8 @@ internal struct CompiledBarrier public override readonly string ToString() { - return AliasingPredecessor.IsValid - ? $"[Pass {PassIndex}] Aliasing: {AliasingPredecessor.Value}->{Resource.Value} -> {TargetState.layout}" + return AliasingPredecessor.IsValid + ? $"[Pass {PassIndex}] Aliasing: {AliasingPredecessor.Value}->{Resource.Value} -> {TargetState.layout}" : $"[Pass {PassIndex}] Transition: {Resource.Value} -> {TargetState.layout}"; } } @@ -320,7 +319,7 @@ internal static class RenderGraphBarriers var sync = BarrierSync.PixelShading | BarrierSync.NonPixelShading; var access = BarrierAccess.ShaderResource; - + var resource = resources.GetResource(handle); if (resource.bufferDesc.Usage.HasFlag(BufferUsage.IndirectArgument)) { diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphBuilder.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphBuilder.cs index 605e82e..a91847e 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphBuilder.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphBuilder.cs @@ -47,7 +47,7 @@ public interface IRenderGraphBuilder : IDisposable /// The access mode specifying how the texture will be read or written during the pass. /// An identifier for the texture. Identifier UseTexture(Identifier texture, AccessFlags accessMode); - + /// /// Registers the specified buffer for use in the current render graph pass with the given access mode. /// @@ -195,7 +195,7 @@ internal class RenderGraphBuilder : IRasterRenderGraphBuilder, IComputeRenderGra _resources.SetProducer(handle.AsResource(), _pass.index); return handle; } - + public Identifier CreateBuffer(in BufferDesc desc, string name) { ThrowIfDisposed(); @@ -211,7 +211,7 @@ internal class RenderGraphBuilder : IRasterRenderGraphBuilder, IComputeRenderGra ThrowIfDisposed(); return UseResource(texture.AsResource(), flags, RenderGraphResourceType.Texture).AsTexture(); } - + public Identifier UseBuffer(Identifier buffer, AccessFlags flags) { ThrowIfDisposed(); diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphCompilationCache.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphCompilationCache.cs index 38aba68..08b61fb 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphCompilationCache.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphCompilationCache.cs @@ -15,19 +15,19 @@ internal sealed class CachedCompilation // Culling decisions for each pass public readonly List passCulledFlags = new(64); - + // Physical resource aliasing mappings (logical index -> physical index) public readonly Dictionary logicalToPhysical = new(128); - + // Placed resource metadata public readonly List placedResources = new(32); - + // Compiled barriers (stores only target states, queries before state from ResourceManager) public readonly List compiledBarriers = new(128); // Real gpu resource public readonly List> backingResources = new(32); - + // View state used for this compilation public ViewState viewState; @@ -94,18 +94,18 @@ internal sealed class RenderGraphCompilationCache { _cachedHash = hash; _hasCachedData = true; - + // Deep copy the data _cached.Clear(); - + _cached.compiledPassIndices.AddRange(data.compiledPassIndices); _cached.passCulledFlags.AddRange(data.passCulledFlags); - + foreach (var kvp in data.logicalToPhysical) { _cached.logicalToPhysical[kvp.Key] = kvp.Value; } - + _cached.placedResources.AddRange(data.placedResources); _cached.compiledBarriers.AddRange(data.compiledBarriers); @@ -137,8 +137,8 @@ internal sealed class RenderGraphCompilationCache /// public (int hits, int misses, double hitRate) GetStatistics() { - int total = CacheHits + CacheMisses; - double hitRate = total > 0 ? (double)CacheHits / total : 0.0; + var total = CacheHits + CacheMisses; + var hitRate = total > 0 ? (double)CacheHits / total : 0.0; return (CacheHits, CacheMisses, hitRate); } } diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphCompiler.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphCompiler.cs index fdee392..2b28a5a 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphCompiler.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphCompiler.cs @@ -35,7 +35,7 @@ internal sealed class RenderGraphCompiler /// /// Compiles the render graph by culling passes, allocating resources, and preparing barriers. /// - public void Compile( + public Error Compile( in ViewState viewState, ulong graphHash, List passes, @@ -43,6 +43,8 @@ internal sealed class RenderGraphCompiler List nativePasses, List compiledBarriers) { + Error error; + // Try to restore from cache if (_compilationCache.TryGetCached(graphHash, out var cached)) { @@ -54,7 +56,11 @@ internal sealed class RenderGraphCompiler RestoreFromCache(cached, compiledPasses, passes, nativePasses, compiledBarriers); _aliasingManager.AssignPhysicalResources(_resources, passes.Count); - AllocateResources(); + error = AllocateResources(); + if (error != Error.None) + { + return error; + } cached.viewState = viewState; } @@ -64,7 +70,7 @@ internal sealed class RenderGraphCompiler RestoreFromCache(cached, compiledPasses, passes, nativePasses, compiledBarriers); } - return; + return Error.None; } // Fresh compilation needed @@ -87,16 +93,19 @@ internal sealed class RenderGraphCompiler } _aliasingManager.AssignPhysicalResources(_resources, passes.Count); - AllocateResources(); + error = AllocateResources(); + if (error != Error.None) + { + return error; + } CompileBarriers(compiledPasses, compiledBarriers); _nativePassBuilder.BuildNativeRenderPasses(compiledPasses, nativePasses, compiledBarriers); StoreInCache(graphHash, viewState, compiledPasses, passes, compiledBarriers); + + return Error.None; } - /// - /// Marks passes that write to imported resources as having side effects. - /// private void MarkPassesWithSideEffects(List passes) { for (var i = 0; i < passes.Count; i++) @@ -121,9 +130,6 @@ internal sealed class RenderGraphCompiler } } - /// - /// Culls unused passes based on dependency analysis. - /// private void CullPasses(List passes) { // Mark all passes as culled initially @@ -143,9 +149,6 @@ internal sealed class RenderGraphCompiler } } - /// - /// Recursively un-culls dependencies of a pass. - /// private void UnculDependencies(RenderGraphPassBase pass, List passes) { // Un-cull producers of read resources @@ -180,9 +183,6 @@ internal sealed class RenderGraphCompiler } } - /// - /// Un-culls the producer of a resource. - /// private void UnculProducer(Identifier resource, List passes) { var res = _resources.GetResource(resource); @@ -197,10 +197,7 @@ internal sealed class RenderGraphCompiler } } - /// - /// Allocates GPU resources for the render graph. - /// - private void AllocateResources() + private Error AllocateResources() { if (_resourceHeap.IsValid) { @@ -211,15 +208,15 @@ internal sealed class RenderGraphCompiler continue; } - _resourceManager.ResourceDatabase.ScheduleReleaseResource(res.backingResource); + _resourceManager.ResourceDatabase.ReleaseResource(res.backingResource); } - _resourceManager.ResourceDatabase.ScheduleReleaseResource(_resourceHeap); + _resourceManager.ResourceDatabase.ReleaseResource(_resourceHeap); } if (_aliasingManager.Heap.size == 0) { - return; + return Error.None; // No resources to allocate } var allocationDesc = new AllocationDesc @@ -231,6 +228,10 @@ internal sealed class RenderGraphCompiler }; _resourceHeap = _resourceManager.ResourceAllocator.Allocate(in allocationDesc, "RenderGraphResourceHeap"); + if (_resourceHeap.IsInvalid) + { + return Error.InvalidState; + } for (var i = 0; i < _resources.Resources.Count; i++) { @@ -263,22 +264,22 @@ internal sealed class RenderGraphCompiler throw new NotSupportedException(); } + if (res.backingResource.IsInvalid) + { + return Error.InvalidState; + } + _compilationCache.UpdateBackingResource(i, res.backingResource); } + + return Error.None; } - /// - /// Compiles all barriers needed for execution. - /// Delegates to RenderGraphBarriers for the actual compilation logic. - /// private void CompileBarriers(List compiledPasses, List compiledBarriers) { RenderGraphBarriers.CompileBarriers(compiledPasses, compiledBarriers, _resources, _aliasingManager); } - /// - /// Restores the render graph state from cached compilation results. - /// private void RestoreFromCache( CachedCompilation cached, List compiledPasses, @@ -323,9 +324,6 @@ internal sealed class RenderGraphCompiler _nativePassBuilder.BuildNativeRenderPasses(compiledPasses, nativePasses, compiledBarriers); } - /// - /// Stores current compilation results in the cache. - /// private void StoreInCache( ulong graphHash, in ViewState viewState, @@ -368,9 +366,6 @@ internal sealed class RenderGraphCompiler _compilationCache.Store(graphHash, cacheData); } - /// - /// Releases allocated GPU resources. - /// public void Dispose() { if (_resourceHeap.IsValid) @@ -379,11 +374,11 @@ internal sealed class RenderGraphCompiler { if (!res.isImported) { - _resourceManager.ResourceDatabase.ScheduleReleaseResource(res.backingResource); + _resourceManager.ResourceDatabase.ReleaseResource(res.backingResource); } } - _resourceManager.ResourceDatabase.ScheduleReleaseResource(_resourceHeap); + _resourceManager.ResourceDatabase.ReleaseResource(_resourceHeap); _resourceHeap = Handle.Invalid; } } diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphContext.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphContext.cs index 719d321..ff186d9 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphContext.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphContext.cs @@ -53,7 +53,7 @@ internal sealed class RenderGraphContext : IRasterRenderContext, IComputeRenderC private int _activeMeshIndexCount; public IResourceManager ResourceManager => _resourceManager; - + public int ActiveMeshIndexCount => _activeMeshIndexCount; public ICommandBuffer CommandBuffer => _commandBuffer; @@ -76,7 +76,7 @@ internal sealed class RenderGraphContext : IRasterRenderContext, IComputeRenderC internal void SetRenderTargetFormats(ReadOnlySpan rtvFormats, TextureFormat dsvFormat) { - for (int i = 0; i < RHIUtility.MAX_RENDER_TARGETS; i++) + for (var i = 0; i < RHIUtility.MAX_RENDER_TARGETS; i++) { _rtvFormats[i] = i < rtvFormats.Length ? rtvFormats[i] : TextureFormat.Unknown; } diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphExecutor.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphExecutor.cs index d19e49d..83c8cc0 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphExecutor.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphExecutor.cs @@ -25,7 +25,7 @@ internal sealed class RenderGraphExecutor /// /// Executes all compiled passes using native render passes where possible. /// - public unsafe void Execute( + public unsafe Error Execute( ICommandBuffer cmd, List compiledPasses, List nativePasses, @@ -53,7 +53,11 @@ internal sealed class RenderGraphExecutor for (var i = 0; i < nativePass.mergedPassIndices.Count; i++) { var mergedPassIdx = nativePass.mergedPassIndices[i]; - ExecuteBarriersForPass(cmd, mergedPassIdx, ref barrierIndex, compiledBarriers); + var e = ExecuteBarriersForPass(cmd, mergedPassIdx, ref barrierIndex, compiledBarriers); + if (e != Error.None) + { + return e; + } } // Begin native render pass @@ -119,19 +123,25 @@ internal sealed class RenderGraphExecutor else { // Compute pass or standalone raster pass (not merged) or Unsafe pass - ExecuteBarriersForPass(cmd, logicalPassIndex, ref barrierIndex, compiledBarriers); + var e = ExecuteBarriersForPass(cmd, logicalPassIndex, ref barrierIndex, compiledBarriers); + if (e != Error.None) + { + return e; + } + pass.Execute(_context); logicalPassIndex++; } - } + + return Error.None; } /// /// Executes all barriers for a specific pass. /// Uses pre-compiled barriers and queries before state from ResourceManager. /// - private unsafe void ExecuteBarriersForPass( + private unsafe Error ExecuteBarriersForPass( ICommandBuffer cmd, int passIndex, ref int barrierIndex, @@ -158,7 +168,13 @@ internal sealed class RenderGraphExecutor var resourceHandle = resource.backingResource; // Always query the before state from ResourceManager (single source of truth) - var currentState = _resourceManager.ResourceDatabase.GetResourceBarrierData(resourceHandle).GetValueOrThrow(); + var currentStateResult = _resourceManager.ResourceDatabase.GetResourceBarrierData(resourceHandle); + if (currentStateResult.IsFailure) + { + return currentStateResult.Error; + } + + var currentState = currentStateResult.Value; BarrierLayout layoutBefore; BarrierAccess accessBefore; @@ -168,7 +184,13 @@ internal sealed class RenderGraphExecutor if (compiledBarrier.AliasingPredecessor.IsValid) { var predHandle = _resources.GetResource(compiledBarrier.AliasingPredecessor).backingResource; - var predState = _resourceManager.ResourceDatabase.GetResourceBarrierData(predHandle).GetValueOrThrow(); + var predStateResult = _resourceManager.ResourceDatabase.GetResourceBarrierData(predHandle); + if (predStateResult.IsFailure) + { + return predStateResult.Error; + } + + var predState = predStateResult.Value; layoutBefore = BarrierLayout.Undefined; accessBefore = BarrierAccess.NoAccess; @@ -184,9 +206,9 @@ internal sealed class RenderGraphExecutor var target = compiledBarrier.TargetState; // Skip if already in target state (optimization) - if (!compiledBarrier.AliasingPredecessor.IsValid && - layoutBefore == target.layout && - accessBefore == target.access && + if (!compiledBarrier.AliasingPredecessor.IsValid && + layoutBefore == target.layout && + accessBefore == target.access && syncBefore == target.sync) { continue; @@ -218,5 +240,7 @@ internal sealed class RenderGraphExecutor } Flush(); + + return Error.None; } } diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphHasher.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphHasher.cs index e515794..bbfe4e0 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphHasher.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphHasher.cs @@ -1,61 +1,43 @@ using Ghost.Core; -using Ghost.Graphics.Core; -using Ghost.Graphics.RHI; +using Ghost.Core.Utilities; using Misaki.HighPerformance.LowLevel.Buffer; -using Misaki.HighPerformance.LowLevel.Collections; using System.IO.Hashing; namespace Ghost.Graphics.RenderGraphModule; -/// -/// Computes structural hashes of render graphs for compilation caching. -/// Hashes are based on graph topology and resource configurations, not runtime values. -/// internal static class RenderGraphHasher { /// /// Computes a hash of the entire render graph structure. /// Used for cache invalidation - same hash means same compilation result. /// - public static unsafe ulong ComputeGraphHash(List passes, RenderGraphResourceRegistry resources) + public static ulong ComputeGraphHash(List passes, RenderGraphResourceRegistry resources) { using var scope = AllocationManager.CreateStackScope(); - var bufferPool = new UnsafeList(2048, scope.AllocationHandle); - var pData = (byte*)bufferPool.GetUnsafePtr(); - var offset = 0; + var writer = new BufferWriter(2048, scope.AllocationHandle); // Hash pass count - *(int*)(pData + offset) = passes.Count; - offset += sizeof(int); + writer.Write(passes.Count); // Hash each pass structure (excluding names) for (var i = 0; i < passes.Count; i++) { var pass = passes[i]; - *(RenderPassType*)(pData + offset) = pass.type; - offset += sizeof(RenderPassType); - - *(bool*)(pData + offset) = pass.allowCulling; - offset += sizeof(bool); - - *(bool*)(pData + offset) = pass.asyncCompute; - offset += sizeof(bool); + writer.Write(pass.type); + writer.Write(pass.allowCulling); + writer.Write(pass.asyncCompute); // Hash depth attachment - offset = ComputeTextureHash(pData, offset, pass.depthAccess.id, resources); + ComputeTextureHash(ref writer, pass.depthAccess.id, resources); - pData[offset] = (byte)pass.depthAccess.accessFlags; - offset += sizeof(AccessFlags); + writer.Write(pass.depthAccess.accessFlags); + writer.Write(pass.maxColorIndex); - *(int*)(pData + offset) = pass.maxColorIndex; - offset += sizeof(int); for (var j = 0; j <= pass.maxColorIndex; j++) { - offset = ComputeTextureHash(pData, offset, pass.colorAccess[j].id, resources); - - pData[offset] = (byte)pass.colorAccess[j].accessFlags; - offset += sizeof(AccessFlags); + ComputeTextureHash(ref writer, pass.colorAccess[j].id, resources); + writer.Write(pass.colorAccess[j].accessFlags); } for (var j = 0; j < (int)RenderGraphResourceType.Count; j++) @@ -64,45 +46,35 @@ internal static class RenderGraphHasher var writeList = pass.resourceWrites[j]; var createList = pass.resourceCreates[j]; - *(int*)(pData + offset) = readList.Count; - offset += sizeof(int); + writer.Write(readList.Count); for (var k = 0; k < readList.Count; k++) { - *(int*)(pData + offset) = readList[k].Value; - offset += sizeof(int); + writer.Write(readList[k].Value); } - *(int*)(pData + offset) = writeList.Count; - offset += sizeof(int); + writer.Write(writeList.Count); for (var k = 0; k < writeList.Count; k++) { - *(int*)(pData + offset) = writeList[k].Value; - offset += sizeof(int); + writer.Write(writeList[k].Value); } - *(int*)(pData + offset) = createList.Count; - offset += sizeof(int); + writer.Write(createList.Count); for (var k = 0; k < createList.Count; k++) { - *(int*)(pData + offset) = createList[k].Value; - offset += sizeof(int); + writer.Write(createList[k].Value); } - *(int*)(pData + offset) = pass.randomAccess.Count; - offset += sizeof(int); + writer.Write(pass.randomAccess.Count); for (var k = 0; k < pass.randomAccess.Count; k++) { - *(int*)(pData + offset) = pass.randomAccess[k].Value; - offset += sizeof(int); + writer.Write(pass.randomAccess[k].Value); } } - *(int*)(pData + offset) = pass.GetRenderFuncHashCode(); - offset += sizeof(int); + writer.Write(pass.GetRenderFuncHashCode()); } - var span = new Span(pData, offset); - return XxHash64.HashToUInt64(span); + return XxHash64.HashToUInt64(writer.AsSpan()); } /// @@ -110,68 +82,49 @@ internal static class RenderGraphHasher /// For imported textures, hashes the backing handle. /// For transient textures, hashes the descriptor (respecting size mode). /// - private static unsafe int ComputeTextureHash(byte* pData, int offset, Identifier texture, RenderGraphResourceRegistry resources) + private static void ComputeTextureHash(ref BufferWriter writer, Identifier texture, RenderGraphResourceRegistry resources) { if (texture.IsInvalid) { - return offset; + return; } var resource = resources.GetResource(texture.AsResource()); // Hash imported flag - *(pData + offset) = resource.isImported ? (byte)1 : (byte)0; - offset += sizeof(byte); + writer.Write(resource.isImported); // For imported textures, hash the backing resource handle if (resource.isImported) { - *(int*)(pData + offset) = resource.backingResource.GetHashCode(); - offset += sizeof(int); - return offset; + writer.Write(resource.backingResource.GetHashCode()); + return; } var desc = resource.rgTextureDesc; - // Hash format (structural) - *(TextureFormat*)(pData + offset) = desc.format; - offset += sizeof(TextureFormat); - - // Hash size mode (structural) - *(RGTextureSizeMode*)(pData + offset) = desc.sizeMode; - offset += sizeof(RGTextureSizeMode); + writer.Write(desc.format); + writer.Write(desc.sizeMode); // Hash size specification based on mode if (desc.sizeMode == RGTextureSizeMode.Absolute) { // Absolute mode: hash actual dimensions - *(uint*)(pData + offset) = desc.width; - offset += sizeof(uint); - *(uint*)(pData + offset) = desc.height; - offset += sizeof(uint); + writer.Write(desc.width); + writer.Write(desc.height); } else { // Relative mode: hash scale factors (NOT resolved dimensions) - *(float*)(pData + offset) = desc.scaleX; - offset += sizeof(float); - *(float*)(pData + offset) = desc.scaleY; - offset += sizeof(float); + writer.Write(desc.scaleX); + writer.Write(desc.scaleY); } // Hash other structural properties - *(TextureDimension*)(pData + offset) = desc.dimension; - offset += sizeof(TextureDimension); - *(uint*)(pData + offset) = desc.mipLevels; - offset += sizeof(uint); - *(TextureUsage*)(pData + offset) = desc.usage; - offset += sizeof(TextureUsage); - - *(bool*)(pData + offset) = desc.clearAtFirstUse; - offset += sizeof(bool); - *(bool*)(pData + offset) = desc.discardAtLastUse; - offset += sizeof(bool); - - return offset; + writer.Write(desc.dimension); + writer.Write(desc.mipLevels); + writer.Write(desc.usage); + writer.Write(desc.clearAtFirstUse); + writer.Write(desc.discardAtLastUse); } } diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphNativePass.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphNativePass.cs index 6ce926c..ae8844b 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphNativePass.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphNativePass.cs @@ -1,5 +1,3 @@ -using Ghost.Core; - namespace Ghost.Graphics.RenderGraphModule; /// @@ -9,35 +7,35 @@ namespace Ghost.Graphics.RenderGraphModule; internal sealed class NativeRenderPass { public int index; - + /// /// Indices of logical passes merged into this native render pass. /// public readonly List mergedPassIndices = new(4); - + /// /// Color attachments shared across all merged passes. /// public RenderTargetInfo[] colorAttachments = new RenderTargetInfo[8]; public int colorAttachmentCount; - + /// /// Depth-stencil attachment (optional). /// public DepthStencilInfo depthAttachment; public bool hasDepthAttachment; - + /// /// Range of logical passes included in this native pass. /// public int firstLogicalPass; public int lastLogicalPass; - + /// /// Whether UAV writes are allowed during this render pass. /// public bool allowUAVWrites; - + public void Reset() { index = -1; diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphPass.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphPass.cs index 4534e2f..bbf8fb5 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphPass.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphPass.cs @@ -44,7 +44,7 @@ internal abstract class RenderGraphPassBase public RenderGraphPassBase() { - for (int i = 0; i < (int)RenderGraphResourceType.Count; i++) + for (var i = 0; i < (int)RenderGraphResourceType.Count; i++) { resourceReads[i] = new List>(8); resourceWrites[i] = new List>(4); diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphResourcePool.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphResourcePool.cs index 6fe76ff..4ab8b7d 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphResourcePool.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphResourcePool.cs @@ -1,5 +1,4 @@ using Ghost.Core; -using Ghost.Graphics.Core; using Ghost.Graphics.RHI; using Misaki.HighPerformance.Buffer; @@ -85,15 +84,15 @@ internal sealed class RenderGraphResource public int index; public RenderGraphResourceType type; - + // Resource descriptors (only one is valid based on type) public RGTextureDesc rgTextureDesc; public BufferDesc bufferDesc; - + // Resolved dimensions (computed from rgTextureDesc + ViewState for textures) public uint resolvedWidth; public uint resolvedHeight; - + public bool isImported; public int firstUsePass = -1; public int lastUsePass = -1; @@ -145,8 +144,8 @@ internal sealed class RenderGraphResourceRegistry { get { - int count = 0; - for (int i = 0; i < _resources.Count; i++) + var count = 0; + for (var i = 0; i < _resources.Count; i++) { if (_resources[i].type == RenderGraphResourceType.Texture) count++; @@ -158,8 +157,8 @@ internal sealed class RenderGraphResourceRegistry { get { - int count = 0; - for (int i = 0; i < _resources.Count; i++) + var count = 0; + for (var i = 0; i < _resources.Count; i++) { if (_resources[i].type == RenderGraphResourceType.Buffer) count++; @@ -226,7 +225,7 @@ internal sealed class RenderGraphResourceRegistry return new Identifier(resource.index); } - + public Identifier ImportBuffer(ref readonly BufferDesc desc, Handle buffer, string name) { var resource = _pool.Rent(); @@ -245,7 +244,7 @@ internal sealed class RenderGraphResourceRegistry public Identifier CreateBuffer(ref readonly BufferDesc desc, string name) { var resource = _pool.Rent(); - resource.name= name; + resource.name = name; resource.type = RenderGraphResourceType.Buffer; resource.index = _resources.Count; resource.bufferDesc = desc; @@ -260,17 +259,17 @@ internal sealed class RenderGraphResourceRegistry { return _resources[resource.Value]; } - + public RenderGraphResource GetResource(Identifier texture) { return _resources[texture.Value]; } - + public RenderGraphResource GetResource(Identifier buffer) { return _resources[buffer.Value]; } - + /// /// Gets resource by global index. Use this when iterating over all resources. /// @@ -299,7 +298,7 @@ internal sealed class RenderGraphResourceRegistry resource.firstUsePass = passIndex; } } - + /// /// Resolves texture sizes based on current view state. /// Must be called after all resources are created and before compilation. @@ -311,7 +310,7 @@ internal sealed class RenderGraphResourceRegistry var res = _resources[i]; if (res.type != RenderGraphResourceType.Texture || res.isImported) continue; - + var desc = res.rgTextureDesc; if (desc.sizeMode == RGTextureSizeMode.Absolute) { diff --git a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphTypes.cs b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphTypes.cs index e31afe0..c8e8a33 100644 --- a/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphTypes.cs +++ b/src/Runtime/Ghost.Graphics/RenderGraphModule/RenderGraphTypes.cs @@ -1,5 +1,4 @@ using Ghost.Core; -using Ghost.Graphics.Core; using Ghost.Graphics.RHI; using System.Runtime.CompilerServices; @@ -22,7 +21,7 @@ public enum RGTextureSizeMode : byte /// Fixed pixel dimensions (width, height). /// Absolute, - + /// /// Scale relative to view state (scaleX * viewportWidth, scaleY * viewportHeight). /// @@ -40,7 +39,7 @@ public struct ViewState : IEquatable // For upscalers that need to know the original render target size before upscaling public uint actualWidth; public uint actualHeight; - + public ViewState(uint width, uint height, uint actualWidth, uint actualHeight) { viewportWidth = width; @@ -48,28 +47,28 @@ public struct ViewState : IEquatable this.actualWidth = actualWidth; this.actualHeight = actualHeight; } - + public readonly bool Equals(ViewState other) { return viewportWidth == other.viewportWidth && viewportHeight == other.viewportHeight && actualWidth == other.actualWidth && actualHeight == other.actualHeight; } - + public override readonly bool Equals(object? obj) { return obj is ViewState other && Equals(other); } - + public override readonly int GetHashCode() { return HashCode.Combine(viewportWidth, viewportHeight); } - + public static bool operator ==(ViewState left, ViewState right) { return left.Equals(right); } - + public static bool operator !=(ViewState left, ViewState right) { return !left.Equals(right); @@ -82,29 +81,29 @@ public struct ViewState : IEquatable public struct RGTextureDesc : IEquatable { public RGTextureSizeMode sizeMode; - + // Size specification (union-like - only one set is used based on sizeMode) public uint width; // For Absolute mode public uint height; // For Absolute mode public float scaleX; // For Relative mode public float scaleY; // For Relative mode - + // Common texture properties public TextureFormat format; public TextureDimension dimension; public uint mipLevels; public uint slice; public TextureUsage usage; - + public bool clearAtFirstUse; public bool discardAtLastUse; - + // Clear operation support public Color128 clearColor; public float clearDepth; public byte clearStencil; - + /// /// Creates a texture descriptor with absolute dimensions. /// @@ -137,7 +136,7 @@ public struct RGTextureDesc : IEquatable usage = usage }; } - + /// /// Creates a texture descriptor with relative dimensions (uniform scale). /// @@ -169,7 +168,7 @@ public struct RGTextureDesc : IEquatable usage = usage }; } - + /// /// Creates a texture descriptor with relative dimensions (non-uniform scale). /// @@ -203,7 +202,7 @@ public struct RGTextureDesc : IEquatable }; } - + /// /// Creates a depth texture descriptor with relative dimensions. /// @@ -233,7 +232,7 @@ public struct RGTextureDesc : IEquatable }; } - + /// /// Converts to RHI TextureDesc using resolved dimensions. /// @@ -250,7 +249,7 @@ public struct RGTextureDesc : IEquatable Usage = usage }; } - + public readonly bool Equals(RGTextureDesc other) { return sizeMode == other.sizeMode && @@ -266,12 +265,12 @@ public struct RGTextureDesc : IEquatable : scaleX == other.scaleX && scaleY == other.scaleY); } - + public override readonly bool Equals(object? obj) { return obj is RGTextureDesc other && Equals(other); } - + public override readonly int GetHashCode() { if (sizeMode == RGTextureSizeMode.Absolute) @@ -283,12 +282,12 @@ public struct RGTextureDesc : IEquatable return HashCode.Combine(sizeMode, scaleX, scaleY, format, dimension, mipLevels, slice, usage); } } - + public static bool operator ==(RGTextureDesc left, RGTextureDesc right) { return left.Equals(right); } - + public static bool operator !=(RGTextureDesc left, RGTextureDesc right) { return !left.Equals(right); diff --git a/src/Runtime/Ghost.Graphics/RenderPasses/MeshRenderPass.cs b/src/Runtime/Ghost.Graphics/RenderPasses/MeshRenderPass.cs index 0343a0b..8182913 100644 --- a/src/Runtime/Ghost.Graphics/RenderPasses/MeshRenderPass.cs +++ b/src/Runtime/Ghost.Graphics/RenderPasses/MeshRenderPass.cs @@ -107,8 +107,8 @@ internal class MeshRenderPass : IRenderPass private void CompileBlitShader(ref readonly RenderingContext ctx) { var shaderDescriptor = DSLShaderCompiler.CompileShader("F:/csharp/GhostEngine/src/Runtime/Ghost.Graphics/Shaders/Blit.gshdr", "C:/Users/Misaki/Downloads/Archive").GetValueOrThrow(); - _blitShader = ctx.ResourceAllocator.CreateGraphicsShader(shaderDescriptor); - _blitMaterial = ctx.ResourceAllocator.CreateMaterial(_blitShader); + _blitShader = ctx.ResourceManager.CreateGraphicsShader(shaderDescriptor); + _blitMaterial = ctx.ResourceManager.CreateMaterial(_blitShader); var config = new ShaderCompilationConfig { @@ -132,8 +132,8 @@ internal class MeshRenderPass : IRenderPass var shaderDescriptor = DSLShaderCompiler.CompileShader("F:/csharp/GhostEngine/src/Runtime/Ghost.Graphics/test.gshdr", "C:/Users/Misaki/Downloads/Archive").GetValueOrThrow(); - _shader = ctx.ResourceAllocator.CreateGraphicsShader(shaderDescriptor); - _material = ctx.ResourceAllocator.CreateMaterial(_shader); + _shader = ctx.ResourceManager.CreateGraphicsShader(shaderDescriptor); + _material = ctx.ResourceManager.CreateMaterial(_shader); for (var i = 0; i < shaderDescriptor.passes.Length; i++) { @@ -320,7 +320,7 @@ internal class MeshRenderPass : IRenderPass { foreach (var texture in _textures) { - resourceManager.ResourceDatabase.ScheduleReleaseResource(texture.AsResource()); + resourceManager.ResourceDatabase.ReleaseResource(texture.AsResource()); } } } diff --git a/src/Runtime/Ghost.Graphics/ResourceManager.cs b/src/Runtime/Ghost.Graphics/ResourceManager.cs index cf62653..b2ad0ce 100644 --- a/src/Runtime/Ghost.Graphics/ResourceManager.cs +++ b/src/Runtime/Ghost.Graphics/ResourceManager.cs @@ -222,14 +222,13 @@ internal sealed class ResourceManager : IResourceManager, IDisposable { ObjectDisposedException.ThrowIf(_disposed, this); - ref var mesh = ref _meshes.GetElementReferenceAt(handle.ID, handle.Generation, out var exist); - if (!exist) + if (!_meshes.TryGetElementAt(handle.ID, handle.Generation, out var mesh)) { return; } - ReleaseResource(mesh); _meshes.Remove(handle.ID, handle.Generation); + mesh.ReleaseResource(_resourceDatabase); } public bool HasMaterial(Handle handle) @@ -253,14 +252,14 @@ internal sealed class ResourceManager : IResourceManager, IDisposable { ObjectDisposedException.ThrowIf(_disposed, this); - ref var material = ref _materials.GetElementReferenceAt(handle.ID, handle.Generation, out var exist); + var material = _materials.GetElementReferenceAt(handle.ID, handle.Generation, out var exist); if (!exist) { return; } - ReleaseResource(material); _materials.Remove(handle.ID, handle.Generation); + material.ReleaseResource(_resourceDatabase); } public bool HasShader(Identifier id) @@ -288,14 +287,8 @@ internal sealed class ResourceManager : IResourceManager, IDisposable return; } - ref var shader = ref _shaders[id.Value]!; - ReleaseResource(shader); - } - - private void ReleaseResource(T resource) - where T : IResourceReleasable - { - resource.ReleaseResource(_resourceDatabase); + var shader = _shaders[id.Value]; + shader.ReleaseResource(_resourceDatabase); } public void Dispose() @@ -307,17 +300,17 @@ internal sealed class ResourceManager : IResourceManager, IDisposable foreach (var mesh in _meshes) { - ReleaseResource(mesh); + mesh.ReleaseResource(_resourceDatabase); } foreach (var material in _materials) { - ReleaseResource(material); + material.ReleaseResource(_resourceDatabase); } foreach (var shader in _shaders) { - ReleaseResource(shader); + shader.ReleaseResource(_resourceDatabase); } _meshes.Dispose(); diff --git a/src/Test/Ghost.Entities.Test/EntityQueryTest.cs b/src/Test/Ghost.Entities.Test/EntityQueryTest.cs index 79bc07a..a0eeaa3 100644 --- a/src/Test/Ghost.Entities.Test/EntityQueryTest.cs +++ b/src/Test/Ghost.Entities.Test/EntityQueryTest.cs @@ -42,7 +42,7 @@ public partial class EntityQueryTest : ITest { var entities = (Span)stackalloc Entity[1000]; - using var scope = AllocationManager.CreateStackScope(); + using var scope = AllocationManager.CreateStackScope(); using var set = new ComponentSet(scope.AllocationHandle, ComponentTypeID.Value); _world.EntityManager.CreateEntities(entities, set); diff --git a/src/Test/Ghost.Entities.Test/Program.cs b/src/Test/Ghost.Entities.Test/Program.cs index 3dccd70..5ecacb9 100644 --- a/src/Test/Ghost.Entities.Test/Program.cs +++ b/src/Test/Ghost.Entities.Test/Program.cs @@ -1,7 +1,5 @@ using BenchmarkDotNet.Running; using Ghost.Entities.Test; -using Ghost.Test.Core; -using Misaki.HighPerformance.LowLevel.Buffer; //AllocationManager.EnableDebugLayer(); //TestRunner.Run(); diff --git a/src/Test/Ghost.Entities.Test/SystemTest.cs b/src/Test/Ghost.Entities.Test/SystemTest.cs index 4902143..ae445aa 100644 --- a/src/Test/Ghost.Entities.Test/SystemTest.cs +++ b/src/Test/Ghost.Entities.Test/SystemTest.cs @@ -11,7 +11,7 @@ internal class SystemTest : ITest _world = World.Create(); } - public void Run() + public void Run() { var group = _world.SystemManager.GetSystem(); group.AddSystem(); diff --git a/src/Test/Ghost.Graphics.Test/Controls/DebugConsole.xaml.cs b/src/Test/Ghost.Graphics.Test/Controls/DebugConsole.xaml.cs index 3639dd6..745d557 100644 --- a/src/Test/Ghost.Graphics.Test/Controls/DebugConsole.xaml.cs +++ b/src/Test/Ghost.Graphics.Test/Controls/DebugConsole.xaml.cs @@ -1,13 +1,11 @@ -using System.Collections.ObjectModel; - using Ghost.Graphics.Test.Models; using Ghost.Graphics.Test.Services; - using Microsoft.UI; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Data; using Microsoft.UI.Xaml.Media; +using System.Collections.ObjectModel; namespace Ghost.Graphics.Test.Controls; diff --git a/src/Test/Ghost.Graphics.Test/Windows/GraphicsTestWindow.xaml.cs b/src/Test/Ghost.Graphics.Test/Windows/GraphicsTestWindow.xaml.cs index f15b71b..9e3b051 100644 --- a/src/Test/Ghost.Graphics.Test/Windows/GraphicsTestWindow.xaml.cs +++ b/src/Test/Ghost.Graphics.Test/Windows/GraphicsTestWindow.xaml.cs @@ -4,7 +4,6 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Media; using Misaki.HighPerformance.Mathematics; -using static Ghost.Graphics.D3D12.D3D12ResourceDatabase; namespace Ghost.Graphics.Test.Windows; diff --git a/src/Test/Ghost.MicroTest/NvttBindingTest.cs b/src/Test/Ghost.MicroTest/NvttBindingTest.cs index eeb171c..e831a82 100644 --- a/src/Test/Ghost.MicroTest/NvttBindingTest.cs +++ b/src/Test/Ghost.MicroTest/NvttBindingTest.cs @@ -38,18 +38,18 @@ internal sealed unsafe class NvttBindingTest : ITest { // ---- Test 1: Version --------------------------------------------------- Console.Write("[Test 1] nvttVersion ... "); - uint version = NvttGlobal.Version; + var version = NvttGlobal.Version; Assert(version > 0, $"Expected version > 0, got {version}"); Console.WriteLine($"OK (version = {version >> 16}.{(version >> 8) & 0xFF}.{version & 0xFF})"); // ---- Test 2: CUDA support query (must not crash) ---------------------- Console.Write("[Test 2] IsCudaSupported ... "); - bool cuda = NvttGlobal.IsCudaSupported; + var cuda = NvttGlobal.IsCudaSupported; Console.WriteLine($"OK (cuda = {cuda})"); // ---- Test 3: Global message callback ---------------------------------- Console.Write("[Test 3] SetMessageCallback ... "); - int callbackFired = 0; + var callbackFired = 0; using (var token = NvttGlobal.SetMessageCallback((severity, error, msg) => { callbackFired++; @@ -66,7 +66,7 @@ internal sealed unsafe class NvttBindingTest : ITest $"Image not found: '{_IMAGE_PATH}'. Edit _IMAGE_PATH before running."); using var surface = new NvttSurfaceHandle(); - bool loaded = surface.Load(_IMAGE_PATH, out bool hasAlpha); + var loaded = surface.Load(_IMAGE_PATH, out var hasAlpha); Assert(loaded, "nvttSurfaceLoad returned false"); Assert(!surface.IsNull, "Surface is null after load"); Assert(surface.Width > 0 && surface.Height > 0, @@ -91,8 +91,8 @@ internal sealed unsafe class NvttBindingTest : ITest // ---- Test 7: CountMipmaps --------------------------------------------- Console.Write("[Test 7] CountMipmaps ... "); - int mipCount = surface.CountMipmaps(); - int expectedMax = (int)Math.Log2(Math.Max(surface.Width, surface.Height)) + 1; + var mipCount = surface.CountMipmaps(); + var expectedMax = (int)Math.Log2(Math.Max(surface.Width, surface.Height)) + 1; Assert(mipCount > 0 && mipCount <= expectedMax, $"Unexpected mip count: {mipCount} (expected 1..{expectedMax})"); Console.WriteLine($"OK ({mipCount} levels)"); @@ -100,16 +100,16 @@ internal sealed unsafe class NvttBindingTest : ITest // ---- Test 8: In-memory BC7 compression + mip chain ------------------- Console.Write("[Test 8] Compress BC7 in-memory ... "); long totalBytesReceived = 0; - int imagesBegun = 0; + var imagesBegun = 0; using var compOpts = new NvttCompressionOptionsHandle(); - compOpts.Format = NvttFormat.NVTT_Format_BC7; + compOpts.Format = NvttFormat.NVTT_Format_BC7; compOpts.Quality = NvttQuality.NVTT_Quality_Fastest; using var outOpts = new NvttOutputOptionsHandle(); outOpts.OutputHeader = true; - outOpts.Srgb = true; - outOpts.Container = NvttContainer.NVTT_Container_DDS10; + outOpts.Srgb = true; + outOpts.Container = NvttContainer.NVTT_Container_DDS10; outOpts.SetOutputHandler( beginImage: (size, w, h, d, face, mip) => @@ -130,12 +130,12 @@ internal sealed unsafe class NvttBindingTest : ITest ctx.SetCudaAcceleration(false); // CPU only for the test using var mip = surface.Clone(); - bool headerOk = ctx.OutputHeader(mip, mipCount, compOpts, outOpts); + var headerOk = ctx.OutputHeader(mip, mipCount, compOpts, outOpts); Assert(headerOk, "OutputHeader returned false"); - for (int level = 0; level < mipCount; level++) + for (var level = 0; level < mipCount; level++) { - bool compressOk = ctx.Compress(mip, face: 0, mipmap: level, compOpts, outOpts); + var compressOk = ctx.Compress(mip, face: 0, mipmap: level, compOpts, outOpts); Assert(compressOk, $"Compress returned false at mip level {level}"); if (level + 1 < mipCount) @@ -150,7 +150,7 @@ internal sealed unsafe class NvttBindingTest : ITest // ---- Test 9: EstimateSize consistency --------------------------------- Console.Write("[Test 9] EstimateSize ... "); - int estimated = ctx.EstimateSize(surface, mipCount, compOpts); + var estimated = ctx.EstimateSize(surface, mipCount, compOpts); // Estimate can differ from actual due to header overhead; just sanity-check it's > 0. Assert(estimated > 0, $"EstimateSize returned {estimated}"); Console.WriteLine($"OK (estimated = {estimated:N0} bytes, actual = {totalBytesReceived:N0} bytes)"); @@ -159,19 +159,19 @@ internal sealed unsafe class NvttBindingTest : ITest Console.Write("[Test 10] Compress to file ... "); using var outOptsFile = new NvttOutputOptionsHandle(); outOptsFile.OutputHeader = true; - outOptsFile.Srgb = true; - outOptsFile.Container = NvttContainer.NVTT_Container_DDS10; - outOptsFile.FileName = _outputDdsPath; + outOptsFile.Srgb = true; + outOptsFile.Container = NvttContainer.NVTT_Container_DDS10; + outOptsFile.FileName = _outputDdsPath; using var ctxFile = new NvttContextHandle(); using var mipFile = surface.Clone(); - bool fileHeaderOk = ctxFile.OutputHeader(mipFile, mipCount, compOpts, outOptsFile); + var fileHeaderOk = ctxFile.OutputHeader(mipFile, mipCount, compOpts, outOptsFile); Assert(fileHeaderOk, "File OutputHeader returned false"); - for (int level = 0; level < mipCount; level++) + for (var level = 0; level < mipCount; level++) { - bool ok = ctxFile.Compress(mipFile, face: 0, mipmap: level, compOpts, outOptsFile); + var ok = ctxFile.Compress(mipFile, face: 0, mipmap: level, compOpts, outOptsFile); Assert(ok, $"File Compress returned false at level {level}"); if (level + 1 < mipCount) @@ -180,7 +180,7 @@ internal sealed unsafe class NvttBindingTest : ITest Assert(File.Exists(_outputDdsPath), $"DDS output file was not created: {_outputDdsPath}"); - long fileSize = new FileInfo(_outputDdsPath).Length; + var fileSize = new FileInfo(_outputDdsPath).Length; Assert(fileSize > 128, $"DDS file suspiciously small: {fileSize} bytes"); Console.WriteLine($"OK ({fileSize:N0} bytes → {_outputDdsPath})"); diff --git a/src/Test/Ghost.MicroTest/Program.cs b/src/Test/Ghost.MicroTest/Program.cs index d72c3ad..3043b77 100644 --- a/src/Test/Ghost.MicroTest/Program.cs +++ b/src/Test/Ghost.MicroTest/Program.cs @@ -1,4 +1,4 @@ -using Ghost.Test.Core; using Ghost.MicroTest; +using Ghost.Test.Core; TestRunner.Run(); diff --git a/src/Test/Ghost.Shader.Test/Program.cs b/src/Test/Ghost.Shader.Test/Program.cs index e53ffff..3eeed06 100644 --- a/src/Test/Ghost.Shader.Test/Program.cs +++ b/src/Test/Ghost.Shader.Test/Program.cs @@ -1,4 +1,3 @@ -using Ghost.DSL.ShaderCompiler; using Misaki.HighPerformance.Mathematics; using System.Numerics; diff --git a/src/Test/Ghost.Test.Core/ITest.cs b/src/Test/Ghost.Test.Core/ITest.cs index 58ddade..60a0f9e 100644 --- a/src/Test/Ghost.Test.Core/ITest.cs +++ b/src/Test/Ghost.Test.Core/ITest.cs @@ -2,9 +2,9 @@ namespace Ghost.Test.Core; public interface ITest { - public void Setup(); + void Setup(); - public void Run(); + void Run(); - public void Cleanup(); + void Cleanup(); } diff --git a/src/Test/Ghost.UnitTest/AssetDatabaseIntegrationTest.cs b/src/Test/Ghost.UnitTest/AssetDatabaseIntegrationTest.cs index e1c30e6..ad302a2 100644 --- a/src/Test/Ghost.UnitTest/AssetDatabaseIntegrationTest.cs +++ b/src/Test/Ghost.UnitTest/AssetDatabaseIntegrationTest.cs @@ -1,5 +1,3 @@ -using Ghost.Editor.Core.AssetHandle; -using Ghost.Data.Services; using Ghost.Core; namespace Ghost.UnitTest; @@ -330,7 +328,7 @@ public class AssetDatabaseIntegrationTest var tasks = new List(); var fileNames = new List(); - for (int i = 0; i < 10; i++) + for (var i = 0; i < 10; i++) { var fileName = $"race{i}.txt"; fileNames.Add(fileName); diff --git a/src/Test/Ghost.UnitTest/AssetMetaTest.cs b/src/Test/Ghost.UnitTest/AssetMetaTest.cs index 0d13dc1..36b4447 100644 --- a/src/Test/Ghost.UnitTest/AssetMetaTest.cs +++ b/src/Test/Ghost.UnitTest/AssetMetaTest.cs @@ -1,5 +1,3 @@ -using Ghost.Editor.Core.AssetHandle; -using Ghost.Editor.Core.AssetHandle.Importers; using System.Text.Json; namespace Ghost.UnitTest; diff --git a/src/ThridParty/Ghost.FMOD/Core/fmod.cs b/src/ThridParty/Ghost.FMOD/Core/fmod.cs index 97bc1bf..135b747 100644 --- a/src/ThridParty/Ghost.FMOD/Core/fmod.cs +++ b/src/ThridParty/Ghost.FMOD/Core/fmod.cs @@ -331,8 +331,8 @@ namespace Ghost.FMOD.Core [StructLayout(LayoutKind.Sequential)] public struct PLUGINLIST { - PLUGINTYPE type; - IntPtr description; + private PLUGINTYPE type; + private IntPtr description; } [Flags] @@ -1396,8 +1396,7 @@ namespace Ghost.FMOD.Core // System information functions. public RESULT getVersion(out uint version) { - uint buildnumber; - return getVersion(out version, out buildnumber); + return getVersion(out version, out var buildnumber); } public RESULT getVersion(out uint version, out uint buildnumber) { @@ -2189,7 +2188,7 @@ namespace Ghost.FMOD.Core /* 'ChannelControl' API */ - interface IChannelControl + internal interface IChannelControl { RESULT getSystemObject(out System system); @@ -3539,8 +3538,7 @@ namespace Ghost.FMOD.Core } public RESULT getParameterInfo(int index, out DSP_PARAMETER_DESC desc) { - IntPtr descPtr; - var result = FMOD5_DSP_GetParameterInfo(this.handle, index, out descPtr); + var result = FMOD5_DSP_GetParameterInfo(this.handle, index, out var descPtr); desc = (DSP_PARAMETER_DESC)Marshal.PtrToStructure(descPtr); return result; } @@ -4060,7 +4058,7 @@ namespace Ghost.FMOD.Core [StructLayout(LayoutKind.Sequential)] public struct StringWrapper { - IntPtr nativeUtf8Ptr; + private IntPtr nativeUtf8Ptr; public StringWrapper(IntPtr ptr) { @@ -4117,15 +4115,15 @@ namespace Ghost.FMOD.Core } } - static class StringHelper + internal static class StringHelper { public class ThreadSafeEncoding : IDisposable { - UTF8Encoding encoding = new UTF8Encoding(); - byte[] encodedBuffer = new byte[128]; - char[] decodedBuffer = new char[128]; - bool inUse; - GCHandle gcHandle; + private UTF8Encoding encoding = new UTF8Encoding(); + private byte[] encodedBuffer = new byte[128]; + private char[] decodedBuffer = new char[128]; + private bool inUse; + private GCHandle gcHandle; public bool InUse() { @@ -4234,7 +4232,7 @@ namespace Ghost.FMOD.Core } } - static List encoders = new List(1); + private static List encoders = new List(1); public static ThreadSafeEncoding GetFreeHelper() { diff --git a/src/ThridParty/Ghost.FMOD/Studio/fmod_studio.cs b/src/ThridParty/Ghost.FMOD/Studio/fmod_studio.cs index f219858..d36e242 100644 --- a/src/ThridParty/Ghost.FMOD/Studio/fmod_studio.cs +++ b/src/ThridParty/Ghost.FMOD/Studio/fmod_studio.cs @@ -170,13 +170,13 @@ namespace Ghost.FMOD.Studio } // This is only need for loading memory and given our C# wrapper LOAD_MEMORY_POINT isn't feasible anyway - enum LOAD_MEMORY_MODE : int + internal enum LOAD_MEMORY_MODE : int { LOAD_MEMORY, LOAD_MEMORY_POINT, } - enum LOAD_MEMORY_ALIGNMENT : int + internal enum LOAD_MEMORY_ALIGNMENT : int { VALUE = 32 } @@ -235,7 +235,7 @@ namespace Ghost.FMOD.Studio }; [StructLayout(LayoutKind.Explicit)] - struct Union_IntBoolFloatString + internal struct Union_IntBoolFloatString { [FieldOffset(0)] public int intvalue; @@ -529,8 +529,7 @@ namespace Ghost.FMOD.Studio using (var encoder = StringHelper.GetFreeHelper()) { var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; - var result = FMOD_Studio_System_GetParameterLabelByID(this.handle, id, labelindex, stringMem, 256, out retrieved); + var result = FMOD_Studio_System_GetParameterLabelByID(this.handle, id, labelindex, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { @@ -550,8 +549,7 @@ namespace Ghost.FMOD.Studio } public RESULT getParameterByID(PARAMETER_ID id, out float value) { - float finalValue; - return getParameterByID(id, out value, out finalValue); + return getParameterByID(id, out value, out var finalValue); } public RESULT getParameterByID(PARAMETER_ID id, out float value, out float finalvalue) { @@ -574,8 +572,7 @@ namespace Ghost.FMOD.Studio } public RESULT getParameterByName(string name, out float value) { - float finalValue; - return getParameterByName(name, out value, out finalValue); + return getParameterByName(name, out value, out var finalValue); } public RESULT getParameterByName(string name, out float value, out float finalvalue) { @@ -612,8 +609,7 @@ namespace Ghost.FMOD.Studio using var encoder = StringHelper.GetFreeHelper(); var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; - var result = FMOD_Studio_System_LookupPath(this.handle, ref id, stringMem, 256, out retrieved); + var result = FMOD_Studio_System_LookupPath(this.handle, ref id, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { @@ -1014,8 +1010,7 @@ namespace Ghost.FMOD.Studio using var encoder = StringHelper.GetFreeHelper(); var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; - var result = FMOD_Studio_EventDescription_GetParameterLabelByIndex(this.handle, index, labelindex, stringMem, 256, out retrieved); + var result = FMOD_Studio_EventDescription_GetParameterLabelByIndex(this.handle, index, labelindex, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { @@ -1038,9 +1033,8 @@ namespace Ghost.FMOD.Studio using var encoder = StringHelper.GetFreeHelper(); var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; var nameBytes = encoder.byteFromStringUTF8(name); - var result = FMOD_Studio_EventDescription_GetParameterLabelByName(this.handle, nameBytes, labelindex, stringMem, 256, out retrieved); + var result = FMOD_Studio_EventDescription_GetParameterLabelByName(this.handle, nameBytes, labelindex, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { @@ -1063,8 +1057,7 @@ namespace Ghost.FMOD.Studio using var encoder = StringHelper.GetFreeHelper(); var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; - var result = FMOD_Studio_EventDescription_GetParameterLabelByID(this.handle, id, labelindex, stringMem, 256, out retrieved); + var result = FMOD_Studio_EventDescription_GetParameterLabelByID(this.handle, id, labelindex, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { @@ -1413,8 +1406,7 @@ namespace Ghost.FMOD.Studio } public RESULT getParameterByID(PARAMETER_ID id, out float value) { - float finalvalue; - return getParameterByID(id, out value, out finalvalue); + return getParameterByID(id, out value, out var finalvalue); } public RESULT getParameterByID(PARAMETER_ID id, out float value, out float finalvalue) { @@ -1437,8 +1429,7 @@ namespace Ghost.FMOD.Studio } public RESULT getParameterByName(string name, out float value) { - float finalValue; - return getParameterByName(name, out value, out finalValue); + return getParameterByName(name, out value, out var finalValue); } public RESULT getParameterByName(string name, out float value, out float finalvalue) { @@ -1608,8 +1599,7 @@ namespace Ghost.FMOD.Studio using var encoder = StringHelper.GetFreeHelper(); var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; - var result = FMOD_Studio_Bus_GetPath(this.handle, stringMem, 256, out retrieved); + var result = FMOD_Studio_Bus_GetPath(this.handle, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { @@ -1628,8 +1618,7 @@ namespace Ghost.FMOD.Studio } public RESULT getVolume(out float volume) { - float finalVolume; - return getVolume(out volume, out finalVolume); + return getVolume(out volume, out var finalVolume); } public RESULT getVolume(out float volume, out float finalvolume) { @@ -1762,8 +1751,7 @@ namespace Ghost.FMOD.Studio using var encoder = StringHelper.GetFreeHelper(); var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; - var result = FMOD_Studio_VCA_GetPath(this.handle, stringMem, 256, out retrieved); + var result = FMOD_Studio_VCA_GetPath(this.handle, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { @@ -1781,8 +1769,7 @@ namespace Ghost.FMOD.Studio } public RESULT getVolume(out float volume) { - float finalVolume; - return getVolume(out volume, out finalVolume); + return getVolume(out volume, out var finalVolume); } public RESULT getVolume(out float volume, out float finalvolume) { @@ -1845,8 +1832,7 @@ namespace Ghost.FMOD.Studio using var encoder = StringHelper.GetFreeHelper(); var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; - var result = FMOD_Studio_Bank_GetPath(this.handle, stringMem, 256, out retrieved); + var result = FMOD_Studio_Bank_GetPath(this.handle, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { @@ -1895,8 +1881,7 @@ namespace Ghost.FMOD.Studio using var encoder = StringHelper.GetFreeHelper(); var stringMem = Marshal.AllocHGlobal(256); - var retrieved = 0; - var result = FMOD_Studio_Bank_GetStringInfo(this.handle, index, out id, stringMem, 256, out retrieved); + var result = FMOD_Studio_Bank_GetStringInfo(this.handle, index, out id, stringMem, 256, out var retrieved); if (result == RESULT.ERR_TRUNCATED) { diff --git a/src/ThridParty/Ghost.MeshOptimizer/meshopt_Allocator.cs b/src/ThridParty/Ghost.MeshOptimizer/meshopt_Allocator.cs index 2f7c873..a6295be 100644 --- a/src/ThridParty/Ghost.MeshOptimizer/meshopt_Allocator.cs +++ b/src/ThridParty/Ghost.MeshOptimizer/meshopt_Allocator.cs @@ -1,4 +1,3 @@ -using Ghost.Zeux.MeshOptimizer; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/ThridParty/Ghost.MeshOptimizer/meshopt_Bounds.cs b/src/ThridParty/Ghost.MeshOptimizer/meshopt_Bounds.cs index 004bcfe..88b2cf1 100644 --- a/src/ThridParty/Ghost.MeshOptimizer/meshopt_Bounds.cs +++ b/src/ThridParty/Ghost.MeshOptimizer/meshopt_Bounds.cs @@ -1,4 +1,3 @@ -using Ghost.Zeux.MeshOptimizer; using System.Runtime.CompilerServices; namespace Ghost.MeshOptimizer diff --git a/src/ThridParty/Ghost.MeshOptimizer/meshopt_CoverageStatistics.cs b/src/ThridParty/Ghost.MeshOptimizer/meshopt_CoverageStatistics.cs index f718ff0..1d6e907 100644 --- a/src/ThridParty/Ghost.MeshOptimizer/meshopt_CoverageStatistics.cs +++ b/src/ThridParty/Ghost.MeshOptimizer/meshopt_CoverageStatistics.cs @@ -1,4 +1,3 @@ -using Ghost.Zeux.MeshOptimizer; using System.Runtime.CompilerServices; namespace Ghost.MeshOptimizer diff --git a/src/ThridParty/Ghost.MeshOptimizer/meshopt_Meshlet.cs b/src/ThridParty/Ghost.MeshOptimizer/meshopt_Meshlet.cs index 0ac9b78..361fea1 100644 --- a/src/ThridParty/Ghost.MeshOptimizer/meshopt_Meshlet.cs +++ b/src/ThridParty/Ghost.MeshOptimizer/meshopt_Meshlet.cs @@ -1,5 +1,3 @@ -using Ghost.Zeux.MeshOptimizer; - namespace Ghost.MeshOptimizer { public partial struct meshopt_Meshlet diff --git a/src/ThridParty/Ghost.MeshOptimizer/meshopt_OverdrawStatistics.cs b/src/ThridParty/Ghost.MeshOptimizer/meshopt_OverdrawStatistics.cs index 9f143b0..618d4c7 100644 --- a/src/ThridParty/Ghost.MeshOptimizer/meshopt_OverdrawStatistics.cs +++ b/src/ThridParty/Ghost.MeshOptimizer/meshopt_OverdrawStatistics.cs @@ -1,5 +1,3 @@ -using Ghost.Zeux.MeshOptimizer; - namespace Ghost.MeshOptimizer { public partial struct meshopt_OverdrawStatistics diff --git a/src/ThridParty/Ghost.MeshOptimizer/meshopt_Stream.cs b/src/ThridParty/Ghost.MeshOptimizer/meshopt_Stream.cs index ed4cc8a..a305fdd 100644 --- a/src/ThridParty/Ghost.MeshOptimizer/meshopt_Stream.cs +++ b/src/ThridParty/Ghost.MeshOptimizer/meshopt_Stream.cs @@ -1,5 +1,3 @@ -using Ghost.Zeux.MeshOptimizer; - namespace Ghost.MeshOptimizer { public unsafe partial struct meshopt_Stream diff --git a/src/ThridParty/Ghost.MeshOptimizer/meshopt_VertexCacheStatistics.cs b/src/ThridParty/Ghost.MeshOptimizer/meshopt_VertexCacheStatistics.cs index 883efe7..2b154a3 100644 --- a/src/ThridParty/Ghost.MeshOptimizer/meshopt_VertexCacheStatistics.cs +++ b/src/ThridParty/Ghost.MeshOptimizer/meshopt_VertexCacheStatistics.cs @@ -1,5 +1,3 @@ -using Ghost.Zeux.MeshOptimizer; - namespace Ghost.MeshOptimizer { public partial struct meshopt_VertexCacheStatistics diff --git a/src/ThridParty/Ghost.MeshOptimizer/meshopt_VertexFetchStatistics.cs b/src/ThridParty/Ghost.MeshOptimizer/meshopt_VertexFetchStatistics.cs index 1545a93..dfd2c38 100644 --- a/src/ThridParty/Ghost.MeshOptimizer/meshopt_VertexFetchStatistics.cs +++ b/src/ThridParty/Ghost.MeshOptimizer/meshopt_VertexFetchStatistics.cs @@ -1,5 +1,3 @@ -using Ghost.Zeux.MeshOptimizer; - namespace Ghost.MeshOptimizer { public partial struct meshopt_VertexFetchStatistics diff --git a/src/ThridParty/Ghost.Nvtt/Native/NativeAnnotationAttribute.cs b/src/ThridParty/Ghost.Nvtt/Native/NativeAnnotationAttribute.cs index 056449f..5d05a59 100644 --- a/src/ThridParty/Ghost.Nvtt/Native/NativeAnnotationAttribute.cs +++ b/src/ThridParty/Ghost.Nvtt/Native/NativeAnnotationAttribute.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics; namespace Ghost.Nvtt.Native diff --git a/src/ThridParty/Ghost.Nvtt/Native/NativeTypeNameAttribute.cs b/src/ThridParty/Ghost.Nvtt/Native/NativeTypeNameAttribute.cs index 911eac8..1f2d211 100644 --- a/src/ThridParty/Ghost.Nvtt/Native/NativeTypeNameAttribute.cs +++ b/src/ThridParty/Ghost.Nvtt/Native/NativeTypeNameAttribute.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics; namespace Ghost.Nvtt.Native diff --git a/src/ThridParty/Ghost.Nvtt/NvttOutputOptions.cs b/src/ThridParty/Ghost.Nvtt/NvttOutputOptions.cs index f0fa36e..b943a1c 100644 --- a/src/ThridParty/Ghost.Nvtt/NvttOutputOptions.cs +++ b/src/ThridParty/Ghost.Nvtt/NvttOutputOptions.cs @@ -32,15 +32,15 @@ public sealed unsafe class NvttOutputOptionsHandle : IDisposable private delegate void ErrorDelegate(Ghost.Nvtt.Native.NvttError error); // Pinned delegate instances – must stay alive as long as native code may call them. - private BeginImageDelegate? _beginImageDelegate; - private OutputDataDelegate? _outputDataDelegate; - private ErrorDelegate? _errorDelegate; + private BeginImageDelegate? _beginImageDelegate; + private OutputDataDelegate? _outputDataDelegate; + private ErrorDelegate? _errorDelegate; // Managed user-facing callbacks. private Action? _beginImage; - private Func? _outputData; - private Action? _endImage; - private Action? _errorHandler; + private Func? _outputData; + private Action? _endImage; + private Action? _errorHandler; // ------------------------------------------------------------------------- // Construction / destruction @@ -58,7 +58,7 @@ public sealed unsafe class NvttOutputOptionsHandle : IDisposable // Release delegate references so GC can collect them. _beginImageDelegate = null; _outputDataDelegate = null; - _errorDelegate = null; + _errorDelegate = null; } // ------------------------------------------------------------------------- @@ -142,7 +142,7 @@ public sealed unsafe class NvttOutputOptionsHandle : IDisposable ThrowIfDisposed(); _beginImage = beginImage; _outputData = outputData; - _endImage = endImage; + _endImage = endImage; RebindOutputHandler(); } @@ -173,13 +173,13 @@ public sealed unsafe class NvttOutputOptionsHandle : IDisposable _outputDataDelegate = (data, size, lastChunk) => { - bool ok = outputData?.Invoke((nint)data, size) ?? true; + var ok = outputData?.Invoke((nint)data, size) ?? true; return ok ? Ghost.Nvtt.Native.NvttBoolean.NVTT_True : Ghost.Nvtt.Native.NvttBoolean.NVTT_False; }; - nint beginPtr = Marshal.GetFunctionPointerForDelegate(_beginImageDelegate); - nint outputPtr = Marshal.GetFunctionPointerForDelegate(_outputDataDelegate); + var beginPtr = Marshal.GetFunctionPointerForDelegate(_beginImageDelegate); + var outputPtr = Marshal.GetFunctionPointerForDelegate(_outputDataDelegate); Api.nvttSetOutputOptionsOutputHandler( _ptr, @@ -193,7 +193,7 @@ public sealed unsafe class NvttOutputOptionsHandle : IDisposable var handler = _errorHandler; _errorDelegate = error => handler?.Invoke(error); - nint errorPtr = Marshal.GetFunctionPointerForDelegate(_errorDelegate); + var errorPtr = Marshal.GetFunctionPointerForDelegate(_errorDelegate); Api.nvttSetOutputOptionsErrorHandler( _ptr, (delegate* unmanaged[Cdecl])errorPtr); diff --git a/src/ThridParty/Ghost.Nvtt/NvttSurface.cs b/src/ThridParty/Ghost.Nvtt/NvttSurface.cs index 770a05d..515cb46 100644 --- a/src/ThridParty/Ghost.Nvtt/NvttSurface.cs +++ b/src/ThridParty/Ghost.Nvtt/NvttSurface.cs @@ -1,6 +1,3 @@ -using Ghost.Nvtt.Native; -using System.Runtime.InteropServices; - namespace Ghost.Nvtt; /// @@ -20,7 +17,7 @@ public sealed unsafe class NvttSurfaceHandle : IDisposable // ------------------------------------------------------------------------- // Construction / destruction // ------------------------------------------------------------------------- - + public NvttSurfaceHandle() => _ptr = Api.nvttCreateSurface(); /// Wraps an existing raw pointer (takes ownership; will destroy on dispose). @@ -150,8 +147,8 @@ public sealed unsafe class NvttSurfaceHandle : IDisposable get { ThrowIfDisposed(); - float* p = Api.nvttSurfaceData(_ptr); - int count = Width * Height * Depth * 4; + var p = Api.nvttSurfaceData(_ptr); + var count = Width * Height * Depth * 4; return p == null ? Span.Empty : new Span(p, count); } } @@ -163,8 +160,8 @@ public sealed unsafe class NvttSurfaceHandle : IDisposable public Span Channel(int index) { ThrowIfDisposed(); - float* p = Api.nvttSurfaceChannel(_ptr, index); - int count = Width * Height * Depth; + var p = Api.nvttSurfaceChannel(_ptr, index); + var count = Width * Height * Depth; return p == null ? Span.Empty : new Span(p, count); } @@ -205,7 +202,7 @@ public sealed unsafe class NvttSurfaceHandle : IDisposable fixed (byte* p = utf8) { Ghost.Nvtt.Native.NvttBoolean nvAlpha; - bool ok = NvttInterop.ToBool( + var ok = NvttInterop.ToBool( Api.nvttSurfaceLoad(_ptr, (sbyte*)p, &nvAlpha, NvttInterop.ToNvtt(expectSigned), tc)); hasAlpha = NvttInterop.ToBool(nvAlpha); @@ -221,7 +218,7 @@ public sealed unsafe class NvttSurfaceHandle : IDisposable fixed (byte* p = data) { Ghost.Nvtt.Native.NvttBoolean nvAlpha; - bool ok = NvttInterop.ToBool( + var ok = NvttInterop.ToBool( Api.nvttSurfaceLoadFromMemory(_ptr, p, (ulong)data.Length, &nvAlpha, NvttInterop.ToNvtt(expectSigned), tc)); hasAlpha = NvttInterop.ToBool(nvAlpha); @@ -363,7 +360,7 @@ public sealed unsafe class NvttSurfaceHandle : IDisposable NvttTimingContext* tc = null) { ThrowIfDisposed(); - float* color = stackalloc float[4] { r, g, b, a }; + var color = stackalloc float[4] { r, g, b, a }; return NvttInterop.ToBool( Api.nvttSurfaceBuildNextMipmapSolidColor(_ptr, color, tc)); } diff --git a/src/ThridParty/Ghost.Nvtt/NvttTimingContext.cs b/src/ThridParty/Ghost.Nvtt/NvttTimingContext.cs index cc06f85..dcd0e4d 100644 --- a/src/ThridParty/Ghost.Nvtt/NvttTimingContext.cs +++ b/src/ThridParty/Ghost.Nvtt/NvttTimingContext.cs @@ -75,7 +75,7 @@ public sealed unsafe class NvttTimingContextHandle : IDisposable fixed (byte* p = buf) { Api.nvttTimingContextGetRecordSafe(_ptr, index, (sbyte*)p, (nuint)buf.Length, &seconds); - string desc = NvttInterop.FromUtf8((sbyte*)p) ?? string.Empty; + var desc = NvttInterop.FromUtf8((sbyte*)p) ?? string.Empty; return (desc, seconds); } }