diff --git a/StgSharp.Common/Collections/SwissTable.cs b/StgSharp.Common/Collections/SwissTable.cs index 69132917..18798384 100644 --- a/StgSharp.Common/Collections/SwissTable.cs +++ b/StgSharp.Common/Collections/SwissTable.cs @@ -1,91 +1,81 @@ -//----------------------------------------------------------------------- -// ----------------------------------------------------------------------- -// file="SwissTable" -// Project: StgSharp -// AuthorGroup: Nitload -// Copyright (c) Nitload. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// ----------------------------------------------------------------------- -// ----------------------------------------------------------------------- -using System; -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Runtime.Intrinsics.Arm; -using System.Runtime.Intrinsics.X86; - -namespace StgSharp.Collections +//----------------------------------------------------------------------- +// ----------------------------------------------------------------------- +// file="SwissTable" +// Project: StgSharp +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// ----------------------------------------------------------------------- +// ----------------------------------------------------------------------- +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics.Arm; +using System.Runtime.Intrinsics.X86; + +namespace StgSharp.Collections { - /// - /// + /// + /// /// - public unsafe partial class SwissTable - { - - private const int BucketCount = 1 << EntryMaskWidth; - private const int BucketSize = 256; - private const int EntryMaskWidth = 10; // 1024 entries total, 256 per bucket + public sealed unsafe partial class SwissTable + { + + private const int BucketCount = 1 << EntryMaskWidth; + private const int BucketSize = 256; + private const int EntryMaskWidth = 10; // 1024 entries total, 256 per bucket public const int MaxCapacity = 1024 * BucketSize; // 256 entries per bucket, 1024 buckets - private readonly Entry* _entries; - - private SwissTable( - Entry* buffer - ) - { - _entries = buffer; - for (int i = 0; i < BucketCount; i++) - { - // Set all control bytes to 0xFF (empty) - Unsafe.InitBlock(&_entries[i].Bucket.Control, 0xFF, BucketSize); - } - } - - public bool TryAddOrSet( - nint key, - nint value - ) - { - throw new NotImplementedException(); - } - - public bool TryAddOrSet( - nint key, - ref nint value, - out bool isNewKey - ) - { - uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); - short entry = (short)(hash & ((1 << 11) - 1)); - Bucket* bucket = &_entries[entry].Bucket; - return IBucketScanner.Current.TrySet(key, hash, bucket, value, out isNewKey); - } - - public bool TryGet( - nint key, - out nint value - ) - { - uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); - short entry = (short)(hash & ((1 << 11) - 1)); - Bucket* bucket = &_entries[entry].Bucket; + private readonly Entry* _entries; + + private SwissTable(Entry* buffer) + { + _entries = buffer; + for (int i = 0; i < BucketCount; i++) + { + // Set all control bytes to 0xFF (empty) + Unsafe.InitBlock(&_entries[i].Bucket.Control, 0xFF, BucketSize); + } + } + + public static SwissTable Create() + { + Entry* buffer = (Entry*)NativeMemory.AlignedAlloc((nuint)Marshal.SizeOf(), 16); + return new SwissTable(buffer); + } + + public bool TryAddOrSet(nint key, nint value, out bool isNewKey) + { + uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); + short entry = (short)(hash & ((1 << 11) - 1)); + Bucket* bucket = &_entries[entry].Bucket; + return IBucketScanner.Current.TrySet(key, hash, bucket, value, out isNewKey); + } + + public bool TryGet(nint key, out nint value) + { + uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); + short entry = (short)(hash & ((1 << 11) - 1)); + Bucket* bucket = &_entries[entry].Bucket; return IBucketScanner.Current.TryFind(key, hash, bucket, out value); /* * hash = CRC32 of key @@ -93,103 +83,89 @@ namespace StgSharp.Collections * ctrl = 8-15 of hash * index = rest of hash * find value of hash - */ - } - - public bool TryRemove( - nint key, - out nint value - ) - { - uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); - short entry = (short)(hash & ((1 << 11) - 1)); - Bucket* bucket = &_entries[entry].Bucket; - return IBucketScanner.Current.TryRemove(key, hash, bucket, out value); - } - - [InlineArray(BucketCount)] - private struct Entry - { - - public Bucket Bucket; - - } - - private unsafe struct Bucket - { - - public BucketControl Control; - public BucketKeyStorage Keys; - public BucketValueStorage Values; - - } - - private interface IBucketScanner - { - - static IBucketScanner Current { get; } = Create(); - - bool TryFind( - nint key, - uint Hash, - Bucket* bucket, - out nint value - ); - - unsafe bool TryRemove( - nint key, - uint hash, - Bucket* bucket, - out nint value - ); - - bool TrySet( - nint key, - uint hash, - Bucket* bucket, - nint value, - out bool isNewKey - ); - - private static IBucketScanner Create() - { - if (X86Base.IsSupported) - { - return new BucketScannerX86(); - } else if (ArmBase.IsSupported) - { - throw new NotSupportedException("ARM architecture is currently not supported for bucket scanning. Please use an x86 platform."); - } else - { - throw new NotSupportedException("No suitable bucket scanner implementation found for the current platform."); - } - } - - } - - [InlineArray(BucketSize)] - private struct BucketControl - { - - public byte Control; - - } - - [InlineArray(BucketSize)] - private struct BucketKeyStorage - { - - public nint value; - - } - - [InlineArray(BucketSize)] - private struct BucketValueStorage - { - - public nint value; - - } - - } + */ + } + + public bool TryRemove(nint key, out nint value) + { + uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); + short entry = (short)(hash & ((1 << 11) - 1)); + Bucket* bucket = &_entries[entry].Bucket; + return IBucketScanner.Current.TryRemove(key, hash, bucket, out value); + } + + ~SwissTable() + { + NativeMemory.AlignedFree(_entries); + } + + [InlineArray(BucketCount)] + private struct Entry + { + + public Bucket Bucket; + + } + + private unsafe struct Bucket + { + + public BucketControl Control; + public BucketKeyStorage Keys; + public BucketValueStorage Values; + + } + + private interface IBucketScanner + { + + static IBucketScanner Current { get; } = Create(); + + bool TryFind(nint key, uint Hash, Bucket* bucket, out nint value); + + unsafe bool TryRemove(nint key, uint hash, Bucket* bucket, out nint value); + + bool TrySet(nint key, uint hash, Bucket* bucket, nint value, out bool isNewKey); + + private static IBucketScanner Create() + { + if (X86Base.IsSupported) + { + return new BucketScannerX86(); + } else if (ArmBase.IsSupported) + { + throw new NotSupportedException("ARM architecture is currently not supported for bucket scanning. Please use an x86 platform."); + } else + { + throw new NotSupportedException("No suitable bucket scanner implementation found for the current platform."); + } + } + + } + + [InlineArray(BucketSize)] + private struct BucketControl + { + + public byte Control; + + } + + [InlineArray(BucketSize)] + private struct BucketKeyStorage + { + + public nint value; + + } + + [InlineArray(BucketSize)] + private struct BucketValueStorage + { + + public nint value; + + } + + } } \ No newline at end of file diff --git a/StgSharp.Common/Environment/GlobalSetting.cs b/StgSharp.Common/Environment/GlobalSetting.cs index b1efcee7..13b44656 100644 --- a/StgSharp.Common/Environment/GlobalSetting.cs +++ b/StgSharp.Common/Environment/GlobalSetting.cs @@ -1,27 +1,30 @@ -//----------------------------------------------------------------------- +//----------------------------------------------------------------------- // ----------------------------------------------------------------------- -// file="GlobalSetting" +// file="GlobalSetting.cs" // Project: StgSharp -// AuthorGroup: Nitload -// Copyright (c) Nitload. All rights reserved. +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the “Software”), to deal in the Software without restriction, +// including without limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of the Software, +// and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and +// this permission notice shall be included in all copies +// or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED “AS IS”, +// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH +// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- @@ -74,21 +77,6 @@ namespace StgSharp private static int _mainThreadID { get; set; } = -1; - /// - /// CustomizeInit an instance of OpenGL program, This method should be called before any - /// other World api. - /// - public static void InitGL(int majorVersion, int minorVersion) - { - if (API == default) { - API = GraphicAPI.GL; - } - if (API != GraphicAPI.GL) { - return; - } - GraphicFramework.InternalInitGL(majorVersion, minorVersion); - } - public static class GlobalSetting { @@ -99,7 +87,7 @@ namespace StgSharp get => vsyncActivated; set { - GraphicFramework.glfwSwapInterval(value ? 1 : 0); + // GraphicFramework.glfwSwapInterval(value ? 1 : 0); vsyncActivated = value; } } diff --git a/StgSharp.Common/Environment/IStaticModule.cs b/StgSharp.Common/Environment/IStaticModule.cs index 9700e6fc..71a975aa 100644 --- a/StgSharp.Common/Environment/IStaticModule.cs +++ b/StgSharp.Common/Environment/IStaticModule.cs @@ -2,8 +2,8 @@ // ----------------------------------------------------------------------- // file="IStaticModule" // Project: StgSharp -// AuthorGroup: Nitload -// Copyright (c) Nitload. All rights reserved. +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -31,56 +31,254 @@ using System.Collections.Generic; namespace StgSharp { + /// + /// Represents a statically activated module that can be registered and initialized as part of + /// the application startup sequence, and gracefully torn down on shutdown. + /// public interface IStaticModule { + /// + /// Gets the display name of this module, used for logging and diagnostics. + /// string ModuleName { get; } - void InitializeModule(); + /// + /// Performs all initialization work for this module using the provided profile. + /// + /// + /// The configuration profile supplied at registration time. Use if no configuration is required. + /// + void InitializeModule(IModuleInitializeProfile profile); + + /// + /// Releases all resources acquired during . Implementations should + /// be idempotent: calling this method more than once must not throw. + /// + void UninitializeModule(); } + /// + /// Marker interface for module initialization configuration. Implementations are plain data + /// carriers; no static factory is required. + /// + public interface IModuleInitializeProfile + { + + /// + /// A shared, allocation-free empty profile for modules that require no configuration. + /// + static readonly IModuleInitializeProfile Empty = EmptyModuleInitializeProfile.Instance; + + private sealed class EmptyModuleInitializeProfile : IModuleInitializeProfile + { + + public static readonly EmptyModuleInitializeProfile Instance = new(); + + private EmptyModuleInitializeProfile() { } + + } + + } + + /// + /// Pairs an with its , + /// ensuring the two are never stored or iterated independently. + /// + /// + /// Using a avoids the boxing overhead that would occur if + /// the pair were stored as two parallel lists of reference types. + /// + public readonly struct ModuleDescriptor + { + + /// + /// Initializes a new using as the profile. + /// + public ModuleDescriptor(IStaticModule module) : this(module, IModuleInitializeProfile.Empty) { } + + /// + /// Initializes a new with an explicit profile. + /// + public ModuleDescriptor(IStaticModule module, IModuleInitializeProfile profile) + { + Module = module; + Profile = profile; + } + + /// + /// Gets the configuration profile associated with the module. + /// + public IModuleInitializeProfile Profile { get; } + + /// + /// Gets the module to be initialized. + /// + public IStaticModule Module { get; } + + /// + /// Calls with the stored profile. + /// + public void Initialize() + { + Module.InitializeModule(Profile); + } + + /// + /// Calls on the stored module. + /// + public void Uninitialize() + { + Module.UninitializeModule(); + } + + } + + /// + /// An ordered collection of modules to be initialized during application startup and + /// uninitialized on shutdown. Supports three registration strategies so that the new() + /// generic constraint is never a hard requirement. + /// public sealed class ModuleToInitializeCollection : IEnumerable, IStaticModule { - private readonly List _modules = []; + private readonly List _descriptors = []; - internal ModuleToInitializeCollection( - World.Initializer i - ) + internal ModuleToInitializeCollection(World.Initializer i) { - _modules.Add(i); + _descriptors.Add(new ModuleDescriptor(i)); } + // ── IEnumerable ─────────────────────────────────────────── + + /// public IEnumerator GetEnumerator() { - return ((IEnumerable)_modules).GetEnumerator(); - } - - public void InitializeModule() - { - foreach (IStaticModule module in _modules) { - module.InitializeModule(); + foreach (ModuleDescriptor d in _descriptors) { + yield return d.Module; } } - public ModuleToInitializeCollection UseModule() where T : IStaticModule, new() + // ── Initialization / Uninitialization ──────────────────────────────────── + + /// + /// Initializes all registered modules in the order they were registered. Each module + /// receives the profile that was supplied at registration time. + /// + public void InitializeModule() { - _modules.Add(new T()); + for (int i = 0; i < _descriptors.Count; i++) { + _descriptors[i].Initialize(); + } + } + + /// + /// Uninitializes all registered modules in reverse registration order, mirroring + /// the typical LIFO teardown convention (e.g., GLFW must be unloaded after all subsystems + /// that depend on it). + /// + public void UninitializeModule() + { + for (int i = _descriptors.Count - 1; i >= 0; i--) { + _descriptors[i].Uninitialize(); + } + } + + // ── Registration API ───────────────────────────────────────────────────── + + /// + /// Registers a module of type using its default constructor. + /// This is the most concise overload for simple modules that expose a public + /// parameterless constructor. + /// + /// + /// A concrete module type that implements and exposes a + /// public parameterless constructor. + /// + /// + /// Optional initialization profile. Defaults to when . + /// + public ModuleToInitializeCollection UseModule(IModuleInitializeProfile? profile = null) + where T: IStaticModule, new() + { + return UseModule(static() => new T(), profile); + } + + /// + /// Registers a module produced by a factory delegate. This overload imposes no generic + /// constraints and supports any construction strategy, including dependency injection and + /// parameterized constructors. + /// + /// + /// A delegate that constructs and returns the module instance. The delegate is invoked + /// once, immediately at registration time. If is or returns , the call is silently ignored + /// and the collection is returned unchanged. + /// + /// + /// Optional initialization profile. Defaults to when . + /// + public ModuleToInitializeCollection UseModule( + Func factory, + IModuleInitializeProfile? profile = null) + { + if (factory is null) { + return this; + } + IStaticModule? mod = factory(); + if (mod is null) { + return this; + } + _descriptors.Add(new ModuleDescriptor( + mod, + profile ?? IModuleInitializeProfile.Empty)); return this; } + /// + /// Registers a pre-existing module instance. Use this overload when the module is + /// provided externally, such as from a DI container, an object pool, or a singleton. + /// + /// + /// The module instance to register. + /// + /// + /// Optional initialization profile. Defaults to when . + /// + public ModuleToInitializeCollection UseModule(IStaticModule module, IModuleInitializeProfile? profile = null) + { + _descriptors.Add(new ModuleDescriptor( + module, + profile ?? IModuleInitializeProfile.Empty)); + return this; + } + + /// IEnumerator IEnumerable.GetEnumerator() { - return ((IEnumerable)_modules).GetEnumerator(); + return GetEnumerator(); } - void IStaticModule.InitializeModule() + // ── IStaticModule explicit implementation ──────────────────────────────── + + /// + /// Explicit implementation. Delegates to , ignoring the supplied profile because each contained module uses + /// its own registered profile. + /// + void IStaticModule.InitializeModule(IModuleInitializeProfile profile) { - throw new NotImplementedException(); + InitializeModule(); } + /// string IStaticModule.ModuleName => "Module Initializer"; } -} +} \ No newline at end of file diff --git a/StgSharp.Common/Environment/Platform.cs b/StgSharp.Common/Environment/Platform.cs index 2a8e1824..a50392d3 100644 --- a/StgSharp.Common/Environment/Platform.cs +++ b/StgSharp.Common/Environment/Platform.cs @@ -58,29 +58,6 @@ namespace StgSharp private static uint markCount = 0; internal static GraphicAPI API = default; - public static unsafe int DefaultSIMDAlignment - { - get - { - SIMDID id = NativeIntrinsic.IntrinsicMask; - switch (id.MaskByte[0] & 0b_00001111) - { - case 1: - return id.MaskByte[1] switch - { - 1 => 16, - 2 => 32, - 3 => 64, - 4 => 64, - 5 => 64, - _ => 8, - }; - default: - return 8; - } - } - } - public static ModuleToInitializeCollection Initialize() { return new ModuleToInitializeCollection(new Initializer()); @@ -122,7 +99,8 @@ namespace StgSharp public static void Terminate(int exitCode) { MainTimeProvider.StopProvidingTime(); - GraphicFramework.glfwTerminate(); + + // GraphicFramework.glfwTerminate(); Environment.Exit(exitCode); } @@ -204,10 +182,6 @@ namespace StgSharp { // Initialize time provider and start providing time MainTimeProvider.StartProvidingTime(); - GraphicFramework.LoadGlfw(); - if (GraphicFramework.glfwInit() == 0) { - throw new Exception("Failed to init system graphic environment."); - } DefaultLog.InternalAppendLog("\n\n\n"); DefaultLog.InternalWriteLog( $"Program {Assembly.GetEntryAssembly()!.FullName} on {Environment.MachineName} Started.", LogType.Info); diff --git a/StgSharp.Common/PipeLine/PipelineScheduler.cs b/StgSharp.Common/PipeLine/PipelineScheduler.cs index cd2aaa6a..c3fe201f 100644 --- a/StgSharp.Common/PipeLine/PipelineScheduler.cs +++ b/StgSharp.Common/PipeLine/PipelineScheduler.cs @@ -1,9 +1,9 @@ -//----------------------------------------------------------------------- +//----------------------------------------------------------------------- // ----------------------------------------------------------------------- // file="PipelineScheduler" // Project: StgSharp -// AuthorGroup: Nitload -// Copyright (c) Nitload. All rights reserved. +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -25,8 +25,6 @@ // // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- -using StgSharp.Stg; - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/StgSharp.Common/Environment/Monitors.cs b/StgSharp.Graphics/Environment/Monitor.cs similarity index 68% rename from StgSharp.Common/Environment/Monitors.cs rename to StgSharp.Graphics/Environment/Monitor.cs index 6e7013b3..a9557ecf 100644 --- a/StgSharp.Common/Environment/Monitors.cs +++ b/StgSharp.Graphics/Environment/Monitor.cs @@ -1,9 +1,9 @@ -//----------------------------------------------------------------------- +//----------------------------------------------------------------------- // ----------------------------------------------------------------------- -// file="Monitors" +// file="Monitor" // Project: StgSharp -// AuthorGroup: Nitload -// Copyright (c) Nitload. All rights reserved. +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -26,32 +26,34 @@ // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- using System; +using System.Collections.Generic; +using System.Linq; using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; -namespace StgSharp +namespace StgSharp.Graphics { - public static partial class World + public static class GraphicsEnvironment { - public static unsafe IntPtr[] MonitorsHandleArray + private static IntPtr[] _monitorsHandleArray; + + public static unsafe ReadOnlySpan MonitorsHandleArray { get { - if (MonitorsArray == null) + if (_monitorsHandleArray == null) { int count = 0; IntPtr* arrayHandle = GraphicFramework.glfwGetMonitors(&count); - MonitorsArray = new IntPtr[count]; - Marshal.Copy((IntPtr)arrayHandle, MonitorsArray, 0, count); + _monitorsHandleArray = new IntPtr[count]; + Marshal.Copy((IntPtr)arrayHandle, _monitorsHandleArray, 0, count); Marshal.FreeHGlobal((IntPtr)arrayHandle); } - return MonitorsArray; + return _monitorsHandleArray; } } - public static nint[] MonitorsArray { get; set; } = []; - - public static IntPtr DefaultMonitor => MonitorsHandleArray[0]; - } } diff --git a/StgSharp.Graphics/GraphicInitializer.cs b/StgSharp.Graphics/GraphicInitializer.cs new file mode 100644 index 00000000..ab056672 --- /dev/null +++ b/StgSharp.Graphics/GraphicInitializer.cs @@ -0,0 +1,58 @@ +//----------------------------------------------------------------------- +// ----------------------------------------------------------------------- +// file="GraphicInitializer" +// Project: StgSharp +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// ----------------------------------------------------------------------- +// ----------------------------------------------------------------------- + +using StgSharp; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using System.Threading.Tasks; + +namespace StgSharp.Graphics +{ + public class GraphicModuel : IStaticModule + { + + public string ModuleName => "Graphics"; + + public void InitializeModule(IModuleInitializeProfile profile) + { + GraphicFramework.LoadGlfw(); + if (GraphicFramework.glfwInit() == 0) { + throw new Exception("Failed to init system graphic environment."); + } + } + + public void UninitializeModule() + { + GraphicFramework.glfwTerminate(); + } + + } +} diff --git a/StgSharp.Mathematics/Internal/MatrixPanel.cs b/StgSharp.Mathematics/Internal/MatrixPanel.cs index 84ad9286..24ad172e 100644 --- a/StgSharp.Mathematics/Internal/MatrixPanel.cs +++ b/StgSharp.Mathematics/Internal/MatrixPanel.cs @@ -26,6 +26,7 @@ // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- using StgSharp.Internal; +using StgSharp.Mathematics.Internal; using System; using System.Numerics; using System.Runtime.CompilerServices; @@ -92,7 +93,7 @@ namespace StgSharp.Mathematics [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int KernelSideCount() where T: unmanaged, INumber { - SIMDID id = NativeIntrinsic.IntrinsicMask; + SIMDID id = MathematicsModule.IntrinsicMask; switch (id.MaskByte[0] & 0b_00001111) { case 1: @@ -147,7 +148,7 @@ namespace StgSharp.Mathematics [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int PanelSideLength() where T: unmanaged, INumber { - SIMDID id = NativeIntrinsic.IntrinsicMask; + SIMDID id = MathematicsModule.IntrinsicMask; switch (id.MaskByte[0] & 0b_00001111) { case 1: diff --git a/StgSharp.Mathematics/Internal/UnsafeCompute.cs b/StgSharp.Mathematics/Internal/UnsafeCompute.cs index 2264bec6..6fccfaa8 100644 --- a/StgSharp.Mathematics/Internal/UnsafeCompute.cs +++ b/StgSharp.Mathematics/Internal/UnsafeCompute.cs @@ -1,30 +1,27 @@ //----------------------------------------------------------------------- // ----------------------------------------------------------------------- -// file="UnsafeCompute.cs" +// file="UnsafeCompute" // Project: StgSharp // AuthorGroup: Nitload Space // Copyright (c) Nitload Space. All rights reserved. // -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the “Software”), to deal in the Software without restriction, -// including without limitation the rights to use, copy, modify, merge, -// publish, distribute, sublicense, and/or sell copies of the Software, -// and to permit persons to whom the Software is furnished to do so, -// subject to the following conditions: -// -// The above copyright notice and -// this permission notice shall be included in all copies -// or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED “AS IS”, -// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -// ARISING FROM, OUT OF OR IN CONNECTION WITH -// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. // // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- @@ -38,19 +35,19 @@ namespace StgSharp.Mathematics.Internal [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe int CityHashSimplify(char* span, int length) { - return NativeIntrinsic.Context.city_hash_simplify(span, length); + return MathematicsModule.GlobalContext.city_hash_simplify(span, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe int CityHashSimplify(char* span, int begin, int length) { - return NativeIntrinsic.Context.city_hash_simplify(span + begin, length); + return MathematicsModule.GlobalContext.city_hash_simplify(span + begin, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe int IndexOfCharPair(char* source, int pairValue, int length) { - return NativeIntrinsic.Context.index_pair(source, pairValue, length); + return MathematicsModule.GlobalContext.index_pair(source, pairValue, length); } } diff --git a/StgSharp.Mathematics/Internal/intrinsicContextProvider.cs b/StgSharp.Mathematics/Moduel.cs similarity index 55% rename from StgSharp.Mathematics/Internal/intrinsicContextProvider.cs rename to StgSharp.Mathematics/Moduel.cs index 67009abd..bf62a3ad 100644 --- a/StgSharp.Mathematics/Internal/intrinsicContextProvider.cs +++ b/StgSharp.Mathematics/Moduel.cs @@ -1,6 +1,6 @@ //----------------------------------------------------------------------- // ----------------------------------------------------------------------- -// file="intrinsicContextProvider" +// file="Moduel" // Project: StgSharp // AuthorGroup: Nitload Space // Copyright (c) Nitload Space. All rights reserved. @@ -25,55 +25,56 @@ // // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- -using StgSharp.Mathematics.Internal; - +using StgSharp.Mathematics.Internal; using System; -using System.Reflection; +using System.Collections.Generic; +using System.Linq; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; -namespace StgSharp.Mathematics.Internal +namespace StgSharp.Mathematics { - internal static unsafe partial class NativeIntrinsic + public class MathematicsModule : IStaticModule { - private static readonly IntrinsicContext _intrinsicContext = new(); + public static unsafe int DefaultSIMDAlignment + { + get + { + SIMDID id = GlobalIntrinsicMask; + switch (id.MaskByte[0] & 0b_00001111) + { + case 1: + return id.MaskByte[1] switch + { + 1 => 16, + 2 => 32, + 3 => 64, + 4 => 64, + 5 => 64, + _ => 8, + }; + default: + return 8; + } + } + } - public static SIMDID IntrinsicMask { get; set; } + public string ModuleName => "Mathematics"; - internal static IntrinsicContext Context + internal static IntrinsicContext GlobalContext { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => _intrinsicContext; - } - - /* - internal static void InitIntrinsicContext() - { - ulong statCode = 0; - - fixed (IntrinsicContext* cPtr = &_intrinsicContext) { - statCode = LoadIntrinsicFunction(cPtr); - } - SIMDID id = new() - { - Mask = statCode - }; - switch (id.MaskByte[1]) - { - case 0: - Dialogue.PostError(new PlatformNotSupportedException("No SIMD instructions supported on current hardware platform")); - Environment.Exit(-1); - break; - default: - break; - } - IntrinsicMask = id; - } - - [LibraryImport(Native.LibName, EntryPoint = "load_intrinsic_function")] - [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] - private static partial void LoadIntrinsicFunction(IntrinsicContext* context, ulong id); - /**/ + get; + } = new(); + + internal static SIMDID GlobalIntrinsicMask { get; set; } + + public void InitializeModule() + { + throw new NotImplementedException(); + } + } -} \ No newline at end of file +} diff --git a/StgSharp.Mathematics/Numeric/Graphics/Matrix44.cs b/StgSharp.Mathematics/Numeric/Graphics/Matrix44.cs index 0b8625c3..b79df51d 100644 --- a/StgSharp.Mathematics/Numeric/Graphics/Matrix44.cs +++ b/StgSharp.Mathematics/Numeric/Graphics/Matrix44.cs @@ -167,7 +167,7 @@ namespace StgSharp.Mathematics.Graphics { const int f32 = 0; fixed (MatrixKernel* source = &this.kernel, target = &transpose.kernel) { - NativeIntrinsic.Context.mat[f32].buffer_transpose(source, target); + MathematicsModule.GlobalContext.mat[f32].buffer_transpose(source, target); } } @@ -176,7 +176,7 @@ namespace StgSharp.Mathematics.Graphics { Matrix44 ret = new(); const int f32 = 0; - NativeIntrinsic.Context.mat[f32].buffer_sub(&left, &right, &ret, 1); + MathematicsModule.GlobalContext.mat[f32].buffer_sub(&left, &right, &ret, 1); return ret; } @@ -197,7 +197,7 @@ namespace StgSharp.Mathematics.Graphics { Matrix44 ret = new(); int f32 = (int)MatrixElementType.F32; - NativeIntrinsic.Context.mat[f32].kernel_fma(&left, &right, &ret); + MathematicsModule.GlobalContext.mat[f32].kernel_fma(&left, &right, &ret); return ret; } @@ -206,7 +206,7 @@ namespace StgSharp.Mathematics.Graphics { Matrix44 ret = new(); const int f32 = 0; - NativeIntrinsic.Context.mat[f32].buffer_add(&left, &right, &ret, 1); + MathematicsModule.GlobalContext.mat[f32].buffer_add(&left, &right, &ret, 1); return ret; } diff --git a/StgSharp.Mathematics/Numeric/MatrixCompute.Factorize.cs b/StgSharp.Mathematics/Numeric/MatrixCompute.Factorize.cs index 99cbabb0..f374e9cd 100644 --- a/StgSharp.Mathematics/Numeric/MatrixCompute.Factorize.cs +++ b/StgSharp.Mathematics/Numeric/MatrixCompute.Factorize.cs @@ -2,8 +2,8 @@ // ----------------------------------------------------------------------- // file="MatrixCompute.Factorize" // Project: StgSharp -// AuthorGroup: Nitload -// Copyright (c) Nitload. All rights reserved. +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -41,8 +41,7 @@ namespace StgSharp.Mathematics.Numeric Matrix matrix, Span pivot, Matrix lower, - Matrix upper - ) + Matrix upper) { if (matrix.ColumnLength != matrix.RowLength) { throw new InvalidOperationException("Matrix must be square."); @@ -54,14 +53,10 @@ namespace StgSharp.Mathematics.Numeric if (pivot.Length < n) { throw new ArgumentException("Pivot span length is insufficient.", nameof(pivot)); } - if (lower.RowLength != n || - lower.ColumnLength != n || - lower.Layout != MatrixLayout.UpperTriangle) { + if (lower.RowLength != n || lower.ColumnLength != n || lower.Layout != MatrixLayout.UpperTriangle) { throw new ArgumentException("Lower matrix must be lower-triangular with same dimensions as input.", nameof(lower)); } - if (upper.RowLength != n || - upper.ColumnLength != n || - upper.Layout != MatrixLayout.UpperTriangle) { + if (upper.RowLength != n || upper.ColumnLength != n || upper.Layout != MatrixLayout.UpperTriangle) { throw new ArgumentException("Upper matrix must be upper-triangular with same dimensions as input.", nameof(upper)); } @@ -77,9 +72,8 @@ namespace StgSharp.Mathematics.Numeric ulong* pivots = stackalloc ulong[4]; for (int kBlock = 0; kBlock < n; kBlock += 4) { - NativeIntrinsic.Context - .mat[(int)MatrixElementType.F32].pivot(matrix.Buffer, - (ulong)(kBlock >> 2), + MathematicsModule.GlobalContext + .mat[(int)MatrixElementType.F32].pivot(matrix.Buffer, (ulong)(kBlock >> 2), (ulong)(matrix.KernelRowLength - (kBlock >> 2)), (ulong)pivots); int colsInBlock = Math.Min(4, n - kBlock); diff --git a/StgSharp.Mathematics/Numeric/MatrixCompute.Float.cs b/StgSharp.Mathematics/Numeric/MatrixCompute.Float.cs index 95bc69dd..aa7ad0bf 100644 --- a/StgSharp.Mathematics/Numeric/MatrixCompute.Float.cs +++ b/StgSharp.Mathematics/Numeric/MatrixCompute.Float.cs @@ -57,7 +57,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* rightPtr = right.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f32].buffer_add(leftPtr, rightPtr, ansPtr, count); + MathematicsModule.GlobalContext.mat[f32].buffer_add(leftPtr, rightPtr, ansPtr, count); return; } else if (count <= 1024) @@ -67,7 +67,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* rightPtr = right.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f32].buffer_add(leftPtr, rightPtr, ansPtr, count); + MathematicsModule.GlobalContext.mat[f32].buffer_add(leftPtr, rightPtr, ansPtr, count); MatrixParallel.ReturnParallelResources(ref pool); return; @@ -80,7 +80,7 @@ namespace StgSharp.Mathematics.Numeric package->PrimCount = ans.KernelColumnLength; package->SecCount = ans.KernelRowLength; package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM); - package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f32].buffer_add; + package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f32].buffer_add; MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); taskGroup.LaunchParallel(SleepMode.DeepSleep); @@ -96,12 +96,12 @@ namespace StgSharp.Mathematics.Numeric scalar->Data(0) = value; if (count <= 256) { - NativeIntrinsic.Context.mat[f32].buffer_fill(ans.Buffer, scalar, count); + MathematicsModule.GlobalContext.mat[f32].buffer_fill(ans.Buffer, scalar, count); return; } else if (count <= 1024) { MatrixParallelThread[] pool = MatrixParallel.LeadParallel(1); - NativeIntrinsic.Context.mat[f32].buffer_fill(ans.Buffer, scalar, count); + MathematicsModule.GlobalContext.mat[f32].buffer_fill(ans.Buffer, scalar, count); MatrixParallel.ReturnParallelResources(ref pool); return; } @@ -111,7 +111,7 @@ namespace StgSharp.Mathematics.Numeric package->PrimCount = ans.KernelColumnLength; package->SecCount = ans.KernelRowLength; package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.ANS_SCALAR_PARAM); - package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f32].buffer_fill; + package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f32].buffer_fill; package->Scalar = scalar; MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); taskGroup.LaunchParallel(SleepMode.DeepSleep); @@ -154,7 +154,7 @@ namespace StgSharp.Mathematics.Numeric enumeration->Member(0) = i; enumeration->Member(1) = j; - NativeIntrinsic.Context + MathematicsModule.GlobalContext .mat[f32].kernel_tile_fma((MatrixKernel*)left.Buffer, (MatrixKernel*)right.Buffer, (MatrixKernel*)ans.Buffer, enumeration); @@ -200,7 +200,7 @@ namespace StgSharp.Mathematics.Numeric { MatrixKernel* leftPtr = left.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f32].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); + MathematicsModule.GlobalContext.mat[f32].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); return; } else if (count <= 1024) @@ -209,7 +209,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f32].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); + MathematicsModule.GlobalContext.mat[f32].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); MatrixParallel.ReturnParallelResources(ref pool); return; @@ -222,7 +222,7 @@ namespace StgSharp.Mathematics.Numeric package->SecCount = left.KernelRowLength; package->Scalar = scalar; package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.RIGHT_ANS_SCALAR_PARAM); - package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f32].buffer_scalar_mul; + package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f32].buffer_scalar_mul; MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); taskGroup.LaunchParallel(SleepMode.DeepSleep); @@ -251,7 +251,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* rightPtr = right.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f32].buffer_sub(leftPtr, rightPtr, ansPtr, count); + MathematicsModule.GlobalContext.mat[f32].buffer_sub(leftPtr, rightPtr, ansPtr, count); return; } else if (count <= 1024) @@ -261,7 +261,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* rightPtr = right.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f32].buffer_sub(leftPtr, rightPtr, ansPtr, count); + MathematicsModule.GlobalContext.mat[f32].buffer_sub(leftPtr, rightPtr, ansPtr, count); MatrixParallel.ReturnParallelResources(ref pool); return; @@ -274,7 +274,7 @@ namespace StgSharp.Mathematics.Numeric package->PrimCount = left.KernelColumnLength; package->SecCount = left.KernelRowLength; package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM); - package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f32].buffer_sub; + package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f32].buffer_sub; MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); taskGroup.LaunchParallel(SleepMode.DeepSleep); diff --git a/StgSharp.Mathematics/Numeric/MatrixCompute.double.cs b/StgSharp.Mathematics/Numeric/MatrixCompute.double.cs index 3b2e6a56..ed3df8c1 100644 --- a/StgSharp.Mathematics/Numeric/MatrixCompute.double.cs +++ b/StgSharp.Mathematics/Numeric/MatrixCompute.double.cs @@ -53,7 +53,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* rightPtr = right.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f64].buffer_add(leftPtr, rightPtr, ansPtr, count); + MathematicsModule.GlobalContext.mat[f64].buffer_add(leftPtr, rightPtr, ansPtr, count); return; } else if (count <= 1024) @@ -63,7 +63,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* rightPtr = right.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f64].buffer_add(leftPtr, rightPtr, ansPtr, count); + MathematicsModule.GlobalContext.mat[f64].buffer_add(leftPtr, rightPtr, ansPtr, count); MatrixParallel.ReturnParallelResources(ref pool); return; @@ -76,7 +76,7 @@ namespace StgSharp.Mathematics.Numeric package->PrimCount = ans.KernelColumnLength; package->SecCount = ans.KernelRowLength; package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM); - package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f64].buffer_add; + package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f64].buffer_add; MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); taskGroup.LaunchParallel(SleepMode.DeepSleep); @@ -92,12 +92,12 @@ namespace StgSharp.Mathematics.Numeric scalar->Data(0) = value; if (count <= 256) { - NativeIntrinsic.Context.mat[f64].buffer_fill(ans.Buffer, scalar, count); + MathematicsModule.GlobalContext.mat[f64].buffer_fill(ans.Buffer, scalar, count); return; } else if (count <= 1024) { MatrixParallelThread[] pool = MatrixParallel.LeadParallel(1); - NativeIntrinsic.Context.mat[f64].buffer_fill(ans.Buffer, scalar, count); + MathematicsModule.GlobalContext.mat[f64].buffer_fill(ans.Buffer, scalar, count); MatrixParallel.ReturnParallelResources(ref pool); return; } @@ -107,7 +107,7 @@ namespace StgSharp.Mathematics.Numeric package->PrimCount = ans.KernelColumnLength; package->SecCount = ans.KernelRowLength; package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.ANS_SCALAR_PARAM); - package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f64].buffer_fill; + package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f64].buffer_fill; package->Scalar = scalar; MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); taskGroup.LaunchParallel(SleepMode.DeepSleep); @@ -144,7 +144,7 @@ namespace StgSharp.Mathematics.Numeric enumeration->Member(0) = i; enumeration->Member(1) = j; - NativeIntrinsic.Context + MathematicsModule.GlobalContext .mat[f64].kernel_tile_fma((MatrixKernel*)left.Buffer, (MatrixKernel*)right.Buffer, (MatrixKernel*)ans.Buffer, enumeration); @@ -189,7 +189,7 @@ namespace StgSharp.Mathematics.Numeric { MatrixKernel* leftPtr = left.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f64].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); + MathematicsModule.GlobalContext.mat[f64].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); return; } else if (count <= 1024) @@ -198,7 +198,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f64].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); + MathematicsModule.GlobalContext.mat[f64].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); MatrixParallel.ReturnParallelResources(ref pool); return; @@ -211,7 +211,7 @@ namespace StgSharp.Mathematics.Numeric package->SecCount = left.KernelRowLength; package->Scalar = scalar; package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.RIGHT_ANS_SCALAR_PARAM); - package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f64].buffer_scalar_mul; + package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f64].buffer_scalar_mul; MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); taskGroup.LaunchParallel(SleepMode.DeepSleep); @@ -240,7 +240,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* rightPtr = right.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f64].buffer_sub(leftPtr, rightPtr, ansPtr, count); + MathematicsModule.GlobalContext.mat[f64].buffer_sub(leftPtr, rightPtr, ansPtr, count); return; } else if (count <= 1024) @@ -250,7 +250,7 @@ namespace StgSharp.Mathematics.Numeric MatrixKernel* leftPtr = left.Buffer; MatrixKernel* rightPtr = right.Buffer; MatrixKernel* ansPtr = ans.Buffer; - NativeIntrinsic.Context.mat[f64].buffer_sub(leftPtr, rightPtr, ansPtr, count); + MathematicsModule.GlobalContext.mat[f64].buffer_sub(leftPtr, rightPtr, ansPtr, count); MatrixParallel.ReturnParallelResources(ref pool); return; @@ -263,7 +263,7 @@ namespace StgSharp.Mathematics.Numeric package->PrimCount = left.KernelColumnLength; package->SecCount = left.KernelRowLength; package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM); - package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f64].buffer_sub; + package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f64].buffer_sub; MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); taskGroup.LaunchParallel(SleepMode.DeepSleep); diff --git a/StgSharp.Mathematics/Numeric/Runtime/MatrixParallelThread.Fma.cs b/StgSharp.Mathematics/Numeric/Runtime/MatrixParallelThread.Fma.cs index 45c8b842..8d3a24ed 100644 --- a/StgSharp.Mathematics/Numeric/Runtime/MatrixParallelThread.Fma.cs +++ b/StgSharp.Mathematics/Numeric/Runtime/MatrixParallelThread.Fma.cs @@ -62,7 +62,8 @@ namespace StgSharp.Mathematics.Numeric int j = (int)(c % ansHeight); enumeration->Member(0) = i; enumeration->Member(1) = j; - NativeIntrinsic.Context.mat[f32].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer, enumeration); + MathematicsModule.GlobalContext.mat[f32].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer, + enumeration); } } @@ -91,7 +92,8 @@ namespace StgSharp.Mathematics.Numeric int j = (int)(c % ansHeight); enumeration->Member(0) = i; enumeration->Member(1) = j; - NativeIntrinsic.Context.mat[f64].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer, enumeration); + MathematicsModule.GlobalContext.mat[f64].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer, + enumeration); } } diff --git a/StgSharp.Mathematics/Numeric/Scalar/Factorial.cs b/StgSharp.Mathematics/Numeric/Scalar/Factorial.cs index 83b66fef..7920c761 100644 --- a/StgSharp.Mathematics/Numeric/Scalar/Factorial.cs +++ b/StgSharp.Mathematics/Numeric/Scalar/Factorial.cs @@ -1,68 +1,67 @@ -//----------------------------------------------------------------------- -// ----------------------------------------------------------------------- -// file="Factorial" -// Project: StgSharp -// AuthorGroup: Nitload -// Copyright (c) Nitload. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// ----------------------------------------------------------------------- -// ----------------------------------------------------------------------- -using System; - -namespace StgSharp.Mathematics -{ - public static partial class Scalar - { - - private static readonly uint[] factorialResult = [ - 1, - 1, - 2, - 6, - 24, - 120, - 720, - 5040, - 40320, - 362880, - 3628800, - 39916800, - 479001600 - ]; - - public static unsafe ulong Factorial(int n) - { - ArgumentOutOfRangeException.ThrowIfLessThan(n, 0); - if (n < 13) { - return factorialResult[n]; - } - if (n < 30) { - return NativeIntrinsic.Context.factorial_simd(n); - } +//----------------------------------------------------------------------- +// ----------------------------------------------------------------------- +// file="Factorial" +// Project: StgSharp +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// ----------------------------------------------------------------------- +// ----------------------------------------------------------------------- +using System; + +namespace StgSharp.Mathematics +{ + public static partial class Scalar + { + + private static readonly uint[] factorialResult = [ + 1, + 1, + 2, + 6, + 24, + 120, + 720, + 5040, + 40320, + 362880, + 3628800, + 39916800, + 479001600]; + + public static unsafe ulong Factorial(int n) + { + ArgumentOutOfRangeException.ThrowIfLessThan(n, 0); + if (n < 13) { + return factorialResult[n]; + } + if (n < 30) { + return MathematicsModule.GlobalContext.factorial_simd(n); + } double dn = n, stir = Sqrt(2 * PiDouble * dn) * Pow(dn / EDouble, dn), - correction = Exp(1 / (12 * dn)); - return (ulong)(stir * correction); - } - - } + correction = Exp(1 / (12 * dn)); + return (ulong)(stir * correction); + } + + } } diff --git a/StgSharp.Native/sn-src/check.ps1 b/StgSharp.Native/sn-src/check.ps1 deleted file mode 100644 index 611fa5de..00000000 --- a/StgSharp.Native/sn-src/check.ps1 +++ /dev/null @@ -1,25 +0,0 @@ -# 1. 版本 — 已确认 18.1.8 -clang-format --version - -# 2. 不可见字符扫描 — 用完整路径 -$file = Join-Path $PWD "simdid.x86.c" -$bytes = [System.IO.File]::ReadAllBytes($file) - -for ($i = 0; $i -lt $bytes.Length - 2; $i++) { - if ($bytes[$i] -eq 0xEF -and $bytes[$i+1] -eq 0xBB -and $bytes[$i+2] -eq 0xBF) { - Write-Host "BOM found at offset $i" - } - if ($bytes[$i] -eq 0xC2 -and $bytes[$i+1] -eq 0xA0) { - Write-Host "NBSP at offset $i" - } - if ($bytes[$i] -eq 0xE2 -and $bytes[$i+1] -eq 0x80 -and - ($bytes[$i+2] -eq 0x8B -or $bytes[$i+2] -eq 0x8C -or $bytes[$i+2] -eq 0x8D)) { - Write-Host "Zero-width char at offset $i" - } -} - -Write-Host "Scan complete. File size: $($bytes.Length) bytes" - -# 3. 格式化对比 — 用 fc.exe 避免 PowerShell 的 Format-Custom 歧义 -clang-format -assume-filename=test.c $file > formatted.c -fc.exe $file formatted.c \ No newline at end of file diff --git a/StgSharpDebug/Program.cs b/StgSharpDebug/Program.cs index 96682124..e7dd8528 100644 --- a/StgSharpDebug/Program.cs +++ b/StgSharpDebug/Program.cs @@ -26,6 +26,7 @@ // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- using StgSharp.Common.Timing; +using StgSharp.Graphics; using StgSharp.Internal; using StgSharp.Mathematics; using StgSharp.Mathematics.Memory; @@ -48,8 +49,9 @@ namespace StgSharp // TestRegexAnalyse.Run(); // HlsfStressTest.Run(); + TestSwiss(); - TestMatrix(); + // TestMatrix(); /* diff --git a/StgSharpDebug/StgSharpDebug.csproj b/StgSharpDebug/StgSharpDebug.csproj index 563220e7..d6f145c9 100644 --- a/StgSharpDebug/StgSharpDebug.csproj +++ b/StgSharpDebug/StgSharpDebug.csproj @@ -11,6 +11,7 @@ + diff --git a/StgSharpDebug/TestRender.cs b/StgSharpDebug/TestRender.cs index 30be26e2..3f8ad4ee 100644 --- a/StgSharpDebug/TestRender.cs +++ b/StgSharpDebug/TestRender.cs @@ -1,37 +1,35 @@ -//----------------------------------------------------------------------- //----------------------------------------------------------------------- -// file="TestRender.cs" -// Project: StgSharp -// AuthorGroup: Nitload Space -// Copyright (c) Nitload Space. All rights reserved. +// ----------------------------------------------------------------------- +// file="TestRender.cs" +// Project: StgSharp +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. // -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the “Software”), to deal in the Software without restriction, -// including without limitation the rights to use, copy, modify, merge, -// publish, distribute, sublicense, and/or sell copies of the Software, -// and to permit persons to whom the Software is furnished to do so, -// subject to the following conditions: +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the “Software”), to deal in the Software without restriction, +// including without limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of the Software, +// and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: // -// The above copyright notice and -// this permission notice shall be included in all copies -// or substantial portions of the Software. +// The above copyright notice and +// this permission notice shall be included in all copies +// or substantial portions of the Software. // -// THE SOFTWARE IS PROVIDED “AS IS”, -// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -// ARISING FROM, OUT OF OR IN CONNECTION WITH -// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// THE SOFTWARE IS PROVIDED “AS IS”, +// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH +// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -//----------------------------------------------------------------------- -//----------------------------------------------------------------------- +// ----------------------------------------------------------------------- +// ----------------------------------------------------------------------- using StgSharp.Collections; -using StgSharp.MVVM; -using StgSharp.MVVM.ViewModel; - +using StgSharp.Graphics; using System; using System.Collections.Generic; using System.Linq; @@ -45,19 +43,19 @@ namespace StgSharp public static void TestRender() { - World.InitGL( 4, 6 ); + // World.InitGL(4, 6); World.GlobalSetting.VSyncActivated = false; - ViewPort vp = new ViewPort( 800, 600, "Hello StgSharp!", IntPtr.Zero ); + ViewPort vp = new ViewPort(800, 600, "Hello StgSharp!", IntPtr.Zero); - //throw new NotImplementedException(); + // throw new NotImplementedException(); + /* + ViewModelBase mainModel = new ViewModelMain(vp); + mainModel.CreateAndBindView("MainView", (1, 1, 1)); - ViewModelBase mainModel = new ViewModelMain( vp ); - mainModel.CreateAndBindView( "MainView", (1, 1, 1) ); - - mainModel.UseViewModel( "MainView" ); - - World.Terminate( 0 ); + mainModel.UseViewModel("MainView"); + /**/ + World.Terminate(0); } } diff --git a/StgSharpDebug/TestSwiss.cs b/StgSharpDebug/TestSwiss.cs new file mode 100644 index 00000000..a69c095a --- /dev/null +++ b/StgSharpDebug/TestSwiss.cs @@ -0,0 +1,64 @@ +//----------------------------------------------------------------------- +// ----------------------------------------------------------------------- +// file="TestSwiss" +// Project: StgSharp +// AuthorGroup: Nitload Space +// Copyright (c) Nitload Space. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// ----------------------------------------------------------------------- +// ----------------------------------------------------------------------- +using StgSharp.Collections; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; + +namespace StgSharp +{ + internal static partial class Program + { + + public static void TestSwiss() + { + SwissTable swiss = SwissTable.Create(); + for (int i = 0; i < 10000; i++) + { + _ = swiss.TryAddOrSet(i, i * 2, out _); + Console.WriteLine($"Set a kvp of ({i},{i * 2})"); + } + Random rand = new Random(); + for (int i = 0; i < 10000; i++) + { + int key = rand.Next(0, 10000); + if (swiss.TryGet(key, out nint value)) + { + Console.WriteLine($"Get a kvp of ({key},{value})"); + } else + { + Console.WriteLine($"Failed to get a kvp of ({key},?)"); + } + } + } + + } +}