Silk.NET Documentation

repository·main·Indexed 26 days ago

https://github.com/dotnet/silk.net

A high-performance .NET library providing low-level bindings for graphics (OpenGL, Vulkan, WebGPU, DirectX), compute (OpenCL), audio (OpenAL), XR (OpenXR), and windowing/input (GLFW, SDL) APIs. It supports .NET Standard 2.0 compliant platforms, including .NET 6.0+, .NET Core 2.0+, .NET Framework 4.6.1+, and Xamarin. The library includes specialized tools for Vulkan-style structure chaining via ManagedChain and provides native binary distributions for various multimedia libraries.

Tokens
65.5K
Snippets
149
Records
324
Agent score
89%

What's inside Silk.NET

  1. Overview of Silk.NET 3.0 Goals and Roadmap

    main

    Silk.NET 3.0 is a major update focused on portability, maintainability, usability, and performance. Key objectives include:

    • Framework Integration: Allowing Silk.NET abstractions to integrate with frameworks like WPF, WinForms, MAUI, and Avalonia.
    • Portable Windowing: A rewritten windowing system for true write-once-run-everywhere capability.
    • Improved Bindings: Moving away from custom binding generation towards more mature alternatives (SilkTouch).
    • SIMD-Accelerated Maths: Accelerating the maths library using SIMD hardware intrinsics.
    • Redesigned Input: A multi-backend input library designed to be less prone to breaking changes and compatible with multiple environments.

    Note on Previews:

    • 3.0 Preview 1-3: Highly experimental; not production-ready.
    • 3.0 Preview 4: Considered "production-ready"; users are encouraged to start integrating this into their workloads.
    • 3.0 Preview 5: Primarily a bugfix release focusing on final breaking changes and platform integrations (MAUI/Avalonia).
  2. Overview of Silk.NET

    main

    Silk.NET is a high-performance .NET library providing bindings to popular low-level multimedia, graphics, and compute APIs. It is designed for high-speed execution with negligible overhead and provides platform-agnostic abstractions for windowing and input.

    Supported APIs include:

    • Graphics: OpenGL, Vulkan, WebGPU, DirectX
    • Compute: OpenCL
    • Audio: OpenAL
    • XR: OpenXR
    • Windowing/Input: GLFW, SDL
    • Asset Loading: Assimp

    Compatibility: Works on any .NET Standard 2.0 compliant platform, including:

    • .NET 6.0+
    • .NET Core 2.0+
    • .NET Framework 4.6.1+
    • Xamarin
  3. Understand Vulkan Structure Chaining in Silk.NET

    main

    Silk.NET APIs (specifically in the Silk.NET.Vulkan package) often use singly linked lists of structures, referred to as 'chains', to pass data. These chains use a void* pointer (PNext) to link to the next item, with nullptr indicating the end.

    To handle the risks of pointer manipulation in a managed environment (like Garbage Collection moving objects), Silk.NET provides three methodologies for managing these chains:

    1. Managed Chaining (Recommended): Uses a Chain object to manage memory and ensure pointers remain valid. This is the safest and easiest approach.
    2. Structure Chaining: Uses fluent extension methods on IChainable structures. This is stack-based and avoids the heap, making it suitable for performance-sensitive code where structures do not leave the stack.
    3. Raw Chaining: Direct pointer manipulation. This is the lowest-level approach for maximum optimization in hot paths but requires unsafe code and manual pointer management.
  4. Understand Silk.NET 3.0 ABI Compatibility

    main

    Silk.NET 3.0 implements an ABI (Application Binary Interface) compatibility mechanism to allow existing libraries compiled against Silk.NET 2.X to continue functioning alongside Silk.NET 3.0.

    Key behaviors for developers:

    • Runtime Compatibility: Code compiled against 2.X will run against 3.0 assemblies because 3.0 implements 2.X APIs internally.
    • API Isolation: When you intentionally compile code against Silk.NET 3.0, you will only see the new 3.0 API. The legacy 2.X APIs are hidden from your IDE to prevent performance issues and encourage the use of modern APIs.
    • Type Resolution: Types that existed in 2.X are retained in the 3.0 reference assemblies to ensure IDEs can resolve type references, even if the members themselves are hidden.
    • Reflection: Note that reflection compatibility is not supported by this mechanism.
  5. Understand Vulkan Structure Chaining in Silk.NET

    main
    Silk.NET uses a type-safe chaining system for Vulkan structures to represent the singly linked lists used in the Vulkan API. Because C# structs cannot inherit from one another, Silk.NET uses a set of interfaces to guarantee that chainable structures have the required SType (StructureType) and PNext (pointer to the next item) fields in the correct memory layout. This allows the library to treat PNext as a BaseInStructure* rather than a void*, enabling safe traversal of the chain and access to each element's StructureType.
  6. Understand Managed Chaining in Silk.NET Vulkan

    main

    Managed chaining uses the Silk.NET.Vulkan.Chain abstract class and its descendants to handle Vulkan's structure chaining (e.g., pNext chains). These are auto-generated types like Chain<TChain, T1, T2, ...> that support chain lengths from 1 to 16.

    Key characteristics:

    • Type Constraints: Every item in a chain must implement IChainable and be unmanaged.
    • Strict vs. Loose Constraints:
      • Standard methods (like Create) use strict constraints: the head must implement IChainStart, and subsequent items must implement IExtendsChain<TChain> to ensure valid Vulkan structure sequences.
      • *Any overloads (like CreateAny) use loose constraints (IChainable), allowing you to build chains even when the specification doesn't strictly define the required sequence. Use *Any versions only when necessary.
    • Memory Management: Each Chain instance holds a pointer to an unmanaged block of memory. You must always dispose of a Chain instance (ideally using a using statement) to prevent memory leaks.
  7. Understand the View vs Window API division

    main

    Silk.NET is moving towards a split API architecture to support mobile platforms.

    • IView: Contains the core windowing APIs that are guaranteed to be available on every supported platform (including mobile). It includes essential lifecycle events, properties, and functions.
    • IWindow: Inherits from IView and contains the extended desktop-specific windowing APIs.

    When working with cross-platform code, targeting IView ensures maximum compatibility.

  8. Proposed Color type structs in Silk.Net.Maths 3.0

    main

    As part of the Silk.Net.Maths 3.0 proposal, new color type structs are being introduced to bring the library to feature parity with math libraries like SlimDX, SharpDX, or Stride3D. These types are designed to leverage modern .NET features, including INumber<T> and vectorization.

    When implemented, these types will follow a naming convention to distinguish between integer and floating-point variants:

    • I types: Integer variants, using a generic type argument T constrained to IBinaryInteger<T>.
    • F types: Floating-point variants, using a generic type argument T constrained to IFloatingPointIeee754<T>.
  9. Use SIMD vectorization APIs for high-performance math

    main

    Silk.NET is proposing a high-performance, generic SIMD (Single Instruction, Multiple Data) math API. This API provides access to Vector64<T>, Vector128<T>, and Vector256<T> types to enable vectorized operations.

    Key design characteristics for users:

    • Mirroring Scalar API: The SIMD API is designed to mirror the existing Scalar<T> API for familiarity.
    • Boolean Operations: For boolean-returning APIs, the system returns a Vector128<T> where all elements are set to either all 1s (representing true) or all 0s (representing false). This is optimized for branchless code execution.
    • Rounding: Supports rounding to a specific number of digits or using a specific rounding mode (backed by intrinsics where available).
    • Bitwise Operations: Future updates are expected to enhance these vector types with bitwise operations.
  10. Use Silk.NET API Objects and Static Methods

    main

    Silk.NET bindings provide two primary ways to interact with native libraries: through API Objects (instances) and Static Methods.

    • API Objects: Use these for multi-context or multi-backend solutions (e.g., Vulkan, OpenCL, OpenXR) where you need to manage specific native contexts. You can create an instance using Create(INativeContext ctx) or the default Create() method.
    • Static Methods: Use these for simplicity or when working with libraries that rely on a global/thread-local state (e.g., OpenGL).

    For stateful libraries like OpenGL, you can use MakeCurrent(IMyStringLibrary current) to set a specific API object as the thread-local instance. Subsequent static calls on that thread will then use that specific instance.

  11. Load a managed chain from an unmanaged chain

    main

    If you have an unmanaged chain (from raw chaining or other sources), you can load it into a managed Chain using Chain.Load<TChain...>().

    There are several overloads:

    • Chain.Load<TChain...>(unmanagedChain): Standard load.
    • Chain.Load<TChain...>(out string errors, unmanagedChain): Returns an errors string. If no errors occurred, errors is string.Empty. Each error is on a new line.
    • Chain.Load<TChain...>(unmanagedChain): A single-argument overload (often used in Debug builds).

    Note: The loading process always succeeds even if the unmanaged chain doesn't match the expected types or length exactly. Any structure type found in the expected position will be loaded into the new Chain.

    // Loads a new managed chain from an unmanaged chain
    using var managedChain = 
        Chain.Load<PhysicalDeviceFeatures2, PhysicalDeviceDescriptorIndexingFeatures, 
            PhysicalDeviceAccelerationStructureFeaturesKHR>(unmanagedChain);
  12. Configure the Surface update loop and timing

    main

    In Silk.NET 3.0, the Surface class manages the application's execution loop. You can control how frequently Tick, Render, and Update events are raised using SurfaceTickOptions, SurfaceTimingOptions, and frequency properties.

    Event Types

    • Tick: Raised as frequently as possible (or according to TickOptions).
    • Render: Raised for redrawing graphics, governed by RenderOptions.
    • Update: Raised for logic updates, governed by UpdateOptions.

    Controlling Frequency

    • Run as fast as possible: Set FramesPerSecond or UpdatesPerSecond to a negative number (which sets TargetDelta to a value close to zero).
    • Disable execution: Set FramesPerSecond or UpdatesPerSecond to 0 (which sets TargetDelta to double.MaxValue).
    • Event-Driven Ticking: Set TickOptions.IsEventDriven to true to ensure Tick only executes in response to an event or a call to Continue().