diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 3a8df01..42ef9e7 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -4,7 +4,7 @@ labels: [bug, needs-triage]
body:
- type: markdown
attributes:
- value: "Questions belong on the [forums](https://forums.ahwoo.dev/forums/brutal/). Security issues: see SECURITY.md."
+ value: "Questions belong on the [forums](https://forums.ahwoo.com/forums/brutal/). Security issues: see SECURITY.md."
- type: input
id: packages
attributes:
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index ebb876d..c650afe 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -1,10 +1,10 @@
blank_issues_enabled: false
contact_links:
- name: Questions and help
- url: https://forums.ahwoo.dev/forums/brutal/guides-and-help/
- about: "How do I…?" questions go here, not in issues.
+ url: https://forums.ahwoo.com/forums/brutal/guides-and-help/
+ about: '"How do I…?" questions go here, not in issues.'
- name: Discussion and ideas
- url: https://forums.ahwoo.dev/forums/brutal/general/
+ url: https://forums.ahwoo.com/forums/brutal/general/
about: General discussion about building on BRUTAL.
- name: Report a security vulnerability
url: https://github.com/ahwootech/BRUTAL/security/advisories/new
diff --git a/.github/workflows/first-interaction.yml b/.github/workflows/first-interaction.yml
index 83ff448..cc20a3c 100644
--- a/.github/workflows/first-interaction.yml
+++ b/.github/workflows/first-interaction.yml
@@ -21,7 +21,7 @@ jobs:
Thanks for opening your first BRUTAL issue! 👋
We're a small team, so please be patient with us. It may be a while before someone replies. To help us:
- - **Questions and "how do I…?"** belong on the [BRUTAL forums](https://forums.ahwoo.dev/forums/brutal/). We may close and redirect them.
+ - **Questions and "how do I…?"** belong on the [BRUTAL forums](https://forums.ahwoo.com/forums/brutal/). We may close and redirect them.
- **Bugs:** please make sure you've included package versions, OS/GPU, and a minimal repro.
- **Security issues:** please don't post them here. See [SECURITY.md](../blob/main/SECURITY.md).
pr-message: |
diff --git a/Brutal.Core/Attributes.cs b/Brutal.Core/Attributes.cs
index 672dcd6..2276f0a 100644
--- a/Brutal.Core/Attributes.cs
+++ b/Brutal.Core/Attributes.cs
@@ -1,6 +1,41 @@
namespace Brutal.Attributes;
+///
+/// Indicates that an entity only exposes memory that has a fixed address. Marking an entity [Fixed] allows the analyser
+/// to check that the entity is only used in contexts where the memory is guaranteed to be fixed, such as when it is
+/// returned from a method or passed as a parameter.
+/// The attribute can be applied to return values, parameters, fields, properties, interfaces, classes, and structs.
+///
[AttributeUsage(
- AttributeTargets.ReturnValue | AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property
+ AttributeTargets.ReturnValue
+ | AttributeTargets.Parameter
+ | AttributeTargets.Field
+ | AttributeTargets.Property
+ | AttributeTargets.Interface
+ | AttributeTargets.Class
+ | AttributeTargets.Struct
)]
public sealed class FixedAttribute : Attribute { }
+
+///
+/// Acts like the [Fixed] attribute but only if the referenced type is itself fixed. Pass the nameof a type
+/// parameter of the containing method or type to resolve its type argument, or the typeof a concrete type or
+/// interface.
+///
+[AttributeUsage(AttributeTargets.ReturnValue | AttributeTargets.Property | AttributeTargets.Parameter)]
+public sealed class FixedWhenAttribute : Attribute
+{
+ public FixedWhenAttribute(string typeName)
+ {
+ TypeName = typeName;
+ }
+
+ public FixedWhenAttribute(Type type)
+ {
+ Type = type;
+ }
+
+ public string? TypeName { get; }
+
+ public Type? Type { get; }
+}
diff --git a/Brutal.FreeType/LICENSES/BRUTAL-FREETYPE-THIRD-PARTY-NOTICES.txt b/Brutal.FreeType/LICENSES/BRUTAL-FREETYPE-THIRD-PARTY-NOTICES.txt
index dd5a06f..0545a49 100644
--- a/Brutal.FreeType/LICENSES/BRUTAL-FREETYPE-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.FreeType/LICENSES/BRUTAL-FREETYPE-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.FreeType
+Ahwoo.BRUTAL.FreeType
This package redistributes the third-party components listed below, each reproduced
with the license that governs it.
@@ -17,7 +17,7 @@ with the license that governs it.
License for the library, and a separate X11-style license for each of the contributed
BDF and PCF drivers, which are compiled into the shipped binaries.
- zlib is not contained in this package. It is supplied by RocketWerkz.Brutal.ZLib,
+ zlib is not contained in this package. It is supplied by Ahwoo.BRUTAL.ZLib,
on which this package depends, and is covered by that package's own notices.
FreeType's own LICENSE.TXT distributes it "under two mutually exclusive open-source
diff --git a/Brutal.Glfw/LICENSES/BRUTAL-GLFW-THIRD-PARTY-NOTICES.txt b/Brutal.Glfw/LICENSES/BRUTAL-GLFW-THIRD-PARTY-NOTICES.txt
index f7bab84..83be9da 100644
--- a/Brutal.Glfw/LICENSES/BRUTAL-GLFW-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Glfw/LICENSES/BRUTAL-GLFW-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Glfw
+Ahwoo.BRUTAL.Glfw
Brutal.Glfw redistributes the third-party components named below, as native libraries.
Each is reproduced with the license that governs it.
diff --git a/Brutal.Gli/LICENSES/BRUTAL-GLI-THIRD-PARTY-NOTICES.txt b/Brutal.Gli/LICENSES/BRUTAL-GLI-THIRD-PARTY-NOTICES.txt
index ae690f0..ea0e5b9 100644
--- a/Brutal.Gli/LICENSES/BRUTAL-GLI-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Gli/LICENSES/BRUTAL-GLI-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Gli
+Ahwoo.BRUTAL.Gli
Brutal.Gli redistributes the third-party components named below, as native libraries.
Each is reproduced with the license that governs it.
diff --git a/Brutal.Gltf/GltfApi/GeneratedSchema/Accessor.gen.cs b/Brutal.Gltf/GltfApi/GeneratedSchema/Accessor.gen.cs
index 8ffaa4b..edaed97 100644
--- a/Brutal.Gltf/GltfApi/GeneratedSchema/Accessor.gen.cs
+++ b/Brutal.Gltf/GltfApi/GeneratedSchema/Accessor.gen.cs
@@ -158,7 +158,7 @@ namespace Brutal.GltfApi {
///
/// Specifies if the accessor's elements are scalars, vectors, or matrices.
///
- [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
+ [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[System.Text.Json.Serialization.JsonRequiredAttribute()]
[System.Text.Json.Serialization.JsonPropertyNameAttribute("type")]
public TypeEnum Type {
diff --git a/Brutal.Gltf/GltfApi/GeneratedSchema/AnimationChannelTarget.gen.cs b/Brutal.Gltf/GltfApi/GeneratedSchema/AnimationChannelTarget.gen.cs
index b1b3e14..92ef86b 100644
--- a/Brutal.Gltf/GltfApi/GeneratedSchema/AnimationChannelTarget.gen.cs
+++ b/Brutal.Gltf/GltfApi/GeneratedSchema/AnimationChannelTarget.gen.cs
@@ -58,7 +58,7 @@ namespace Brutal.GltfApi {
///
/// The name of the node's TRS property to animate, or the `"weights"` of the Morph Targets it instantiates. For the `"translation"` property, the values that are provided by the sampler are the translation along the X, Y, and Z axes. For the `"rotation"` property, the values are a quaternion in the order (x, y, z, w), where w is the scalar. For the `"scale"` property, the values are the scaling factors along the X, Y, and Z axes.
///
- [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
+ [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[System.Text.Json.Serialization.JsonRequiredAttribute()]
[System.Text.Json.Serialization.JsonPropertyNameAttribute("path")]
public PathEnum Path {
diff --git a/Brutal.Gltf/GltfApi/GeneratedSchema/AnimationSampler.gen.cs b/Brutal.Gltf/GltfApi/GeneratedSchema/AnimationSampler.gen.cs
index d19cefe..d248640 100644
--- a/Brutal.Gltf/GltfApi/GeneratedSchema/AnimationSampler.gen.cs
+++ b/Brutal.Gltf/GltfApi/GeneratedSchema/AnimationSampler.gen.cs
@@ -64,7 +64,7 @@ namespace Brutal.GltfApi {
///
/// Interpolation algorithm.
///
- [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
+ [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[System.Text.Json.Serialization.JsonPropertyNameAttribute("interpolation")]
public InterpolationEnum Interpolation {
get {
diff --git a/Brutal.Gltf/GltfApi/GeneratedSchema/Camera.gen.cs b/Brutal.Gltf/GltfApi/GeneratedSchema/Camera.gen.cs
index 487635d..3a53e0d 100644
--- a/Brutal.Gltf/GltfApi/GeneratedSchema/Camera.gen.cs
+++ b/Brutal.Gltf/GltfApi/GeneratedSchema/Camera.gen.cs
@@ -78,7 +78,7 @@ namespace Brutal.GltfApi {
///
/// Specifies if the camera uses a perspective or orthographic projection.
///
- [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
+ [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[System.Text.Json.Serialization.JsonRequiredAttribute()]
[System.Text.Json.Serialization.JsonPropertyNameAttribute("type")]
public TypeEnum Type {
diff --git a/Brutal.Gltf/GltfApi/GeneratedSchema/GltfJsonContext.gen.cs b/Brutal.Gltf/GltfApi/GeneratedSchema/GltfJsonContext.gen.cs
new file mode 100644
index 0000000..9f16494
--- /dev/null
+++ b/Brutal.Gltf/GltfApi/GeneratedSchema/GltfJsonContext.gen.cs
@@ -0,0 +1,46 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace Brutal.GltfApi {
+
+
+ ///
+ /// Source-generated JSON metadata for the generated glTF schema types.
+ ///
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(System.Text.Json.JsonElement))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(DracoMeshCompressionGltfMeshPrimitiveExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Gltf))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(LightsPunctualGltfDocumentExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsAnisotropyGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsClearcoatGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsEmissiveStrengthGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsIridescenceGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsSheenGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsSpecularGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsTransmissionGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsUnlitGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MaterialsVolumeGltfMaterialExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(TextureBasisuGltfTextureExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(TextureTransformGltfTextureinfoExtension))]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Accessor.ComponentTypeEnum), TypeInfoPropertyName="AccessorComponentTypeEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Accessor.TypeEnum), TypeInfoPropertyName="AccessorTypeEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(AccessorSparseIndices.ComponentTypeEnum), TypeInfoPropertyName="AccessorSparseIndicesComponentTypeEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(AnimationChannelTarget.PathEnum), TypeInfoPropertyName="AnimationChannelTargetPathEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(AnimationSampler.InterpolationEnum), TypeInfoPropertyName="AnimationSamplerInterpolationEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(BufferView.TargetEnum), TypeInfoPropertyName="BufferViewTargetEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Camera.TypeEnum), TypeInfoPropertyName="CameraTypeEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Material.AlphaModeEnum), TypeInfoPropertyName="MaterialAlphaModeEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(MeshPrimitive.ModeEnum), TypeInfoPropertyName="MeshPrimitiveModeEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Sampler.MagFilterEnum), TypeInfoPropertyName="SamplerMagFilterEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Sampler.MinFilterEnum), TypeInfoPropertyName="SamplerMinFilterEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Sampler.WrapSEnum), TypeInfoPropertyName="SamplerWrapSEnum")]
+ [System.Text.Json.Serialization.JsonSerializableAttribute(typeof(Sampler.WrapTEnum), TypeInfoPropertyName="SamplerWrapTEnum")]
+ internal partial class GltfJsonContext {
+ }
+}
diff --git a/Brutal.Gltf/GltfApi/GeneratedSchema/Material.gen.cs b/Brutal.Gltf/GltfApi/GeneratedSchema/Material.gen.cs
index 57b0c6d..afae9d0 100644
--- a/Brutal.Gltf/GltfApi/GeneratedSchema/Material.gen.cs
+++ b/Brutal.Gltf/GltfApi/GeneratedSchema/Material.gen.cs
@@ -181,7 +181,7 @@ namespace Brutal.GltfApi {
///
/// The alpha rendering mode of the material.
///
- [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
+ [System.Text.Json.Serialization.JsonConverterAttribute(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[System.Text.Json.Serialization.JsonPropertyNameAttribute("alphaMode")]
public AlphaModeEnum AlphaMode {
get {
diff --git a/Brutal.Gltf/GltfApi/GltfJsonContext.cs b/Brutal.Gltf/GltfApi/GltfJsonContext.cs
new file mode 100644
index 0000000..7f89361
--- /dev/null
+++ b/Brutal.Gltf/GltfApi/GltfJsonContext.cs
@@ -0,0 +1,27 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Brutal.GltfApi;
+
+///
+/// Source-generated System.Text.Json metadata for the glTF schema, so that loading and saving
+/// works without reflection (trimming and Native AOT).
+///
+///
+/// The generator emits the other half of this class (GeneratedSchema/GltfJsonContext.gen.cs) with every
+/// : the document root, every extension root type, the nested enums and
+/// . Don't add here; the System.Text.Json source
+/// generator fails when more than one partial declaration carries it.
+///
+[JsonSourceGenerationOptions(
+ // glTF has no concept of an explicit JSON null; absent optional properties must be
+ // omitted entirely or strict validators reject the asset (e.g. "uri": null in GLB).
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ Converters = [
+ typeof(JsonHelpers.Float3JsonConverter),
+ typeof(JsonHelpers.Float4JsonConverter),
+ typeof(JsonHelpers.FloatQuatJsonConverter),
+ typeof(JsonHelpers.Float4X4JsonConverter),
+ ]
+)]
+internal partial class GltfJsonContext : JsonSerializerContext;
diff --git a/Brutal.Gltf/GltfApi/GltfUtility.cs b/Brutal.Gltf/GltfApi/GltfUtility.cs
index cc08e93..979fc22 100644
--- a/Brutal.Gltf/GltfApi/GltfUtility.cs
+++ b/Brutal.Gltf/GltfApi/GltfUtility.cs
@@ -1,5 +1,7 @@
+using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Text.Json;
+using System.Text.Json.Serialization.Metadata;
namespace Brutal.GltfApi;
@@ -149,21 +151,37 @@ public static class GltfUtility
}
}
+ [UnconditionalSuppressMessage(
+ "Trimming",
+ "IL2026",
+ Justification = "Reflection is only used when JsonSerializer.IsReflectionEnabledByDefault, which is false under trimming and Native AOT."
+ )]
+ [UnconditionalSuppressMessage(
+ "AOT",
+ "IL3050",
+ Justification = "Reflection is only used when JsonSerializer.IsReflectionEnabledByDefault, which is false under trimming and Native AOT."
+ )]
private static JsonSerializerOptions CreateSerializerOptions()
{
- var options = new JsonSerializerOptions();
- // glTF has no concept of an explicit JSON null; absent optional properties must be
- // omitted entirely or strict validators reject the asset (e.g. "uri": null in GLB).
- options.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
- options.Converters.Add(new JsonHelpers.Float3JsonConverter());
- options.Converters.Add(new JsonHelpers.Float4JsonConverter());
- options.Converters.Add(new JsonHelpers.FloatQuatJsonConverter());
- options.Converters.Add(new JsonHelpers.Float4X4JsonConverter());
+ // Settings, converters and metadata come from the source-generated GltfJsonContext, which is all
+ // that is available under trimming and Native AOT. When reflection is enabled, fall back to it for
+ // types the context doesn't know, such as custom extension classes passed to GetExtension or
+ // assigned to an Extensions map.
+ var options = new JsonSerializerOptions(GltfJsonContext.Default.Options);
+ if (JsonSerializer.IsReflectionEnabledByDefault)
+ {
+ options.TypeInfoResolver = JsonTypeInfoResolver.Combine(
+ GltfJsonContext.Default,
+ new DefaultJsonTypeInfoResolver()
+ );
+ }
return options;
}
internal static readonly JsonSerializerOptions JsonOptions = CreateSerializerOptions();
+ private static readonly JsonTypeInfo GltfTypeInfo = (JsonTypeInfo)JsonOptions.GetTypeInfo(typeof(Gltf));
+
///
/// Parses a JSON formatted text content
///
@@ -171,7 +189,7 @@ public static class GltfUtility
/// Schema.Gltf model
public static Gltf DeserializeModelJson(string fileData)
{
- return JsonSerializer.Deserialize(fileData, JsonOptions) ?? throw new NullReferenceException();
+ return JsonSerializer.Deserialize(fileData, GltfTypeInfo) ?? throw new NullReferenceException();
}
///
@@ -181,7 +199,7 @@ public static class GltfUtility
/// JSON formatted text
public static string SerializeModelJson(this Gltf model)
{
- return JsonSerializer.Serialize(model, JsonOptions);
+ return JsonSerializer.Serialize(model, GltfTypeInfo);
}
private static byte[]? TryLoadBase64BinaryBufferUnchecked(Buffer buffer, string prefix)
diff --git a/Brutal.Gltf/GltfApi/IExtensionGltfObject.cs b/Brutal.Gltf/GltfApi/IExtensionGltfObject.cs
index 0255f56..24d5efb 100644
--- a/Brutal.Gltf/GltfApi/IExtensionGltfObject.cs
+++ b/Brutal.Gltf/GltfApi/IExtensionGltfObject.cs
@@ -1,4 +1,5 @@
using System.Text.Json;
+using System.Text.Json.Serialization.Metadata;
namespace Brutal.GltfApi;
@@ -9,8 +10,31 @@ public interface IExtensionGltfObject
public static class GltfExtensions
{
+ ///
+ /// Gets an extension object by name.
+ ///
+ ///
+ /// Under trimming or Native AOT, must be one of the extension types this library
+ /// defines; for your own extension types use the overload that takes a .
+ ///
public static T? GetExtension(this IExtensionGltfObject obj, string extensionName)
where T : class
+ {
+ return GetExtensionCore(obj, extensionName, jsonTypeInfo: null);
+ }
+
+ ///
+ /// Gets an extension object by name, reading it with the given source-generated metadata.
+ ///
+ public static T? GetExtension(this IExtensionGltfObject obj, string extensionName, JsonTypeInfo jsonTypeInfo)
+ where T : class
+ {
+ ArgumentNullException.ThrowIfNull(jsonTypeInfo);
+ return GetExtensionCore(obj, extensionName, jsonTypeInfo);
+ }
+
+ private static T? GetExtensionCore(IExtensionGltfObject obj, string extensionName, JsonTypeInfo? jsonTypeInfo)
+ where T : class
{
var extensionMap = obj.Extensions;
if (extensionMap == null || !extensionMap.TryGetValue(extensionName, out var extObj))
@@ -19,8 +43,10 @@ public static class GltfExtensions
// from deserialization hold the raw JsonElement.
if (extObj is T typed)
return typed;
+ // Metadata is resolved only here: for an unregistered T it throws under Native AOT, and in JIT builds
+ // for types System.Text.Json can't describe, which must not break lookups that never deserialize.
if (extObj is JsonElement je)
- return je.Deserialize(GltfUtility.JsonOptions);
+ return je.Deserialize(jsonTypeInfo ?? (JsonTypeInfo)GltfUtility.JsonOptions.GetTypeInfo(typeof(T)));
throw new InvalidCastException(
$"Extension '{extensionName}' holds a {extObj.GetType()}, expected {typeof(T)} or JsonElement"
);
diff --git a/Brutal.Gltf/LICENSES/BRUTAL-GLTF-THIRD-PARTY-NOTICES.txt b/Brutal.Gltf/LICENSES/BRUTAL-GLTF-THIRD-PARTY-NOTICES.txt
index cfe2353..f39b221 100644
--- a/Brutal.Gltf/LICENSES/BRUTAL-GLTF-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Gltf/LICENSES/BRUTAL-GLTF-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Gltf
+Ahwoo.BRUTAL.Gltf
This package contains no third-party library. Its glTF type definitions are generated
from The Khronos Group's glTF 2.0 JSON schemas, and the descriptive text of those
diff --git a/Brutal.ImGui.Abstractions/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt b/Brutal.ImGui.Abstractions/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
new file mode 100644
index 0000000..3ac9b12
--- /dev/null
+++ b/Brutal.ImGui.Abstractions/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
@@ -0,0 +1,180 @@
+THIRD-PARTY LICENSE NOTICES
+The Brutal.ImGui packages
+
+This file ships in all eleven packages named below. They redistribute the third-party
+components listed here, each reproduced with the license that governs it.
+
+ One file serves all eleven packages, so this table says which components apply to
+ the package you are holding:
+
+ Ahwoo.BRUTAL.ImGui Dear ImGui, and the three stb libraries
+ compiled into it
+ Ahwoo.BRUTAL.ImGui.Backends Dear ImGui's platform and renderer
+ backends, translated to C#
+ Ahwoo.BRUTAL.ImGui.DemoWindow Dear ImGui's demo sources, translated
+ to C#
+ Ahwoo.BRUTAL.ImGui.FreeType Dear ImGui's FreeType font adapter
+ Ahwoo.BRUTAL.ImPlot ImPlot
+ Ahwoo.BRUTAL.ImPlot.DemoWindow ImPlot's demo sources, translated to C#
+ Ahwoo.BRUTAL.ImGui.Native Dear ImGui's native library, and the three
+ stb libraries compiled into it
+ Ahwoo.BRUTAL.ImGui.FreeType.Native Dear ImGui's FreeType font adapter, as a
+ native library
+ Ahwoo.BRUTAL.ImPlot.Native ImPlot's native library
+ Ahwoo.BRUTAL.ImGui.Abstractions no third-party code
+ Ahwoo.BRUTAL.ImGui.Extensions no third-party code
+
+ The native libraries ship only in the three .Native packages, each for every
+ runtime identifier it supports (win-x64, linux-x64, osx-arm64):
+
+ Dear ImGui 1.92.2 imgui.dll / libimgui.so / libimgui.dylib
+ imgui_freetype.dll / libimgui_freetype.so / libimgui_freetype.dylib
+ ImPlot 0.17 implot.dll / libimplot.so / libimplot.dylib
+
+ Dear ImGui vendors three of Sean Barrett's stb libraries, and all three are
+ compiled into the Dear ImGui binaries shipped here. They have their own section
+ below.
+
+ The managed assemblies are in scope as well as the native libraries. Type names,
+ enumerant values and entry-point signatures are generated from the corresponding
+ upstream headers, and the backend and demo assemblies are C# translations of
+ upstream sources.
+
+ Ahwoo.BRUTAL.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which
+ is Dear ImGui code and is covered by the Dear ImGui section below. FreeType itself
+ is in none of these eleven packages; it is supplied by Ahwoo.BRUTAL.FreeType,
+ whose own notices reproduce the FreeType License in full.
+
+
+==============================================================================
+Dear ImGui
+==============================================================================
+
+ Name Dear ImGui
+ Version 1.92.2, docking branch
+ Upstream https://github.com/ocornut/imgui
+ SPDX MIT
+
+ Built from a RocketWerkz fork of the docking branch. The modifications are ours
+ and do not alter the terms below, which are reproduced from the copy these
+ packages were built from.
+
+ This component covers the imgui and imgui_freetype native libraries, the managed
+ bindings generated from Dear ImGui's headers, and the C# translations of Dear
+ ImGui's backend and demo sources.
+
+The MIT License (MIT)
+
+Copyright (c) 2014-2025 Omar Cornut
+
+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.
+
+
+==============================================================================
+stb
+==============================================================================
+
+ Name stb_rect_pack, stb_textedit, stb_truetype
+ Version 1.01, 1.14, 1.26 respectively
+ Upstream https://github.com/nothings/stb
+ SPDX MIT OR Unlicense
+
+ Vendored by Dear ImGui as imstb_rectpack.h, imstb_textedit.h and
+ imstb_truetype.h, and compiled into the Dear ImGui native libraries shipped
+ here. All three carry the same dual license, which offers a choice between
+ the MIT License and release into the public domain. It is reproduced once
+ below, from the copy these packages were built from.
+
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+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.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+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 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.
+------------------------------------------------------------------------------
+
+
+==============================================================================
+ImPlot
+==============================================================================
+
+ Name ImPlot
+ Version 0.17, upstream commit 3da8bd3 (26 commits after tag v0.16)
+ Upstream https://github.com/epezent/implot
+ SPDX MIT
+
+ ImPlot is a plotting extension for Dear ImGui. Its version is the one ImPlot
+ reports for itself; the commit is given because upstream had not tagged 0.17 when
+ these packages were built.
+
+ This component covers the implot native library, the managed bindings generated
+ from ImPlot's headers, and the C# translation of ImPlot's demo sources.
+
+MIT License
+
+Copyright (c) 2020 Evan Pezent
+
+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.
diff --git a/Brutal.ImGui.Backends/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt b/Brutal.ImGui.Backends/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
new file mode 100644
index 0000000..3ac9b12
--- /dev/null
+++ b/Brutal.ImGui.Backends/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
@@ -0,0 +1,180 @@
+THIRD-PARTY LICENSE NOTICES
+The Brutal.ImGui packages
+
+This file ships in all eleven packages named below. They redistribute the third-party
+components listed here, each reproduced with the license that governs it.
+
+ One file serves all eleven packages, so this table says which components apply to
+ the package you are holding:
+
+ Ahwoo.BRUTAL.ImGui Dear ImGui, and the three stb libraries
+ compiled into it
+ Ahwoo.BRUTAL.ImGui.Backends Dear ImGui's platform and renderer
+ backends, translated to C#
+ Ahwoo.BRUTAL.ImGui.DemoWindow Dear ImGui's demo sources, translated
+ to C#
+ Ahwoo.BRUTAL.ImGui.FreeType Dear ImGui's FreeType font adapter
+ Ahwoo.BRUTAL.ImPlot ImPlot
+ Ahwoo.BRUTAL.ImPlot.DemoWindow ImPlot's demo sources, translated to C#
+ Ahwoo.BRUTAL.ImGui.Native Dear ImGui's native library, and the three
+ stb libraries compiled into it
+ Ahwoo.BRUTAL.ImGui.FreeType.Native Dear ImGui's FreeType font adapter, as a
+ native library
+ Ahwoo.BRUTAL.ImPlot.Native ImPlot's native library
+ Ahwoo.BRUTAL.ImGui.Abstractions no third-party code
+ Ahwoo.BRUTAL.ImGui.Extensions no third-party code
+
+ The native libraries ship only in the three .Native packages, each for every
+ runtime identifier it supports (win-x64, linux-x64, osx-arm64):
+
+ Dear ImGui 1.92.2 imgui.dll / libimgui.so / libimgui.dylib
+ imgui_freetype.dll / libimgui_freetype.so / libimgui_freetype.dylib
+ ImPlot 0.17 implot.dll / libimplot.so / libimplot.dylib
+
+ Dear ImGui vendors three of Sean Barrett's stb libraries, and all three are
+ compiled into the Dear ImGui binaries shipped here. They have their own section
+ below.
+
+ The managed assemblies are in scope as well as the native libraries. Type names,
+ enumerant values and entry-point signatures are generated from the corresponding
+ upstream headers, and the backend and demo assemblies are C# translations of
+ upstream sources.
+
+ Ahwoo.BRUTAL.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which
+ is Dear ImGui code and is covered by the Dear ImGui section below. FreeType itself
+ is in none of these eleven packages; it is supplied by Ahwoo.BRUTAL.FreeType,
+ whose own notices reproduce the FreeType License in full.
+
+
+==============================================================================
+Dear ImGui
+==============================================================================
+
+ Name Dear ImGui
+ Version 1.92.2, docking branch
+ Upstream https://github.com/ocornut/imgui
+ SPDX MIT
+
+ Built from a RocketWerkz fork of the docking branch. The modifications are ours
+ and do not alter the terms below, which are reproduced from the copy these
+ packages were built from.
+
+ This component covers the imgui and imgui_freetype native libraries, the managed
+ bindings generated from Dear ImGui's headers, and the C# translations of Dear
+ ImGui's backend and demo sources.
+
+The MIT License (MIT)
+
+Copyright (c) 2014-2025 Omar Cornut
+
+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.
+
+
+==============================================================================
+stb
+==============================================================================
+
+ Name stb_rect_pack, stb_textedit, stb_truetype
+ Version 1.01, 1.14, 1.26 respectively
+ Upstream https://github.com/nothings/stb
+ SPDX MIT OR Unlicense
+
+ Vendored by Dear ImGui as imstb_rectpack.h, imstb_textedit.h and
+ imstb_truetype.h, and compiled into the Dear ImGui native libraries shipped
+ here. All three carry the same dual license, which offers a choice between
+ the MIT License and release into the public domain. It is reproduced once
+ below, from the copy these packages were built from.
+
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+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.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+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 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.
+------------------------------------------------------------------------------
+
+
+==============================================================================
+ImPlot
+==============================================================================
+
+ Name ImPlot
+ Version 0.17, upstream commit 3da8bd3 (26 commits after tag v0.16)
+ Upstream https://github.com/epezent/implot
+ SPDX MIT
+
+ ImPlot is a plotting extension for Dear ImGui. Its version is the one ImPlot
+ reports for itself; the commit is given because upstream had not tagged 0.17 when
+ these packages were built.
+
+ This component covers the implot native library, the managed bindings generated
+ from ImPlot's headers, and the C# translation of ImPlot's demo sources.
+
+MIT License
+
+Copyright (c) 2020 Evan Pezent
+
+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.
diff --git a/Brutal.ImGui.Backends/PlatformBackends/GlfwBackend.cs b/Brutal.ImGui.Backends/PlatformBackends/GlfwBackend.cs
index e5e3032..ad0cfb2 100644
--- a/Brutal.ImGui.Backends/PlatformBackends/GlfwBackend.cs
+++ b/Brutal.ImGui.Backends/PlatformBackends/GlfwBackend.cs
@@ -277,6 +277,9 @@ public partial class GlfwBackend : IPlatformBackend
private unsafe byte* GetClipboardText(ImGuiContextPtr context)
{
var str = Glfw.Clipboard;
+ if (str is null)
+ return null;
+
var byteCount = Utf8.GetByteCount(str);
_cachedClipboardText.Count = byteCount + 1;
Utf8.FromUtf16(str, _cachedClipboardText.AsSpan(), out _, out _);
diff --git a/Brutal.ImGui.Extensions/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt b/Brutal.ImGui.Extensions/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
new file mode 100644
index 0000000..3ac9b12
--- /dev/null
+++ b/Brutal.ImGui.Extensions/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
@@ -0,0 +1,180 @@
+THIRD-PARTY LICENSE NOTICES
+The Brutal.ImGui packages
+
+This file ships in all eleven packages named below. They redistribute the third-party
+components listed here, each reproduced with the license that governs it.
+
+ One file serves all eleven packages, so this table says which components apply to
+ the package you are holding:
+
+ Ahwoo.BRUTAL.ImGui Dear ImGui, and the three stb libraries
+ compiled into it
+ Ahwoo.BRUTAL.ImGui.Backends Dear ImGui's platform and renderer
+ backends, translated to C#
+ Ahwoo.BRUTAL.ImGui.DemoWindow Dear ImGui's demo sources, translated
+ to C#
+ Ahwoo.BRUTAL.ImGui.FreeType Dear ImGui's FreeType font adapter
+ Ahwoo.BRUTAL.ImPlot ImPlot
+ Ahwoo.BRUTAL.ImPlot.DemoWindow ImPlot's demo sources, translated to C#
+ Ahwoo.BRUTAL.ImGui.Native Dear ImGui's native library, and the three
+ stb libraries compiled into it
+ Ahwoo.BRUTAL.ImGui.FreeType.Native Dear ImGui's FreeType font adapter, as a
+ native library
+ Ahwoo.BRUTAL.ImPlot.Native ImPlot's native library
+ Ahwoo.BRUTAL.ImGui.Abstractions no third-party code
+ Ahwoo.BRUTAL.ImGui.Extensions no third-party code
+
+ The native libraries ship only in the three .Native packages, each for every
+ runtime identifier it supports (win-x64, linux-x64, osx-arm64):
+
+ Dear ImGui 1.92.2 imgui.dll / libimgui.so / libimgui.dylib
+ imgui_freetype.dll / libimgui_freetype.so / libimgui_freetype.dylib
+ ImPlot 0.17 implot.dll / libimplot.so / libimplot.dylib
+
+ Dear ImGui vendors three of Sean Barrett's stb libraries, and all three are
+ compiled into the Dear ImGui binaries shipped here. They have their own section
+ below.
+
+ The managed assemblies are in scope as well as the native libraries. Type names,
+ enumerant values and entry-point signatures are generated from the corresponding
+ upstream headers, and the backend and demo assemblies are C# translations of
+ upstream sources.
+
+ Ahwoo.BRUTAL.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which
+ is Dear ImGui code and is covered by the Dear ImGui section below. FreeType itself
+ is in none of these eleven packages; it is supplied by Ahwoo.BRUTAL.FreeType,
+ whose own notices reproduce the FreeType License in full.
+
+
+==============================================================================
+Dear ImGui
+==============================================================================
+
+ Name Dear ImGui
+ Version 1.92.2, docking branch
+ Upstream https://github.com/ocornut/imgui
+ SPDX MIT
+
+ Built from a RocketWerkz fork of the docking branch. The modifications are ours
+ and do not alter the terms below, which are reproduced from the copy these
+ packages were built from.
+
+ This component covers the imgui and imgui_freetype native libraries, the managed
+ bindings generated from Dear ImGui's headers, and the C# translations of Dear
+ ImGui's backend and demo sources.
+
+The MIT License (MIT)
+
+Copyright (c) 2014-2025 Omar Cornut
+
+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.
+
+
+==============================================================================
+stb
+==============================================================================
+
+ Name stb_rect_pack, stb_textedit, stb_truetype
+ Version 1.01, 1.14, 1.26 respectively
+ Upstream https://github.com/nothings/stb
+ SPDX MIT OR Unlicense
+
+ Vendored by Dear ImGui as imstb_rectpack.h, imstb_textedit.h and
+ imstb_truetype.h, and compiled into the Dear ImGui native libraries shipped
+ here. All three carry the same dual license, which offers a choice between
+ the MIT License and release into the public domain. It is reproduced once
+ below, from the copy these packages were built from.
+
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+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.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+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 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.
+------------------------------------------------------------------------------
+
+
+==============================================================================
+ImPlot
+==============================================================================
+
+ Name ImPlot
+ Version 0.17, upstream commit 3da8bd3 (26 commits after tag v0.16)
+ Upstream https://github.com/epezent/implot
+ SPDX MIT
+
+ ImPlot is a plotting extension for Dear ImGui. Its version is the one ImPlot
+ reports for itself; the commit is given because upstream had not tagged 0.17 when
+ these packages were built.
+
+ This component covers the implot native library, the managed bindings generated
+ from ImPlot's headers, and the C# translation of ImPlot's demo sources.
+
+MIT License
+
+Copyright (c) 2020 Evan Pezent
+
+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.
diff --git a/Brutal.ImGui.FreeType/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt b/Brutal.ImGui.FreeType/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
new file mode 100644
index 0000000..3ac9b12
--- /dev/null
+++ b/Brutal.ImGui.FreeType/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
@@ -0,0 +1,180 @@
+THIRD-PARTY LICENSE NOTICES
+The Brutal.ImGui packages
+
+This file ships in all eleven packages named below. They redistribute the third-party
+components listed here, each reproduced with the license that governs it.
+
+ One file serves all eleven packages, so this table says which components apply to
+ the package you are holding:
+
+ Ahwoo.BRUTAL.ImGui Dear ImGui, and the three stb libraries
+ compiled into it
+ Ahwoo.BRUTAL.ImGui.Backends Dear ImGui's platform and renderer
+ backends, translated to C#
+ Ahwoo.BRUTAL.ImGui.DemoWindow Dear ImGui's demo sources, translated
+ to C#
+ Ahwoo.BRUTAL.ImGui.FreeType Dear ImGui's FreeType font adapter
+ Ahwoo.BRUTAL.ImPlot ImPlot
+ Ahwoo.BRUTAL.ImPlot.DemoWindow ImPlot's demo sources, translated to C#
+ Ahwoo.BRUTAL.ImGui.Native Dear ImGui's native library, and the three
+ stb libraries compiled into it
+ Ahwoo.BRUTAL.ImGui.FreeType.Native Dear ImGui's FreeType font adapter, as a
+ native library
+ Ahwoo.BRUTAL.ImPlot.Native ImPlot's native library
+ Ahwoo.BRUTAL.ImGui.Abstractions no third-party code
+ Ahwoo.BRUTAL.ImGui.Extensions no third-party code
+
+ The native libraries ship only in the three .Native packages, each for every
+ runtime identifier it supports (win-x64, linux-x64, osx-arm64):
+
+ Dear ImGui 1.92.2 imgui.dll / libimgui.so / libimgui.dylib
+ imgui_freetype.dll / libimgui_freetype.so / libimgui_freetype.dylib
+ ImPlot 0.17 implot.dll / libimplot.so / libimplot.dylib
+
+ Dear ImGui vendors three of Sean Barrett's stb libraries, and all three are
+ compiled into the Dear ImGui binaries shipped here. They have their own section
+ below.
+
+ The managed assemblies are in scope as well as the native libraries. Type names,
+ enumerant values and entry-point signatures are generated from the corresponding
+ upstream headers, and the backend and demo assemblies are C# translations of
+ upstream sources.
+
+ Ahwoo.BRUTAL.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which
+ is Dear ImGui code and is covered by the Dear ImGui section below. FreeType itself
+ is in none of these eleven packages; it is supplied by Ahwoo.BRUTAL.FreeType,
+ whose own notices reproduce the FreeType License in full.
+
+
+==============================================================================
+Dear ImGui
+==============================================================================
+
+ Name Dear ImGui
+ Version 1.92.2, docking branch
+ Upstream https://github.com/ocornut/imgui
+ SPDX MIT
+
+ Built from a RocketWerkz fork of the docking branch. The modifications are ours
+ and do not alter the terms below, which are reproduced from the copy these
+ packages were built from.
+
+ This component covers the imgui and imgui_freetype native libraries, the managed
+ bindings generated from Dear ImGui's headers, and the C# translations of Dear
+ ImGui's backend and demo sources.
+
+The MIT License (MIT)
+
+Copyright (c) 2014-2025 Omar Cornut
+
+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.
+
+
+==============================================================================
+stb
+==============================================================================
+
+ Name stb_rect_pack, stb_textedit, stb_truetype
+ Version 1.01, 1.14, 1.26 respectively
+ Upstream https://github.com/nothings/stb
+ SPDX MIT OR Unlicense
+
+ Vendored by Dear ImGui as imstb_rectpack.h, imstb_textedit.h and
+ imstb_truetype.h, and compiled into the Dear ImGui native libraries shipped
+ here. All three carry the same dual license, which offers a choice between
+ the MIT License and release into the public domain. It is reproduced once
+ below, from the copy these packages were built from.
+
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+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.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+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 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.
+------------------------------------------------------------------------------
+
+
+==============================================================================
+ImPlot
+==============================================================================
+
+ Name ImPlot
+ Version 0.17, upstream commit 3da8bd3 (26 commits after tag v0.16)
+ Upstream https://github.com/epezent/implot
+ SPDX MIT
+
+ ImPlot is a plotting extension for Dear ImGui. Its version is the one ImPlot
+ reports for itself; the commit is given because upstream had not tagged 0.17 when
+ these packages were built.
+
+ This component covers the implot native library, the managed bindings generated
+ from ImPlot's headers, and the C# translation of ImPlot's demo sources.
+
+MIT License
+
+Copyright (c) 2020 Evan Pezent
+
+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.
diff --git a/Brutal.ImGui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt b/Brutal.ImGui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
index b3cd102..3ac9b12 100644
--- a/Brutal.ImGui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.ImGui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
@@ -1,26 +1,31 @@
THIRD-PARTY LICENSE NOTICES
The Brutal.ImGui packages
-This file ships in all eight packages named below. They redistribute the third-party
+This file ships in all eleven packages named below. They redistribute the third-party
components listed here, each reproduced with the license that governs it.
- One file serves all eight packages, so this table says which components apply to
+ One file serves all eleven packages, so this table says which components apply to
the package you are holding:
- RocketWerkz.Brutal.ImGui Dear ImGui, and the three stb libraries
+ Ahwoo.BRUTAL.ImGui Dear ImGui, and the three stb libraries
compiled into it
- RocketWerkz.Brutal.ImGui.Backends Dear ImGui's platform and renderer
+ Ahwoo.BRUTAL.ImGui.Backends Dear ImGui's platform and renderer
backends, translated to C#
- RocketWerkz.Brutal.ImGui.DemoWindow Dear ImGui's demo sources, translated
+ Ahwoo.BRUTAL.ImGui.DemoWindow Dear ImGui's demo sources, translated
to C#
- RocketWerkz.Brutal.ImGui.FreeType Dear ImGui's FreeType font adapter
- RocketWerkz.Brutal.ImPlot ImPlot
- RocketWerkz.Brutal.ImPlot.DemoWindow ImPlot's demo sources, translated to C#
- RocketWerkz.Brutal.ImGui.Abstractions no third-party code
- RocketWerkz.Brutal.ImGui.Extensions no third-party code
+ Ahwoo.BRUTAL.ImGui.FreeType Dear ImGui's FreeType font adapter
+ Ahwoo.BRUTAL.ImPlot ImPlot
+ Ahwoo.BRUTAL.ImPlot.DemoWindow ImPlot's demo sources, translated to C#
+ Ahwoo.BRUTAL.ImGui.Native Dear ImGui's native library, and the three
+ stb libraries compiled into it
+ Ahwoo.BRUTAL.ImGui.FreeType.Native Dear ImGui's FreeType font adapter, as a
+ native library
+ Ahwoo.BRUTAL.ImPlot.Native ImPlot's native library
+ Ahwoo.BRUTAL.ImGui.Abstractions no third-party code
+ Ahwoo.BRUTAL.ImGui.Extensions no third-party code
- Where a package ships native libraries, it ships them for every runtime identifier
- it supports (win-x64, linux-x64, osx-arm64):
+ The native libraries ship only in the three .Native packages, each for every
+ runtime identifier it supports (win-x64, linux-x64, osx-arm64):
Dear ImGui 1.92.2 imgui.dll / libimgui.so / libimgui.dylib
imgui_freetype.dll / libimgui_freetype.so / libimgui_freetype.dylib
@@ -35,9 +40,9 @@ components listed here, each reproduced with the license that governs it.
upstream headers, and the backend and demo assemblies are C# translations of
upstream sources.
- RocketWerkz.Brutal.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which
+ Ahwoo.BRUTAL.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which
is Dear ImGui code and is covered by the Dear ImGui section below. FreeType itself
- is in none of these eight packages; it is supplied by RocketWerkz.Brutal.FreeType,
+ is in none of these eleven packages; it is supplied by Ahwoo.BRUTAL.FreeType,
whose own notices reproduce the FreeType License in full.
diff --git a/Brutal.ImPlot/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt b/Brutal.ImPlot/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
new file mode 100644
index 0000000..3ac9b12
--- /dev/null
+++ b/Brutal.ImPlot/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
@@ -0,0 +1,180 @@
+THIRD-PARTY LICENSE NOTICES
+The Brutal.ImGui packages
+
+This file ships in all eleven packages named below. They redistribute the third-party
+components listed here, each reproduced with the license that governs it.
+
+ One file serves all eleven packages, so this table says which components apply to
+ the package you are holding:
+
+ Ahwoo.BRUTAL.ImGui Dear ImGui, and the three stb libraries
+ compiled into it
+ Ahwoo.BRUTAL.ImGui.Backends Dear ImGui's platform and renderer
+ backends, translated to C#
+ Ahwoo.BRUTAL.ImGui.DemoWindow Dear ImGui's demo sources, translated
+ to C#
+ Ahwoo.BRUTAL.ImGui.FreeType Dear ImGui's FreeType font adapter
+ Ahwoo.BRUTAL.ImPlot ImPlot
+ Ahwoo.BRUTAL.ImPlot.DemoWindow ImPlot's demo sources, translated to C#
+ Ahwoo.BRUTAL.ImGui.Native Dear ImGui's native library, and the three
+ stb libraries compiled into it
+ Ahwoo.BRUTAL.ImGui.FreeType.Native Dear ImGui's FreeType font adapter, as a
+ native library
+ Ahwoo.BRUTAL.ImPlot.Native ImPlot's native library
+ Ahwoo.BRUTAL.ImGui.Abstractions no third-party code
+ Ahwoo.BRUTAL.ImGui.Extensions no third-party code
+
+ The native libraries ship only in the three .Native packages, each for every
+ runtime identifier it supports (win-x64, linux-x64, osx-arm64):
+
+ Dear ImGui 1.92.2 imgui.dll / libimgui.so / libimgui.dylib
+ imgui_freetype.dll / libimgui_freetype.so / libimgui_freetype.dylib
+ ImPlot 0.17 implot.dll / libimplot.so / libimplot.dylib
+
+ Dear ImGui vendors three of Sean Barrett's stb libraries, and all three are
+ compiled into the Dear ImGui binaries shipped here. They have their own section
+ below.
+
+ The managed assemblies are in scope as well as the native libraries. Type names,
+ enumerant values and entry-point signatures are generated from the corresponding
+ upstream headers, and the backend and demo assemblies are C# translations of
+ upstream sources.
+
+ Ahwoo.BRUTAL.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which
+ is Dear ImGui code and is covered by the Dear ImGui section below. FreeType itself
+ is in none of these eleven packages; it is supplied by Ahwoo.BRUTAL.FreeType,
+ whose own notices reproduce the FreeType License in full.
+
+
+==============================================================================
+Dear ImGui
+==============================================================================
+
+ Name Dear ImGui
+ Version 1.92.2, docking branch
+ Upstream https://github.com/ocornut/imgui
+ SPDX MIT
+
+ Built from a RocketWerkz fork of the docking branch. The modifications are ours
+ and do not alter the terms below, which are reproduced from the copy these
+ packages were built from.
+
+ This component covers the imgui and imgui_freetype native libraries, the managed
+ bindings generated from Dear ImGui's headers, and the C# translations of Dear
+ ImGui's backend and demo sources.
+
+The MIT License (MIT)
+
+Copyright (c) 2014-2025 Omar Cornut
+
+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.
+
+
+==============================================================================
+stb
+==============================================================================
+
+ Name stb_rect_pack, stb_textedit, stb_truetype
+ Version 1.01, 1.14, 1.26 respectively
+ Upstream https://github.com/nothings/stb
+ SPDX MIT OR Unlicense
+
+ Vendored by Dear ImGui as imstb_rectpack.h, imstb_textedit.h and
+ imstb_truetype.h, and compiled into the Dear ImGui native libraries shipped
+ here. All three carry the same dual license, which offers a choice between
+ the MIT License and release into the public domain. It is reproduced once
+ below, from the copy these packages were built from.
+
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+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.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+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 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.
+------------------------------------------------------------------------------
+
+
+==============================================================================
+ImPlot
+==============================================================================
+
+ Name ImPlot
+ Version 0.17, upstream commit 3da8bd3 (26 commits after tag v0.16)
+ Upstream https://github.com/epezent/implot
+ SPDX MIT
+
+ ImPlot is a plotting extension for Dear ImGui. Its version is the one ImPlot
+ reports for itself; the commit is given because upstream had not tagged 0.17 when
+ these packages were built.
+
+ This component covers the implot native library, the managed bindings generated
+ from ImPlot's headers, and the C# translation of ImPlot's demo sources.
+
+MIT License
+
+Copyright (c) 2020 Evan Pezent
+
+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.
diff --git a/Brutal.Localization/LICENSES/BRUTAL-LOCALIZATION-THIRD-PARTY-NOTICES.txt b/Brutal.Localization/LICENSES/BRUTAL-LOCALIZATION-THIRD-PARTY-NOTICES.txt
index afd0b6c..8f4b2bc 100644
--- a/Brutal.Localization/LICENSES/BRUTAL-LOCALIZATION-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Localization/LICENSES/BRUTAL-LOCALIZATION-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Localization
+Ahwoo.BRUTAL.Localization
This package redistributes the third-party component listed below. It is reproduced
with the license that governs it.
diff --git a/Brutal.MeshOptimizer/LICENSES/BRUTAL-MESHOPTIMIZER-THIRD-PARTY-NOTICES.txt b/Brutal.MeshOptimizer/LICENSES/BRUTAL-MESHOPTIMIZER-THIRD-PARTY-NOTICES.txt
index efdb35c..0421f7a 100644
--- a/Brutal.MeshOptimizer/LICENSES/BRUTAL-MESHOPTIMIZER-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.MeshOptimizer/LICENSES/BRUTAL-MESHOPTIMIZER-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.MeshOptimizer
+Ahwoo.BRUTAL.MeshOptimizer
Brutal.MeshOptimizer redistributes one third-party component, meshoptimizer, as native
libraries on every runtime identifier it supports. It is reproduced below with the
diff --git a/Brutal.NotCurses/LICENSES/BRUTAL-NOTCURSES-THIRD-PARTY-NOTICES.txt b/Brutal.NotCurses/LICENSES/BRUTAL-NOTCURSES-THIRD-PARTY-NOTICES.txt
index cca5840..076b396 100644
--- a/Brutal.NotCurses/LICENSES/BRUTAL-NOTCURSES-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.NotCurses/LICENSES/BRUTAL-NOTCURSES-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.NotCurses
+Ahwoo.BRUTAL.NotCurses
This package ships three third-party components on macOS and Linux and four on Windows: notcurses,
plus the parts of its dependency closure that are not part of the operating system.
@@ -11,7 +11,7 @@ plus the parts of its dependency closure that are not part of the operating syst
from the comments in those headers.
zlib is not built or shipped by this package on any platform. It is supplied by the
- RocketWerkz.Brutal.ZLib package, which this package depends on and whose own notices
+ Ahwoo.BRUTAL.ZLib package, which this package depends on and whose own notices
file covers it. The terminfo database is read from the host and is not shipped.
Upstream states a second license over one file that this package does not build. It
diff --git a/Brutal.OpenAl/LICENSES/BRUTAL-OPENAL-THIRD-PARTY-NOTICES.txt b/Brutal.OpenAl/LICENSES/BRUTAL-OPENAL-THIRD-PARTY-NOTICES.txt
index 995c46f..031ebd8 100644
--- a/Brutal.OpenAl/LICENSES/BRUTAL-OPENAL-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.OpenAl/LICENSES/BRUTAL-OPENAL-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.OpenAl
+Ahwoo.BRUTAL.OpenAl
This package redistributes the third-party components listed below, each reproduced
with the license that governs it.
diff --git a/Brutal.OpenGl/LICENSES/BRUTAL-OPENGL-THIRD-PARTY-NOTICES.txt b/Brutal.OpenGl/LICENSES/BRUTAL-OPENGL-THIRD-PARTY-NOTICES.txt
index 3699980..a482b26 100644
--- a/Brutal.OpenGl/LICENSES/BRUTAL-OPENGL-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.OpenGl/LICENSES/BRUTAL-OPENGL-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.OpenGl
+Ahwoo.BRUTAL.OpenGl
This package ships one third-party native library, glad, on win-x64, linux-x64 and
osx-arm64. It contains no OpenGL implementation - glad resolves OpenGL entry points at
diff --git a/Brutal.RakNet/LICENSES/BRUTAL-RAKNET-THIRD-PARTY-NOTICES.txt b/Brutal.RakNet/LICENSES/BRUTAL-RAKNET-THIRD-PARTY-NOTICES.txt
index f1f3c11..789a058 100644
--- a/Brutal.RakNet/LICENSES/BRUTAL-RAKNET-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.RakNet/LICENSES/BRUTAL-RAKNET-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.RakNet
+Ahwoo.BRUTAL.RakNet
This package redistributes third-party software. Where terms attach to that software,
the license governing it is reproduced below in full.
diff --git a/Brutal.Sdl.Image/LICENSES/BRUTAL-SDL-IMAGE-THIRD-PARTY-NOTICES.txt b/Brutal.Sdl.Image/LICENSES/BRUTAL-SDL-IMAGE-THIRD-PARTY-NOTICES.txt
index f74b56d..de27820 100644
--- a/Brutal.Sdl.Image/LICENSES/BRUTAL-SDL-IMAGE-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Sdl.Image/LICENSES/BRUTAL-SDL-IMAGE-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Sdl.Image
+Ahwoo.BRUTAL.Sdl.Image
This package redistributes third-party software. The licenses governing that software
are reproduced below in full.
@@ -24,7 +24,7 @@ WHAT THIS PACKAGE CONTAINS
A NOTE ON SCOPE
- This package depends on RocketWerkz.Brutal.Sdl and links against SDL3 at runtime.
+ This package depends on Ahwoo.BRUTAL.Sdl and links against SDL3 at runtime.
SDL3 is not contained in this package and is covered by that package's own notices.
SDL_image can optionally be built against libpng, libjpeg, libtiff, libwebp, libavif,
diff --git a/Brutal.Sdl.Mixer/LICENSES/BRUTAL-SDL-MIXER-THIRD-PARTY-NOTICES.txt b/Brutal.Sdl.Mixer/LICENSES/BRUTAL-SDL-MIXER-THIRD-PARTY-NOTICES.txt
index 8023639..94b69f4 100644
--- a/Brutal.Sdl.Mixer/LICENSES/BRUTAL-SDL-MIXER-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Sdl.Mixer/LICENSES/BRUTAL-SDL-MIXER-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Sdl.Mixer
+Ahwoo.BRUTAL.Sdl.Mixer
This package redistributes third-party software. The licenses governing that software
are reproduced below in full.
@@ -20,7 +20,7 @@ WHAT THIS PACKAGE CONTAINS
A NOTE ON SCOPE
- This package depends on RocketWerkz.Brutal.Sdl and links against SDL3 at runtime.
+ This package depends on Ahwoo.BRUTAL.Sdl and links against SDL3 at runtime.
SDL3 is not contained in this package and is covered by that package's own notices.
SDL_mixer can optionally be built against libmpg123, libFLAC, libvorbis, libopus,
diff --git a/Brutal.Sdl.Ttf/LICENSES/BRUTAL-SDL-TTF-THIRD-PARTY-NOTICES.txt b/Brutal.Sdl.Ttf/LICENSES/BRUTAL-SDL-TTF-THIRD-PARTY-NOTICES.txt
index 8479d44..74fc495 100644
--- a/Brutal.Sdl.Ttf/LICENSES/BRUTAL-SDL-TTF-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Sdl.Ttf/LICENSES/BRUTAL-SDL-TTF-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Sdl.Ttf
+Ahwoo.BRUTAL.Sdl.Ttf
This package redistributes third-party software. The licenses governing that software
are reproduced below in full.
@@ -42,12 +42,12 @@ FREETYPE IS DUAL-LICENSED, AND WE DISTRIBUTE UNDER THE FREETYPE LICENSE
This software is based in part of the work of the FreeType Team.
The year is 2023 because that is the year of FreeType 2.13.2, the version contained
- here. RocketWerkz.Brutal.FreeType contains a different version and its credit
+ here. Ahwoo.BRUTAL.FreeType contains a different version and its credit
states a different year; both are correct, and they must not be made to agree.
A NOTE ON SCOPE
- This package depends on RocketWerkz.Brutal.Sdl and links against SDL3 at runtime.
+ This package depends on Ahwoo.BRUTAL.Sdl and links against SDL3 at runtime.
SDL3 is not contained in this package and is covered by that package's own notices.
SDL_ttf can optionally be built against PlutoSVG and PlutoVG for colour-emoji
diff --git a/Brutal.Sdl/LICENSES/BRUTAL-SDL-THIRD-PARTY-NOTICES.txt b/Brutal.Sdl/LICENSES/BRUTAL-SDL-THIRD-PARTY-NOTICES.txt
index dfe5065..86dec03 100644
--- a/Brutal.Sdl/LICENSES/BRUTAL-SDL-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Sdl/LICENSES/BRUTAL-SDL-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Sdl
+Ahwoo.BRUTAL.Sdl
This package redistributes third-party software. The licenses governing that software
are reproduced below in full.
diff --git a/Brutal.ShaderC/LICENSES/BRUTAL-SHADERC-THIRD-PARTY-NOTICES.txt b/Brutal.ShaderC/LICENSES/BRUTAL-SHADERC-THIRD-PARTY-NOTICES.txt
index 4d7bf77..f6d8a05 100644
--- a/Brutal.ShaderC/LICENSES/BRUTAL-SHADERC-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.ShaderC/LICENSES/BRUTAL-SHADERC-THIRD-PARTY-NOTICES.txt
@@ -2,7 +2,7 @@
BRUTAL SHADERC - THIRD-PARTY NOTICES
==============================================================================
-RocketWerkz.Brutal.ShaderC redistributes third-party software inside the native
+Ahwoo.BRUTAL.ShaderC redistributes third-party software inside the native
libraries it ships under runtimes//native/:
shaderc_shared win-x64, linux-x64, osx-arm64
diff --git a/Brutal.Slang/AssemblyInfo.cs b/Brutal.Slang/AssemblyInfo.cs
new file mode 100644
index 0000000..c05c8ed
--- /dev/null
+++ b/Brutal.Slang/AssemblyInfo.cs
@@ -0,0 +1,3 @@
+using System.Runtime.CompilerServices;
+
+[assembly: InternalsVisibleTo("Brutal.Slang.Test")]
diff --git a/Brutal.Slang/BorrowedSlangInterfaceMarshaller.cs b/Brutal.Slang/BorrowedSlangInterfaceMarshaller.cs
new file mode 100644
index 0000000..1b5e63d
--- /dev/null
+++ b/Brutal.Slang/BorrowedSlangInterfaceMarshaller.cs
@@ -0,0 +1,18 @@
+using System.Runtime.InteropServices.Marshalling;
+
+namespace Brutal.SlangApi;
+
+// Slang's direct interface-returning getters/loaders lend a reference. The RCW
+// takes its own reference, but the returned pointer must not be released by the stub.
+[CustomMarshaller(
+ typeof(CustomMarshallerAttribute.GenericPlaceholder),
+ MarshalMode.Default,
+ typeof(BorrowedSlangInterfaceMarshaller<>)
+)]
+internal static unsafe class BorrowedSlangInterfaceMarshaller
+ where T : class
+{
+ public static T? ConvertToManaged(void* unmanaged) => Slang.WrapBorrowedComInstance((nint)unmanaged);
+
+ public static void* ConvertToUnmanaged(T? managed) => ComInterfaceMarshaller.ConvertToUnmanaged(managed);
+}
diff --git a/Brutal.Slang/EntryPointLayoutExtensions.cs b/Brutal.Slang/EntryPointLayoutExtensions.cs
new file mode 100644
index 0000000..15dadb4
--- /dev/null
+++ b/Brutal.Slang/EntryPointLayoutExtensions.cs
@@ -0,0 +1,20 @@
+namespace Brutal.SlangApi;
+
+///
+/// Hand-written helpers on entry-point reflection handles for flat-C getters that fill
+/// output arrays, which the generated signatures expose as raw pointers.
+///
+public static unsafe class EntryPointLayoutExtensions
+{
+ ///
+ /// Returns a compute entry point's thread-group size, its [numthreads], along
+ /// X, Y and Z. The handle borrows from its program layout, so call this only while the
+ /// component that produced the layout is alive.
+ ///
+ public static (ulong X, ulong Y, ulong Z) GetComputeThreadGroupSize(this EntryPointLayout entryPoint)
+ {
+ var sizes = stackalloc ulong[3];
+ Slang.PInvoke.spReflectionEntryPoint_getComputeThreadGroupSize(entryPoint, 3, sizes);
+ return (sizes[0], sizes[1], sizes[2]);
+ }
+}
diff --git a/Brutal.Slang/Generated/GlobalUsings.gen.cs b/Brutal.Slang/Generated/GlobalUsings.gen.cs
index aae177d..2039f5d 100644
--- a/Brutal.Slang/Generated/GlobalUsings.gen.cs
+++ b/Brutal.Slang/Generated/GlobalUsings.gen.cs
@@ -62,6 +62,7 @@ global using ReflectionDecl = Brutal.SlangApi.DeclReflection;
global using ReflectionEntryPoint = Brutal.SlangApi.EntryPointLayout;
global using ReflectionFunction = Brutal.SlangApi.FunctionReflection;
global using ReflectionGeneric = Brutal.SlangApi.GenericReflection;
+global using ReflectionModifier = Brutal.SlangApi.Modifier;
global using ReflectionParameter = Brutal.SlangApi.VariableLayoutReflection;
global using ReflectionType = Brutal.SlangApi.TypeReflection;
global using ReflectionTypeLayout = Brutal.SlangApi.TypeLayoutReflection;
@@ -69,4 +70,3 @@ global using ReflectionTypeParameter = Brutal.SlangApi.TypeParameterReflection;
global using ReflectionVariable = Brutal.SlangApi.VariableReflection;
global using ReflectionVariableLayout = Brutal.SlangApi.VariableLayoutReflection;
global using Session = Brutal.SlangApi.IGlobalSession;
-global using UserAttribute = Brutal.SlangApi.Attribute;
diff --git a/Brutal.Slang/Generated/Interfaces.gen.cs b/Brutal.Slang/Generated/Interfaces.gen.cs
index a05676c..24b982c 100644
--- a/Brutal.Slang/Generated/Interfaces.gen.cs
+++ b/Brutal.Slang/Generated/Interfaces.gen.cs
@@ -7,17 +7,7 @@ namespace Brutal.SlangApi
{
[GeneratedComInterface]
[Guid("00000000-0000-0000-c000-000000000046")]
- public unsafe partial interface ISlangUnknown
- {
- [PreserveSig]
- Result QueryInterface(ref Brutal.SlangApi.Uuid uuid, out void* outObject);
-
- [PreserveSig]
- uint AddRef();
-
- [PreserveSig]
- uint Release();
- };
+ public unsafe partial interface ISlangUnknown { };
[GeneratedComInterface]
[Guid("87ede0e1-4852-44b0-8bf2-cb31874de239")]
@@ -43,7 +33,8 @@ namespace Brutal.SlangApi
void* GetBufferPointer();
[PreserveSig]
- ByteSize64 GetBufferSize();
+ [return: MarshalUsing(typeof(SlangSizeMarshaller))]
+ ByteSize GetBufferSize();
};
[GeneratedComInterface]
@@ -51,7 +42,10 @@ namespace Brutal.SlangApi
public unsafe partial interface ISlangFileSystem : Brutal.SlangApi.ISlangCastable
{
[PreserveSig]
- Result LoadFile(byte* path, out ISlangBlob outBlob);
+ Result LoadFile(
+ byte* path,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outBlob
+ );
};
[GeneratedComInterface]
@@ -75,7 +69,11 @@ namespace Brutal.SlangApi
public unsafe partial interface ISlangSharedLibraryLoader
{
[PreserveSig]
- Result LoadSharedLibrary(byte* path, out ISlangSharedLibrary sharedLibraryOut);
+ Result LoadSharedLibrary(
+ byte* path,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out ISlangSharedLibrary sharedLibraryOut
+ );
};
[GeneratedComInterface]
@@ -83,21 +81,28 @@ namespace Brutal.SlangApi
public unsafe partial interface ISlangFileSystemExt : Brutal.SlangApi.ISlangFileSystem
{
[PreserveSig]
- Result GetFileUniqueIdentity(byte* path, out ISlangBlob outUniqueIdentity);
+ Result GetFileUniqueIdentity(
+ byte* path,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outUniqueIdentity
+ );
[PreserveSig]
Result CalcCombinedPath(
Brutal.SlangApi.PathType fromPathType,
byte* fromPath,
byte* path,
- out ISlangBlob pathOut
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob pathOut
);
[PreserveSig]
Result GetPathType(byte* path, out Brutal.SlangApi.PathType pathTypeOut);
[PreserveSig]
- Result GetPath(PathKind kind, byte* path, out ISlangBlob outPath);
+ Result GetPath(
+ PathKind kind,
+ byte* path,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outPath
+ );
[PreserveSig]
void ClearCache();
@@ -114,10 +119,13 @@ namespace Brutal.SlangApi
public unsafe partial interface ISlangMutableFileSystem : Brutal.SlangApi.ISlangFileSystemExt
{
[PreserveSig]
- Result SaveFile(byte* path, void* data, ByteSize64 size);
+ Result SaveFile(byte* path, void* data, [MarshalUsing(typeof(SlangSizeMarshaller))] ByteSize size);
[PreserveSig]
- Result SaveFileBlob(byte* path, ISlangBlob dataBlob);
+ Result SaveFileBlob(
+ byte* path,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] ISlangBlob dataBlob
+ );
[PreserveSig]
Result Remove(byte* path);
@@ -131,18 +139,19 @@ namespace Brutal.SlangApi
public unsafe partial interface ISlangWriter
{
[PreserveSig]
- byte* BeginAppendBuffer(ByteSize64 maxNumChars);
+ byte* BeginAppendBuffer([MarshalUsing(typeof(SlangSizeMarshaller))] ByteSize maxNumChars);
[PreserveSig]
- Result EndAppendBuffer(byte* buffer, ByteSize64 numChars);
+ Result EndAppendBuffer(byte* buffer, [MarshalUsing(typeof(SlangSizeMarshaller))] ByteSize numChars);
[PreserveSig]
- Result Write(byte* chars, ByteSize64 numChars);
+ Result Write(byte* chars, [MarshalUsing(typeof(SlangSizeMarshaller))] ByteSize numChars);
[PreserveSig]
void Flush();
[PreserveSig]
+ [return: MarshalUsing(typeof(SlangBoolMarshaller))]
Bool IsConsole();
[PreserveSig]
@@ -154,7 +163,8 @@ namespace Brutal.SlangApi
public unsafe partial interface ISlangProfiler
{
[PreserveSig]
- ByteSize64 GetEntryCount();
+ [return: MarshalUsing(typeof(SlangSizeMarshaller))]
+ ByteSize GetEntryCount();
[PreserveSig]
byte* GetEntryName(uint index);
@@ -171,7 +181,11 @@ namespace Brutal.SlangApi
public unsafe partial interface IGlobalSession
{
[PreserveSig]
- Result CreateSession(ref Brutal.SlangApi.SessionDesc desc, out Brutal.SlangApi.ISession outSession);
+ Result CreateSession(
+ ref Brutal.SlangApi.SessionDesc desc,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.ISession outSession
+ );
[PreserveSig]
Brutal.SlangApi.ProfileID FindProfile(byte* name);
@@ -183,7 +197,10 @@ namespace Brutal.SlangApi
void SetDownstreamCompilerPrelude(Brutal.SlangApi.PassThrough passThrough, byte* preludeText);
[PreserveSig]
- void GetDownstreamCompilerPrelude(Brutal.SlangApi.PassThrough passThrough, out ISlangBlob outPrelude);
+ void GetDownstreamCompilerPrelude(
+ Brutal.SlangApi.PassThrough passThrough,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outPrelude
+ );
[PreserveSig]
byte* GetBuildTagString();
@@ -201,18 +218,27 @@ namespace Brutal.SlangApi
void SetLanguagePrelude(Brutal.SlangApi.SourceLanguage sourceLanguage, byte* preludeText);
[PreserveSig]
- void GetLanguagePrelude(Brutal.SlangApi.SourceLanguage sourceLanguage, out ISlangBlob outPrelude);
+ void GetLanguagePrelude(
+ Brutal.SlangApi.SourceLanguage sourceLanguage,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outPrelude
+ );
[PreserveSig]
- Result CreateCompileRequest(out Brutal.SlangApi.ICompileRequest outCompileRequest);
+ Result CreateCompileRequest(
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ out Brutal.SlangApi.ICompileRequest outCompileRequest
+ );
[PreserveSig]
void AddBuiltins(byte* sourcePath, byte* sourceString);
[PreserveSig]
- void SetSharedLibraryLoader(ISlangSharedLibraryLoader loader);
+ void SetSharedLibraryLoader(
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] ISlangSharedLibraryLoader loader
+ );
[PreserveSig]
+ [return: MarshalUsing(typeof(BorrowedSlangInterfaceMarshaller))]
ISlangSharedLibraryLoader? GetSharedLibraryLoader();
[PreserveSig]
@@ -225,10 +251,16 @@ namespace Brutal.SlangApi
Result CompileCoreModule(CompileCoreModuleFlags flags);
[PreserveSig]
- Result LoadCoreModule(void* coreModule, ByteSize64 coreModuleSizeInBytes);
+ Result LoadCoreModule(
+ void* coreModule,
+ [MarshalUsing(typeof(SlangSizeMarshaller))] ByteSize coreModuleSizeInBytes
+ );
[PreserveSig]
- Result SaveCoreModule(Brutal.SlangApi.ArchiveType archiveType, out ISlangBlob outBlob);
+ Result SaveCoreModule(
+ Brutal.SlangApi.ArchiveType archiveType,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outBlob
+ );
[PreserveSig]
Brutal.SlangApi.CapabilityID FindCapability(byte* name);
@@ -257,23 +289,30 @@ namespace Brutal.SlangApi
int argc,
byte** argv,
out Brutal.SlangApi.SessionDesc outSessionDesc,
- out ISlangUnknown outAuxAllocation
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangUnknown outAuxAllocation
);
[PreserveSig]
- Result GetSessionDescDigest(in Brutal.SlangApi.SessionDesc sessionDesc, out ISlangBlob outBlob);
+ Result GetSessionDescDigest(
+ in Brutal.SlangApi.SessionDesc sessionDesc,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outBlob
+ );
[PreserveSig]
Result CompileBuiltinModule(Brutal.SlangApi.BuiltinModuleName module, CompileCoreModuleFlags flags);
[PreserveSig]
- Result LoadBuiltinModule(Brutal.SlangApi.BuiltinModuleName module, void* moduleData, ByteSize64 sizeInBytes);
+ Result LoadBuiltinModule(
+ Brutal.SlangApi.BuiltinModuleName module,
+ void* moduleData,
+ [MarshalUsing(typeof(SlangSizeMarshaller))] ByteSize sizeInBytes
+ );
[PreserveSig]
Result SaveBuiltinModule(
Brutal.SlangApi.BuiltinModuleName module,
Brutal.SlangApi.ArchiveType archiveType,
- out ISlangBlob outBlob
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outBlob
);
};
@@ -282,118 +321,154 @@ namespace Brutal.SlangApi
public unsafe partial interface ISession
{
[PreserveSig]
+ [return: MarshalUsing(typeof(BorrowedSlangInterfaceMarshaller))]
Brutal.SlangApi.IGlobalSession? GetGlobalSession();
[PreserveSig]
- Brutal.SlangApi.IModule? LoadModule(byte* moduleName, out IBlob outDiagnostics);
+ [return: MarshalUsing(typeof(BorrowedSlangInterfaceMarshaller))]
+ Brutal.SlangApi.IModule? LoadModule(
+ byte* moduleName,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
+ );
[PreserveSig]
+ [return: MarshalUsing(typeof(BorrowedSlangInterfaceMarshaller))]
Brutal.SlangApi.IModule? LoadModuleFromSource(
byte* moduleName,
byte* path,
- IBlob source,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] IBlob source,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
[PreserveSig]
Result CreateCompositeComponentType(
nint* componentTypes,
Int componentTypeCount,
- out Brutal.SlangApi.IComponentType outCompositeComponentType,
- out ISlangBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IComponentType outCompositeComponentType,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
);
[PreserveSig]
+ [return: MarshalUsing(typeof(SlangHandleMarshaller))]
Brutal.SlangApi.TypeReflection SpecializeType(
- Brutal.SlangApi.TypeReflection type,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection type,
in Brutal.SlangApi.SpecializationArg specializationArgs,
Int specializationArgCount,
- out ISlangBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
);
[PreserveSig]
+ [return: MarshalUsing(typeof(SlangHandleMarshaller))]
Brutal.SlangApi.TypeLayoutReflection GetTypeLayout(
- Brutal.SlangApi.TypeReflection type,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection type,
Int targetIndex,
Brutal.SlangApi.LayoutRules rules,
- out ISlangBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
);
[PreserveSig]
+ [return: MarshalUsing(typeof(SlangHandleMarshaller))]
Brutal.SlangApi.TypeReflection GetContainerType(
- Brutal.SlangApi.TypeReflection elementType,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection elementType,
Brutal.SlangApi.ContainerType containerType,
- out ISlangBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
);
[PreserveSig]
+ [return: MarshalUsing(typeof(SlangHandleMarshaller))]
Brutal.SlangApi.TypeReflection GetDynamicType();
[PreserveSig]
- Result GetTypeRTTIMangledName(Brutal.SlangApi.TypeReflection type, out ISlangBlob outNameBlob);
+ Result GetTypeRTTIMangledName(
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection type,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outNameBlob
+ );
[PreserveSig]
Result GetTypeConformanceWitnessMangledName(
- Brutal.SlangApi.TypeReflection type,
- Brutal.SlangApi.TypeReflection interfaceType,
- out ISlangBlob outNameBlob
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection type,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection interfaceType,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outNameBlob
);
[PreserveSig]
Result GetTypeConformanceWitnessSequentialID(
- Brutal.SlangApi.TypeReflection type,
- Brutal.SlangApi.TypeReflection interfaceType,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection type,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection interfaceType,
out uint outId
);
[PreserveSig]
- Result CreateCompileRequest(out CompileRequest outCompileRequest);
-
- [PreserveSig]
- Result CreateTypeConformanceComponentType(
- Brutal.SlangApi.TypeReflection type,
- Brutal.SlangApi.TypeReflection interfaceType,
- out Brutal.SlangApi.ITypeConformance outConformance,
- Int conformanceIdOverride,
- out ISlangBlob outDiagnostics
+ Result CreateCompileRequest(
+ [MarshalUsing(typeof(SlangHandleMarshaller))] out CompileRequest outCompileRequest
);
[PreserveSig]
+ Result CreateTypeConformanceComponentType(
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection type,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection interfaceType,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.ITypeConformance outConformance,
+ Int conformanceIdOverride,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
+ );
+
+ [PreserveSig]
+ [return: MarshalUsing(typeof(BorrowedSlangInterfaceMarshaller))]
Brutal.SlangApi.IModule? LoadModuleFromIRBlob(
byte* moduleName,
byte* path,
- IBlob source,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] IBlob source,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
[PreserveSig]
Int GetLoadedModuleCount();
[PreserveSig]
+ [return: MarshalUsing(typeof(BorrowedSlangInterfaceMarshaller))]
Brutal.SlangApi.IModule? GetLoadedModule(Int index);
[PreserveSig]
- Brutal.Bool8 IsBinaryModuleUpToDate(byte* modulePath, IBlob binaryModuleBlob);
+ [return: MarshalUsing(typeof(SlangBoolMarshaller))]
+ Brutal.Bool8 IsBinaryModuleUpToDate(
+ byte* modulePath,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] IBlob binaryModuleBlob
+ );
[PreserveSig]
+ [return: MarshalUsing(typeof(BorrowedSlangInterfaceMarshaller))]
Brutal.SlangApi.IModule? LoadModuleFromSourceString(
byte* moduleName,
byte* path,
byte* @string,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
[PreserveSig]
Result GetDynamicObjectRTTIBytes(
- Brutal.SlangApi.TypeReflection type,
- Brutal.SlangApi.TypeReflection interfaceType,
- out uint outRTTIDataBuffer,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection type,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.TypeReflection interfaceType,
+ uint* outRTTIDataBuffer,
uint bufferSizeInBytes
);
[PreserveSig]
Result LoadModuleInfoFromIRBlob(
- IBlob source,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] IBlob source,
ref Int outModuleVersion,
ref byte* outModuleCompilerVersion,
ref byte* outModuleName
@@ -401,7 +476,8 @@ namespace Brutal.SlangApi
[PreserveSig]
Result GetDeclSourceLocation(
- Brutal.SlangApi.DeclReflection decl,
+ [MarshalUsing(typeof(SlangHandleMarshaller))]
+ Brutal.SlangApi.DeclReflection decl,
out Brutal.SlangApi.SourceLocation outLocation
);
};
@@ -411,65 +487,105 @@ namespace Brutal.SlangApi
public unsafe partial interface IComponentType
{
[PreserveSig]
+ [return: MarshalUsing(typeof(BorrowedSlangInterfaceMarshaller))]
Brutal.SlangApi.ISession? GetSession();
[PreserveSig]
- ProgramLayout GetLayout(Int targetIndex, out IBlob outDiagnostics);
+ [return: MarshalUsing(typeof(SlangHandleMarshaller))]
+ ProgramLayout GetLayout(
+ Int targetIndex,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
+ );
[PreserveSig]
Int GetSpecializationParamCount();
[PreserveSig]
- Result GetEntryPointCode(Int entryPointIndex, Int targetIndex, out IBlob outCode, out IBlob outDiagnostics);
+ Result GetEntryPointCode(
+ Int entryPointIndex,
+ Int targetIndex,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outCode,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
+ );
[PreserveSig]
- Result GetResultAsFileSystem(Int entryPointIndex, Int targetIndex, out ISlangMutableFileSystem outFileSystem);
+ Result GetResultAsFileSystem(
+ Int entryPointIndex,
+ Int targetIndex,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out ISlangMutableFileSystem outFileSystem
+ );
[PreserveSig]
- void GetEntryPointHash(Int entryPointIndex, Int targetIndex, out IBlob outHash);
+ void GetEntryPointHash(
+ Int entryPointIndex,
+ Int targetIndex,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outHash
+ );
[PreserveSig]
Result Specialize(
in Brutal.SlangApi.SpecializationArg specializationArgs,
Int specializationArgCount,
- out Brutal.SlangApi.IComponentType outSpecializedComponentType,
- out ISlangBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IComponentType outSpecializedComponentType,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
);
[PreserveSig]
- Result Link(out Brutal.SlangApi.IComponentType outLinkedComponentType, out ISlangBlob outDiagnostics);
+ Result Link(
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IComponentType outLinkedComponentType,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
+ );
[PreserveSig]
Result GetEntryPointHostCallable(
int entryPointIndex,
int targetIndex,
- out ISlangSharedLibrary outSharedLibrary,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out ISlangSharedLibrary outSharedLibrary,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
[PreserveSig]
- Result RenameEntryPoint(byte* newName, out Brutal.SlangApi.IComponentType outEntryPoint);
+ Result RenameEntryPoint(
+ byte* newName,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IComponentType outEntryPoint
+ );
[PreserveSig]
Result LinkWithOptions(
- out Brutal.SlangApi.IComponentType outLinkedComponentType,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IComponentType outLinkedComponentType,
uint compilerOptionEntryCount,
in Brutal.SlangApi.CompilerOptionEntry compilerOptionEntries,
- out ISlangBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
);
[PreserveSig]
- Result GetTargetCode(Int targetIndex, out IBlob outCode, out IBlob outDiagnostics);
+ Result GetTargetCode(
+ Int targetIndex,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outCode,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
+ );
[PreserveSig]
- Result GetTargetMetadata(Int targetIndex, out Brutal.SlangApi.IMetadata outMetadata, out IBlob outDiagnostics);
+ Result GetTargetMetadata(
+ Int targetIndex,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IMetadata outMetadata,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
+ );
[PreserveSig]
Result GetEntryPointMetadata(
Int entryPointIndex,
Int targetIndex,
- out Brutal.SlangApi.IMetadata outMetadata,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IMetadata outMetadata,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
};
@@ -478,16 +594,24 @@ namespace Brutal.SlangApi
public unsafe partial interface IModule : Brutal.SlangApi.IComponentType
{
[PreserveSig]
- Result FindEntryPointByName(byte* name, out Brutal.SlangApi.IEntryPoint outEntryPoint);
+ Result FindEntryPointByName(
+ byte* name,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IEntryPoint outEntryPoint
+ );
[PreserveSig]
Int32 GetDefinedEntryPointCount();
[PreserveSig]
- Result GetDefinedEntryPoint(Int32 index, out Brutal.SlangApi.IEntryPoint outEntryPoint);
+ Result GetDefinedEntryPoint(
+ Int32 index,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IEntryPoint outEntryPoint
+ );
[PreserveSig]
- Result Serialize(out ISlangBlob outSerializedBlob);
+ Result Serialize([MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outSerializedBlob);
[PreserveSig]
Result WriteToFile(byte* fileName);
@@ -505,8 +629,9 @@ namespace Brutal.SlangApi
Result FindAndCheckEntryPoint(
byte* name,
Brutal.SlangApi.Stage stage,
- out Brutal.SlangApi.IEntryPoint outEntryPoint,
- out ISlangBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IEntryPoint outEntryPoint,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
);
[PreserveSig]
@@ -516,10 +641,11 @@ namespace Brutal.SlangApi
byte* GetDependencyFilePath(Int32 index);
[PreserveSig]
+ [return: MarshalUsing(typeof(SlangHandleMarshaller))]
Brutal.SlangApi.DeclReflection GetModuleReflection();
[PreserveSig]
- Result Disassemble(out IBlob outDisassembledBlob);
+ Result Disassemble([MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDisassembledBlob);
};
[GeneratedComInterface]
@@ -535,7 +661,7 @@ namespace Brutal.SlangApi
Brutal.SlangApi.ParameterCategory category,
UInt spaceIndex,
UInt registerIndex,
- ref Brutal.Bool8 outUsed
+ [MarshalUsing(typeof(SlangBoolMarshaller))] ref Brutal.Bool8 outUsed
);
[PreserveSig]
@@ -550,10 +676,13 @@ namespace Brutal.SlangApi
uint GetItemCount();
[PreserveSig]
- Result GetItemData(uint index, out IBlob outblob);
+ Result GetItemData(uint index, [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outblob);
[PreserveSig]
- Result GetMetadata(out Brutal.SlangApi.IMetadata outMetadata);
+ Result GetMetadata(
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IMetadata outMetadata
+ );
};
[GeneratedComInterface]
@@ -561,6 +690,7 @@ namespace Brutal.SlangApi
public unsafe partial interface IEntryPoint : Brutal.SlangApi.IComponentType
{
[PreserveSig]
+ [return: MarshalUsing(typeof(SlangHandleMarshaller))]
Brutal.SlangApi.FunctionReflection GetFunctionReflection();
};
@@ -571,23 +701,26 @@ namespace Brutal.SlangApi
[PreserveSig]
Result GetTargetCompileResult(
Int targetIndex,
- out Brutal.SlangApi.ICompileResult outCompileResult,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.ICompileResult outCompileResult,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
[PreserveSig]
Result GetEntryPointCompileResult(
Int entryPointIndex,
Int targetIndex,
- out Brutal.SlangApi.ICompileResult outCompileResult,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.ICompileResult outCompileResult,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
[PreserveSig]
Result GetTargetHostCallable(
int targetIndex,
- out ISlangSharedLibrary outSharedLibrary,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out ISlangSharedLibrary outSharedLibrary,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
};
@@ -596,13 +729,16 @@ namespace Brutal.SlangApi
public unsafe partial interface IModulePrecompileService_Experimental
{
[PreserveSig]
- Result PrecompileForTarget(Brutal.SlangApi.CompileTarget target, out ISlangBlob outDiagnostics);
+ Result PrecompileForTarget(
+ Brutal.SlangApi.CompileTarget target,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out ISlangBlob outDiagnostics
+ );
[PreserveSig]
Result GetPrecompiledTargetCode(
Brutal.SlangApi.CompileTarget target,
- out IBlob outCode,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outCode,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
[PreserveSig]
@@ -611,8 +747,9 @@ namespace Brutal.SlangApi
[PreserveSig]
Result GetModuleDependency(
Int dependencyIndex,
- out Brutal.SlangApi.IModule outModule,
- out IBlob outDiagnostics
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))]
+ out Brutal.SlangApi.IModule outModule,
+ [MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outDiagnostics
);
};
@@ -621,7 +758,7 @@ namespace Brutal.SlangApi
public unsafe partial interface IByteCodeRunner
{
[PreserveSig]
- Result LoadModule(IBlob moduleBlob);
+ Result LoadModule([MarshalUsing(typeof(SlangInterfaceMarshaller))] IBlob moduleBlob);
[PreserveSig]
Result SelectFunctionByIndex(uint functionIndex);
@@ -636,13 +773,13 @@ namespace Brutal.SlangApi
void* GetCurrentWorkingSet();
[PreserveSig]
- Result Execute(void* argumentData, ByteSize64 argumentSize);
+ Result Execute(void* argumentData, [MarshalUsing(typeof(SlangSizeMarshaller))] ByteSize argumentSize);
[PreserveSig]
- void GetErrorString(out IBlob outBlob);
+ void GetErrorString([MarshalUsing(typeof(SlangInterfaceMarshaller))] out IBlob outBlob);
[PreserveSig]
- void* GetReturnValue(out ByteSize64 outValueSize);
+ void* GetReturnValue([MarshalUsing(typeof(SlangSizeMarshaller))] out ByteSize outValueSize);
[PreserveSig]
void SetExtInstHandlerUserData(void* userData);
diff --git a/Brutal.Slang/Generated/InterfacesExt.gen.cs b/Brutal.Slang/Generated/InterfacesExt.gen.cs
index 507551f..59a3da5 100644
--- a/Brutal.Slang/Generated/InterfacesExt.gen.cs
+++ b/Brutal.Slang/Generated/InterfacesExt.gen.cs
@@ -6,17 +6,6 @@ using Brutal.Strings;
namespace Brutal.SlangApi;
-public static unsafe partial class ISlangUnknownExtensions
-{
- public static void* QueryInterface(this ISlangUnknown self, ref Brutal.SlangApi.Uuid uuid)
- {
- self.QueryInterface(ref uuid, out var __result).ThrowIfFailure();
- return __result;
- }
- public static Result TryQueryInterface(this ISlangUnknown self, ref Brutal.SlangApi.Uuid uuid, out void* outObject)
- => self.QueryInterface(ref uuid, out outObject);
-}
-
public static unsafe partial class ISlangFileSystemExtensions
{
public static ISlangBlob LoadFile(this ISlangFileSystem self, byte* path)
@@ -75,7 +64,7 @@ public static unsafe partial class ISlangFileSystemExtExtensions
public static unsafe partial class ISlangMutableFileSystemExtensions
{
- public static Result TrySaveFile(this ISlangMutableFileSystem self, byte* path, void* data, ByteSize64 size)
+ public static Result TrySaveFile(this ISlangMutableFileSystem self, byte* path, void* data, ByteSize size)
=> self.SaveFile(path, data, size);
public static Result TrySaveFileBlob(this ISlangMutableFileSystem self, byte* path, ISlangBlob dataBlob)
=> self.SaveFileBlob(path, dataBlob);
@@ -87,9 +76,9 @@ public static unsafe partial class ISlangMutableFileSystemExtensions
public static unsafe partial class ISlangWriterExtensions
{
- public static Result TryEndAppendBuffer(this ISlangWriter self, byte* buffer, ByteSize64 numChars)
+ public static Result TryEndAppendBuffer(this ISlangWriter self, byte* buffer, ByteSize numChars)
=> self.EndAppendBuffer(buffer, numChars);
- public static Result TryWrite(this ISlangWriter self, byte* chars, ByteSize64 numChars)
+ public static Result TryWrite(this ISlangWriter self, byte* chars, ByteSize numChars)
=> self.Write(chars, numChars);
public static Result TrySetMode(this ISlangWriter self, Brutal.SlangApi.WriterMode mode)
=> self.SetMode(mode);
@@ -119,7 +108,7 @@ public static unsafe partial class IGlobalSessionExtensions
=> self.CheckPassThroughSupport(passThrough);
public static Result TryCompileCoreModule(this IGlobalSession self, CompileCoreModuleFlags flags)
=> self.CompileCoreModule(flags);
- public static Result TryLoadCoreModule(this IGlobalSession self, void* coreModule, ByteSize64 coreModuleSizeInBytes)
+ public static Result TryLoadCoreModule(this IGlobalSession self, void* coreModule, ByteSize coreModuleSizeInBytes)
=> self.LoadCoreModule(coreModule, coreModuleSizeInBytes);
public static ISlangBlob SaveCoreModule(this IGlobalSession self, Brutal.SlangApi.ArchiveType archiveType)
{
@@ -130,9 +119,9 @@ public static unsafe partial class IGlobalSessionExtensions
=> self.SaveCoreModule(archiveType, out outBlob);
public static Result TrySetSpirvCoreGrammar(this IGlobalSession self, byte* jsonPath)
=> self.SetSpirvCoreGrammar(jsonPath);
- public static ISlangUnknown ParseCommandLineArguments(this IGlobalSession self, int argc, byte** argv, out Brutal.SlangApi.SessionDesc outSessionDesc)
+ public static Brutal.SlangApi.SessionDesc ParseCommandLineArguments(this IGlobalSession self, int argc, byte** argv, out ISlangUnknown outAuxAllocation)
{
- self.ParseCommandLineArguments(argc, argv, out outSessionDesc, out var __result).ThrowIfFailure();
+ self.ParseCommandLineArguments(argc, argv, out var __result, out outAuxAllocation).ThrowIfFailure();
return __result;
}
public static Result TryParseCommandLineArguments(this IGlobalSession self, int argc, byte** argv, out Brutal.SlangApi.SessionDesc outSessionDesc, out ISlangUnknown outAuxAllocation)
@@ -146,7 +135,7 @@ public static unsafe partial class IGlobalSessionExtensions
=> self.GetSessionDescDigest(in sessionDesc, out outBlob);
public static Result TryCompileBuiltinModule(this IGlobalSession self, Brutal.SlangApi.BuiltinModuleName module, CompileCoreModuleFlags flags)
=> self.CompileBuiltinModule(module, flags);
- public static Result TryLoadBuiltinModule(this IGlobalSession self, Brutal.SlangApi.BuiltinModuleName module, void* moduleData, ByteSize64 sizeInBytes)
+ public static Result TryLoadBuiltinModule(this IGlobalSession self, Brutal.SlangApi.BuiltinModuleName module, void* moduleData, ByteSize sizeInBytes)
=> self.LoadBuiltinModule(module, moduleData, sizeInBytes);
public static ISlangBlob SaveBuiltinModule(this IGlobalSession self, Brutal.SlangApi.BuiltinModuleName module, Brutal.SlangApi.ArchiveType archiveType)
{
@@ -187,15 +176,15 @@ public static unsafe partial class ISessionExtensions
}
public static Result TryCreateCompileRequest(this ISession self, out CompileRequest outCompileRequest)
=> self.CreateCompileRequest(out outCompileRequest);
- public static ISlangBlob CreateTypeConformanceComponentType(this ISession self, Brutal.SlangApi.TypeReflection type, Brutal.SlangApi.TypeReflection interfaceType, out Brutal.SlangApi.ITypeConformance outConformance, Int conformanceIdOverride)
+ public static Brutal.SlangApi.ITypeConformance CreateTypeConformanceComponentType(this ISession self, Brutal.SlangApi.TypeReflection type, Brutal.SlangApi.TypeReflection interfaceType, Int conformanceIdOverride, out ISlangBlob outDiagnostics)
{
- self.CreateTypeConformanceComponentType(type, interfaceType, out outConformance, conformanceIdOverride, out var __result).ThrowIfFailure();
+ self.CreateTypeConformanceComponentType(type, interfaceType, out var __result, conformanceIdOverride, out outDiagnostics).ThrowIfFailure();
return __result;
}
public static Result TryCreateTypeConformanceComponentType(this ISession self, Brutal.SlangApi.TypeReflection type, Brutal.SlangApi.TypeReflection interfaceType, out Brutal.SlangApi.ITypeConformance outConformance, Int conformanceIdOverride, out ISlangBlob outDiagnostics)
=> self.CreateTypeConformanceComponentType(type, interfaceType, out outConformance, conformanceIdOverride, out outDiagnostics);
- public static Result TryGetDynamicObjectRTTIBytes(this ISession self, Brutal.SlangApi.TypeReflection type, Brutal.SlangApi.TypeReflection interfaceType, out uint outRTTIDataBuffer, uint bufferSizeInBytes)
- => self.GetDynamicObjectRTTIBytes(type, interfaceType, out outRTTIDataBuffer, bufferSizeInBytes);
+ public static Result TryGetDynamicObjectRTTIBytes(this ISession self, Brutal.SlangApi.TypeReflection type, Brutal.SlangApi.TypeReflection interfaceType, uint* outRTTIDataBuffer, uint bufferSizeInBytes)
+ => self.GetDynamicObjectRTTIBytes(type, interfaceType, outRTTIDataBuffer, bufferSizeInBytes);
public static Result TryLoadModuleInfoFromIRBlob(this ISession self, IBlob source, ref Int outModuleVersion, ref byte* outModuleCompilerVersion, ref byte* outModuleName)
=> self.LoadModuleInfoFromIRBlob(source, ref outModuleVersion, ref outModuleCompilerVersion, ref outModuleName);
public static Brutal.SlangApi.SourceLocation GetDeclSourceLocation(this ISession self, Brutal.SlangApi.DeclReflection decl)
@@ -251,9 +240,9 @@ public static unsafe partial class IComponentTypeExtensions
}
public static Result TryRenameEntryPoint(this IComponentType self, byte* newName, out Brutal.SlangApi.IComponentType outEntryPoint)
=> self.RenameEntryPoint(newName, out outEntryPoint);
- public static ISlangBlob LinkWithOptions(this IComponentType self, out Brutal.SlangApi.IComponentType outLinkedComponentType, uint compilerOptionEntryCount, in Brutal.SlangApi.CompilerOptionEntry compilerOptionEntries)
+ public static Brutal.SlangApi.IComponentType LinkWithOptions(this IComponentType self, uint compilerOptionEntryCount, in Brutal.SlangApi.CompilerOptionEntry compilerOptionEntries, out ISlangBlob outDiagnostics)
{
- self.LinkWithOptions(out outLinkedComponentType, compilerOptionEntryCount, in compilerOptionEntries, out var __result).ThrowIfFailure();
+ self.LinkWithOptions(out var __result, compilerOptionEntryCount, in compilerOptionEntries, out outDiagnostics).ThrowIfFailure();
return __result;
}
public static Result TryLinkWithOptions(this IComponentType self, out Brutal.SlangApi.IComponentType outLinkedComponentType, uint compilerOptionEntryCount, in Brutal.SlangApi.CompilerOptionEntry compilerOptionEntries, out ISlangBlob outDiagnostics)
@@ -409,7 +398,7 @@ public static unsafe partial class IByteCodeRunnerExtensions
}
public static Result TryGetFunctionInfo(this IByteCodeRunner self, uint index, out Brutal.SlangApi.ByteCodeFuncInfo outInfo)
=> self.GetFunctionInfo(index, out outInfo);
- public static Result TryExecute(this IByteCodeRunner self, void* argumentData, ByteSize64 argumentSize)
+ public static Result TryExecute(this IByteCodeRunner self, void* argumentData, ByteSize argumentSize)
=> self.Execute(argumentData, argumentSize);
public static Result TryRegisterExtCall(this IByteCodeRunner self, byte* name, VMExtFunction functionPtr)
=> self.RegisterExtCall(name, functionPtr);
diff --git a/Brutal.Slang/Generated/Slang.gen.cs b/Brutal.Slang/Generated/Slang.gen.cs
index 89c3a33..c727fa6 100644
--- a/Brutal.Slang/Generated/Slang.gen.cs
+++ b/Brutal.Slang/Generated/Slang.gen.cs
@@ -239,7 +239,7 @@ namespace Brutal.SlangApi
CompileRequest request,
RefString8 basePath,
void* libData,
- ByteSize64 libDataSize
+ ByteSize libDataSize
);
[LibraryImport("slang")]
@@ -342,7 +342,7 @@ namespace Brutal.SlangApi
public static partial void* spGetEntryPointCode(
CompileRequest request,
int entryPointIndex,
- out ByteSize64 outSize
+ out ByteSize outSize
);
[LibraryImport("slang")]
@@ -372,7 +372,7 @@ namespace Brutal.SlangApi
);
[LibraryImport("slang")]
- public static partial void* spGetCompileRequestCode(CompileRequest request, out ByteSize64 outSize);
+ public static partial void* spGetCompileRequestCode(CompileRequest request, out ByteSize outSize);
[LibraryImport("slang")]
public static partial Result spGetContainerCode(CompileRequest request, out nint outBlob);
@@ -382,7 +382,7 @@ namespace Brutal.SlangApi
CompileRequest request,
nint fileSystem,
void* data,
- ByteSize64 size
+ ByteSize size
);
[LibraryImport("slang")]
@@ -402,7 +402,7 @@ namespace Brutal.SlangApi
public static partial Result spExtractRepro(
nint session,
void* reproData,
- ByteSize64 reproDataSize,
+ ByteSize reproDataSize,
nint fileSystem
);
@@ -410,7 +410,7 @@ namespace Brutal.SlangApi
public static partial Result spLoadReproAsFileSystem(
nint session,
void* reproData,
- ByteSize64 reproDataSize,
+ ByteSize reproDataSize,
nint replaceFileSystem,
out nint outFileSystem
);
@@ -473,7 +473,7 @@ namespace Brutal.SlangApi
public static partial string spReflectionUserAttribute_GetArgumentValueString(
Brutal.SlangApi.ReflectionUserAttribute attrib,
uint index,
- out ByteSize64 outSize
+ out ByteSize outSize
);
[LibraryImport("slang")]
@@ -507,10 +507,10 @@ namespace Brutal.SlangApi
public static partial ReflectionVariable spReflectionType_GetFieldByIndex(ReflectionType type, uint index);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflectionType_GetElementCount(ReflectionType type);
+ public static partial ByteSize spReflectionType_GetElementCount(ReflectionType type);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflectionType_GetSpecializedElementCount(
+ public static partial ByteSize spReflectionType_GetSpecializedElementCount(
ReflectionType type,
Reflection reflection
);
@@ -558,13 +558,13 @@ namespace Brutal.SlangApi
public static partial Brutal.SlangApi.TypeKind spReflectionTypeLayout_getKind(ReflectionTypeLayout type);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflectionTypeLayout_GetSize(
+ public static partial ByteSize spReflectionTypeLayout_GetSize(
ReflectionTypeLayout type,
Brutal.SlangApi.ParameterCategory category
);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflectionTypeLayout_GetStride(
+ public static partial ByteSize spReflectionTypeLayout_GetStride(
ReflectionTypeLayout type,
Brutal.SlangApi.ParameterCategory category
);
@@ -597,7 +597,7 @@ namespace Brutal.SlangApi
);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflectionTypeLayout_GetElementStride(
+ public static partial ByteSize spReflectionTypeLayout_GetElementStride(
ReflectionTypeLayout type,
Brutal.SlangApi.ParameterCategory category
);
@@ -801,7 +801,7 @@ namespace Brutal.SlangApi
public static partial ReflectionType spReflectionVariable_GetType(ReflectionVariable var);
[LibraryImport("slang")]
- public static partial Brutal.SlangApi.ReflectionModifier spReflectionVariable_FindModifier(
+ public static partial ReflectionModifier spReflectionVariable_FindModifier(
ReflectionVariable var,
Brutal.SlangApi.ModifierID modifierID
);
@@ -851,13 +851,13 @@ namespace Brutal.SlangApi
);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflectionVariableLayout_GetOffset(
+ public static partial ByteSize spReflectionVariableLayout_GetOffset(
ReflectionVariableLayout var,
Brutal.SlangApi.ParameterCategory category
);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflectionVariableLayout_GetSpace(
+ public static partial ByteSize spReflectionVariableLayout_GetSpace(
ReflectionVariableLayout var,
Brutal.SlangApi.ParameterCategory category
);
@@ -875,7 +875,7 @@ namespace Brutal.SlangApi
public static partial string spReflectionVariableLayout_GetSemanticName(ReflectionVariableLayout var);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflectionVariableLayout_GetSemanticIndex(ReflectionVariableLayout var);
+ public static partial ByteSize spReflectionVariableLayout_GetSemanticIndex(ReflectionVariableLayout var);
[LibraryImport("slang")]
public static partial ReflectionDecl spReflectionFunction_asDecl(ReflectionFunction func);
@@ -888,7 +888,7 @@ namespace Brutal.SlangApi
public static partial string spReflectionFunction_GetName(ReflectionFunction func);
[LibraryImport("slang")]
- public static partial Brutal.SlangApi.ReflectionModifier spReflectionFunction_FindModifier(
+ public static partial ReflectionModifier spReflectionFunction_FindModifier(
ReflectionFunction var,
Brutal.SlangApi.ModifierID modifierID
);
@@ -981,7 +981,7 @@ namespace Brutal.SlangApi
public static partial ReflectionDecl spReflectionDecl_getParent(ReflectionDecl decl);
[LibraryImport("slang")]
- public static partial Brutal.SlangApi.ReflectionModifier spReflectionDecl_findModifier(
+ public static partial ReflectionModifier spReflectionDecl_findModifier(
ReflectionDecl decl,
Brutal.SlangApi.ModifierID modifierID
);
@@ -1120,7 +1120,7 @@ namespace Brutal.SlangApi
public static partial void spReflectionEntryPoint_getComputeThreadGroupSize(
ReflectionEntryPoint entryPoint,
UInt axisCount,
- out UInt outSizeAlongAxis
+ UInt* outSizeAlongAxis
);
[LibraryImport("slang")]
@@ -1251,7 +1251,7 @@ namespace Brutal.SlangApi
public static partial UInt spReflection_getGlobalConstantBufferBinding(Reflection reflection);
[LibraryImport("slang")]
- public static partial ByteSize64 spReflection_getGlobalConstantBufferSize(Reflection reflection);
+ public static partial ByteSize spReflection_getGlobalConstantBufferSize(Reflection reflection);
[LibraryImport("slang")]
public static partial ReflectionType spReflection_specializeType(
@@ -1290,11 +1290,11 @@ namespace Brutal.SlangApi
public static partial string spReflection_getHashedString(
Reflection reflection,
UInt index,
- out ByteSize64 outCount
+ out ByteSize outCount
);
[LibraryImport("slang")]
- public static partial UInt32 spComputeStringHash(RefString8 chars, ByteSize64 count);
+ public static partial UInt32 spComputeStringHash(RefString8 chars, ByteSize count);
[LibraryImport("slang")]
public static partial ReflectionTypeLayout spReflection_getGlobalParamsTypeLayout(Reflection reflection);
@@ -1312,9 +1312,6 @@ namespace Brutal.SlangApi
[LibraryImport("slang")]
public static partial Int spReflection_getBindlessSpaceIndex(Reflection reflection);
- [LibraryImport("slang")]
- public static partial nint spReflection_GetSession(Reflection reflection);
-
[LibraryImport("slang")]
public static partial Result spCompileRequest_getProgram(CompileRequest request, out nint outProgram);
@@ -1342,7 +1339,7 @@ namespace Brutal.SlangApi
public static partial Result spCompileRequest_getSession(CompileRequest request, out nint outSession);
[LibraryImport("slang")]
- public static partial nint slang_createBlob(void* data, ByteSize64 size);
+ public static partial nint slang_createBlob(void* data, ByteSize size);
[LibraryImport("slang")]
public static partial nint slang_loadModuleFromSource(
@@ -1350,7 +1347,7 @@ namespace Brutal.SlangApi
RefString8 moduleName,
RefString8 path,
RefString8 source,
- ByteSize64 sourceSize,
+ ByteSize sourceSize,
out nint outDiagnostics
);
@@ -1360,7 +1357,7 @@ namespace Brutal.SlangApi
RefString8 moduleName,
RefString8 path,
void* source,
- ByteSize64 sourceSize,
+ ByteSize sourceSize,
out nint outDiagnostics
);
@@ -1368,7 +1365,7 @@ namespace Brutal.SlangApi
public static partial Result slang_loadModuleInfoFromIRBlob(
nint session,
void* source,
- ByteSize64 sourceSize,
+ ByteSize sourceSize,
ref Int outModuleVersion,
ref byte* outModuleCompilerVersion,
ref byte* outModuleName
@@ -1389,9 +1386,6 @@ namespace Brutal.SlangApi
out nint outGlobalSession
);
- [LibraryImport("slang")]
- public static partial nint slang_getEmbeddedCoreModule();
-
[LibraryImport("slang")]
public static partial void slang_shutdown();
@@ -1502,7 +1496,7 @@ namespace Brutal.SlangApi
internal static unsafe Result ExtractRepro(
nint session,
void* reproData,
- ByteSize64 reproDataSize,
+ ByteSize reproDataSize,
nint fileSystem
)
{
@@ -1512,7 +1506,7 @@ namespace Brutal.SlangApi
internal static unsafe Result LoadReproAsFileSystem(
nint session,
void* reproData,
- ByteSize64 reproDataSize,
+ ByteSize reproDataSize,
nint replaceFileSystem,
out nint outFileSystem
)
@@ -1567,12 +1561,12 @@ namespace Brutal.SlangApi
return PInvoke.spReflectionType_GetFieldByIndex(type, index);
}
- public static ByteSize64 ReflectionTypeGetElementCount(ReflectionType type)
+ public static ByteSize ReflectionTypeGetElementCount(ReflectionType type)
{
return PInvoke.spReflectionType_GetElementCount(type);
}
- public static ByteSize64 ReflectionTypeGetSpecializedElementCount(ReflectionType type, Reflection reflection)
+ public static ByteSize ReflectionTypeGetSpecializedElementCount(ReflectionType type, Reflection reflection)
{
return PInvoke.spReflectionType_GetSpecializedElementCount(type, reflection);
}
@@ -1637,7 +1631,7 @@ namespace Brutal.SlangApi
return PInvoke.spReflectionTypeLayout_getKind(type);
}
- public static ByteSize64 ReflectionTypeLayoutGetSize(
+ public static ByteSize ReflectionTypeLayoutGetSize(
ReflectionTypeLayout type,
Brutal.SlangApi.ParameterCategory category
)
@@ -1645,7 +1639,7 @@ namespace Brutal.SlangApi
return PInvoke.spReflectionTypeLayout_GetSize(type, category);
}
- public static ByteSize64 ReflectionTypeLayoutGetStride(
+ public static ByteSize ReflectionTypeLayoutGetStride(
ReflectionTypeLayout type,
Brutal.SlangApi.ParameterCategory category
)
@@ -1688,7 +1682,7 @@ namespace Brutal.SlangApi
return PInvoke.spReflectionTypeLayout_GetExplicitCounter(typeLayout);
}
- public static ByteSize64 ReflectionTypeLayoutGetElementStride(
+ public static ByteSize ReflectionTypeLayoutGetElementStride(
ReflectionTypeLayout type,
Brutal.SlangApi.ParameterCategory category
)
@@ -1954,7 +1948,7 @@ namespace Brutal.SlangApi
return PInvoke.spReflectionVariable_GetType(var);
}
- public static Brutal.SlangApi.ReflectionModifier ReflectionVariableFindModifier(
+ public static ReflectionModifier ReflectionVariableFindModifier(
ReflectionVariable var,
Brutal.SlangApi.ModifierID modifierID
)
@@ -2022,7 +2016,7 @@ namespace Brutal.SlangApi
return PInvoke.spReflectionFunction_GetName(func);
}
- public static Brutal.SlangApi.ReflectionModifier ReflectionFunctionFindModifier(
+ public static ReflectionModifier ReflectionFunctionFindModifier(
ReflectionFunction var,
Brutal.SlangApi.ModifierID modifierID
)
@@ -2149,7 +2143,7 @@ namespace Brutal.SlangApi
return PInvoke.spReflectionDecl_getParent(decl);
}
- public static Brutal.SlangApi.ReflectionModifier ReflectionDeclFindModifier(
+ public static ReflectionModifier ReflectionDeclFindModifier(
ReflectionDecl decl,
Brutal.SlangApi.ModifierID modifierID
)
@@ -2263,12 +2257,12 @@ namespace Brutal.SlangApi
return PInvoke.spReflectionTypeParameter_GetConstraintByIndex(typeParam, index);
}
- public static UInt32 ComputeStringHash(RefString8 chars, ByteSize64 count)
+ public static UInt32 ComputeStringHash(RefString8 chars, ByteSize count)
{
return PInvoke.spComputeStringHash(chars, count);
}
- internal static unsafe nint CreateBlob(void* data, ByteSize64 size)
+ internal static unsafe nint CreateBlob(void* data, ByteSize size)
{
return PInvoke.slang_createBlob(data, size);
}
@@ -2278,7 +2272,7 @@ namespace Brutal.SlangApi
RefString8 moduleName,
RefString8 path,
RefString8 source,
- ByteSize64 sourceSize,
+ ByteSize sourceSize,
out nint outDiagnostics
)
{
@@ -2297,7 +2291,7 @@ namespace Brutal.SlangApi
RefString8 moduleName,
RefString8 path,
void* source,
- ByteSize64 sourceSize,
+ ByteSize sourceSize,
out nint outDiagnostics
)
{
@@ -2314,7 +2308,7 @@ namespace Brutal.SlangApi
internal static unsafe Result LoadModuleInfoFromIRBlob(
nint session,
void* source,
- ByteSize64 sourceSize,
+ ByteSize sourceSize,
ref Int outModuleVersion,
ref byte* outModuleCompilerVersion,
ref byte* outModuleName
@@ -2348,11 +2342,6 @@ namespace Brutal.SlangApi
return PInvoke.slang_createGlobalSessionWithoutCoreModule(apiVersion, out outGlobalSession);
}
- internal static nint GetEmbeddedCoreModule()
- {
- return PInvoke.slang_getEmbeddedCoreModule();
- }
-
public static void Shutdown()
{
PInvoke.slang_shutdown();
diff --git a/Brutal.Slang/Generated/Structs.gen.cs b/Brutal.Slang/Generated/Structs.gen.cs
index 574d021..1352702 100644
--- a/Brutal.Slang/Generated/Structs.gen.cs
+++ b/Brutal.Slang/Generated/Structs.gen.cs
@@ -197,7 +197,7 @@ namespace Brutal.SlangApi
Slang.PInvoke.spAddTranslationUnitSourceString(this, translationUnitIndex, path, source);
}
- public unsafe Result AddLibraryReference(RefString8 basePath, void* libData, ByteSize64 libDataSize)
+ public unsafe Result AddLibraryReference(RefString8 basePath, void* libData, ByteSize libDataSize)
{
return Slang.PInvoke.spAddLibraryReference(this, basePath, libData, libDataSize);
}
@@ -305,7 +305,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spGetEntryPointSource(this, entryPointIndex);
}
- public unsafe void* GetEntryPointCode(int entryPointIndex, out ByteSize64 outSize)
+ public unsafe void* GetEntryPointCode(int entryPointIndex, out ByteSize outSize)
{
return Slang.PInvoke.spGetEntryPointCode(this, entryPointIndex, out outSize);
}
@@ -330,7 +330,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spGetTargetHostCallable(this, targetIndex, out outSharedLibrary);
}
- public unsafe void* GetCompileRequestCode(out ByteSize64 outSize)
+ public unsafe void* GetCompileRequestCode(out ByteSize outSize)
{
return Slang.PInvoke.spGetCompileRequestCode(this, out outSize);
}
@@ -340,7 +340,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spGetContainerCode(this, out outBlob);
}
- internal unsafe Result LoadRepro(nint fileSystem, void* data, ByteSize64 size)
+ internal unsafe Result LoadRepro(nint fileSystem, void* data, ByteSize size)
{
return Slang.PInvoke.spLoadRepro(this, fileSystem, data, size);
}
@@ -494,7 +494,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionDecl_getParent(this);
}
- public Brutal.SlangApi.ReflectionModifier FindModifier(Brutal.SlangApi.ModifierID modifierID)
+ public ReflectionModifier FindModifier(Brutal.SlangApi.ModifierID modifierID)
{
return Slang.PInvoke.spReflectionDecl_findModifier(this, modifierID);
}
@@ -513,12 +513,12 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionTypeLayout_getKind(this);
}
- public ByteSize64 GetSize(Brutal.SlangApi.ParameterCategory category)
+ public ByteSize GetSize(Brutal.SlangApi.ParameterCategory category)
{
return Slang.PInvoke.spReflectionTypeLayout_GetSize(this, category);
}
- public ByteSize64 GetStride(Brutal.SlangApi.ParameterCategory category)
+ public ByteSize GetStride(Brutal.SlangApi.ParameterCategory category)
{
return Slang.PInvoke.spReflectionTypeLayout_GetStride(this, category);
}
@@ -548,7 +548,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionTypeLayout_GetExplicitCounter(this);
}
- public ByteSize64 GetElementStride(Brutal.SlangApi.ParameterCategory category)
+ public ByteSize GetElementStride(Brutal.SlangApi.ParameterCategory category)
{
return Slang.PInvoke.spReflectionTypeLayout_GetElementStride(this, category);
}
@@ -817,12 +817,12 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionType_GetFieldByIndex(this, index);
}
- public ByteSize64 GetElementCount()
+ public ByteSize GetElementCount()
{
return Slang.PInvoke.spReflectionType_GetElementCount(this);
}
- public ByteSize64 GetSpecializedElementCount(Reflection reflection)
+ public ByteSize GetSpecializedElementCount(Reflection reflection)
{
return Slang.PInvoke.spReflectionType_GetSpecializedElementCount(this, reflection);
}
@@ -901,12 +901,12 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionVariableLayout_GetTypeLayout(this);
}
- public ByteSize64 GetOffset(Brutal.SlangApi.ParameterCategory category)
+ public ByteSize GetOffset(Brutal.SlangApi.ParameterCategory category)
{
return Slang.PInvoke.spReflectionVariableLayout_GetOffset(this, category);
}
- public ByteSize64 GetSpace(Brutal.SlangApi.ParameterCategory category)
+ public ByteSize GetSpace(Brutal.SlangApi.ParameterCategory category)
{
return Slang.PInvoke.spReflectionVariableLayout_GetSpace(this, category);
}
@@ -921,7 +921,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionVariableLayout_GetSemanticName(this);
}
- public ByteSize64 GetSemanticIndex()
+ public ByteSize GetSemanticIndex()
{
return Slang.PInvoke.spReflectionVariableLayout_GetSemanticIndex(this);
}
@@ -950,7 +950,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionVariable_GetType(this);
}
- public Brutal.SlangApi.ReflectionModifier FindModifier(Brutal.SlangApi.ModifierID modifierID)
+ public ReflectionModifier FindModifier(Brutal.SlangApi.ModifierID modifierID)
{
return Slang.PInvoke.spReflectionVariable_FindModifier(this, modifierID);
}
@@ -1009,7 +1009,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionFunction_GetName(this);
}
- public Brutal.SlangApi.ReflectionModifier FindModifier(Brutal.SlangApi.ModifierID modifierID)
+ public ReflectionModifier FindModifier(Brutal.SlangApi.ModifierID modifierID)
{
return Slang.PInvoke.spReflectionFunction_FindModifier(this, modifierID);
}
@@ -1149,9 +1149,6 @@ namespace Brutal.SlangApi
}
};
- [InteropHandle]
- public readonly unsafe partial struct Attribute { };
-
[InteropHandle]
public readonly unsafe partial struct ShaderReflection { };
@@ -1213,7 +1210,7 @@ namespace Brutal.SlangApi
public unsafe partial struct SessionDesc
{
/// The size of this structure, in bytes.
- public ByteSize64 StructureSize;
+ public ByteSize StructureSize;
/// Code generation targets to include in the session.
public Brutal.SlangApi.TargetDesc* Targets;
@@ -1272,7 +1269,7 @@ namespace Brutal.SlangApi
public unsafe partial struct TargetDesc
{
/// The size of this structure, in bytes.
- public ByteSize64 StructureSize;
+ public ByteSize StructureSize;
/// The target format to generate code for (e.g., SPIR-V, DXIL, etc.)
public Brutal.SlangApi.CompileTarget Format;
@@ -1336,7 +1333,7 @@ namespace Brutal.SlangApi
public unsafe partial struct ByteCodeRunnerDesc
{
/// The size of this structure, in bytes.
- public ByteSize64 StructSize;
+ public ByteSize StructSize;
};
/// A "Universally Unique Identifier" (UUID)
@@ -1355,8 +1352,6 @@ namespace Brutal.SlangApi
public fixed byte Data4[8];
};
- public unsafe partial struct Guid { };
-
/// Can be requested from ISlangCastable cast to indicate the contained chars are null
/// terminated.
public unsafe partial struct TerminatedChars
@@ -1372,8 +1367,6 @@ namespace Brutal.SlangApi
[InteropHandle]
public readonly unsafe partial struct EntryPointLayout { };
- public unsafe partial struct ReflectionModifier { };
-
[InteropHandle]
public readonly unsafe partial struct ReflectionUserAttribute
{
@@ -1402,7 +1395,7 @@ namespace Brutal.SlangApi
return Slang.PInvoke.spReflectionUserAttribute_GetArgumentValueFloat(this, index, rs);
}
- public string GetArgumentValueString(uint index, out ByteSize64 outSize)
+ public string GetArgumentValueString(uint index, out ByteSize outSize)
{
return Slang.PInvoke.spReflectionUserAttribute_GetArgumentValueString(this, index, out outSize);
}
diff --git a/Brutal.Slang/ICompileRequestExtensions.cs b/Brutal.Slang/ICompileRequestExtensions.cs
index b2b4441..ef25528 100644
--- a/Brutal.Slang/ICompileRequestExtensions.cs
+++ b/Brutal.Slang/ICompileRequestExtensions.cs
@@ -122,17 +122,11 @@ public static unsafe class ICompileRequestExtensions
///
/// Returns the currently installed for
/// , or null if the channel is unset. Slang's
- /// getter does not AddRef the returned pointer, so this wrapper performs the
- /// AddRef itself before handing the pointer to .
+ /// getter lends the pointer without an AddRef; the returned proxy takes its own
+ /// reference, so release it with .
///
- public static ISlangWriter? GetWriter(this ICompileRequest self, WriterChannel channel)
- {
- var raw = self.GetWriter(channel);
- if (raw == 0)
- return null;
- Marshal.AddRef(raw);
- return (ISlangWriter)Slang.ComWrappers.GetOrCreateObjectForComInstance(raw, CreateObjectFlags.None);
- }
+ public static ISlangWriter? GetWriter(this ICompileRequest self, WriterChannel channel) =>
+ Slang.WrapBorrowedComInstance(self.GetWriter(channel));
///
/// Adds a translation-unit source whose contents are provided as an
diff --git a/Brutal.Slang/ISessionExtensions.cs b/Brutal.Slang/ISessionExtensions.cs
index 5f660b2..62bf70e 100644
--- a/Brutal.Slang/ISessionExtensions.cs
+++ b/Brutal.Slang/ISessionExtensions.cs
@@ -139,6 +139,24 @@ public static unsafe partial class ISessionExtensions
return self.LoadModuleFromIRBlob(nameP, pathP, source, out outDiagnostics);
}
+ ///
+ /// Writes the RTTI bytes Slang uses to identify 's conformance to
+ /// into , which must hold at
+ /// least 16 bytes.
+ ///
+ /// Thrown if slang reports a failing .
+ public static void GetDynamicObjectRTTIBytes(
+ this ISession self,
+ TypeReflection type,
+ TypeReflection interfaceType,
+ Span buffer
+ )
+ {
+ fixed (byte* p = buffer)
+ self.GetDynamicObjectRTTIBytes(type, interfaceType, (uint*)p, checked((uint)buffer.Length))
+ .ThrowIfFailure();
+ }
+
private const int ShortStringStackBytes = 256;
private const int LongStringStackBytes = 8192;
diff --git a/Brutal.Slang/ISlangBlobExtensions.cs b/Brutal.Slang/ISlangBlobExtensions.cs
index 362812d..f0bdf4a 100644
--- a/Brutal.Slang/ISlangBlobExtensions.cs
+++ b/Brutal.Slang/ISlangBlobExtensions.cs
@@ -9,9 +9,9 @@ public static unsafe partial class ISlangBlobExtensions
{
///
/// Returns the blob's contents as a . The span is
- /// valid for the lifetime of the underlying blob. Copy if you need the bytes
- /// to outlive it.
+ /// valid until the blob is passed to . Copy if you need
+ /// the bytes to outlive it.
///
public static ReadOnlySpan AsSpan(this ISlangBlob self) =>
- new(self.GetBufferPointer(), checked((int)self.GetBufferSize()));
+ new(self.GetBufferPointer(), checked((int)self.GetBufferSize().Value));
}
diff --git a/Brutal.Slang/ScalarMarshallers.cs b/Brutal.Slang/ScalarMarshallers.cs
new file mode 100644
index 0000000..ce2f628
--- /dev/null
+++ b/Brutal.Slang/ScalarMarshallers.cs
@@ -0,0 +1,34 @@
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices.Marshalling;
+using Brutal;
+
+namespace Brutal.SlangApi;
+
+[CustomMarshaller(
+ typeof(CustomMarshallerAttribute.GenericPlaceholder),
+ MarshalMode.Default,
+ typeof(SlangHandleMarshaller<>)
+)]
+internal static class SlangHandleMarshaller
+ where T : unmanaged
+{
+ public static nint ConvertToUnmanaged(T managed) => Unsafe.BitCast(managed);
+
+ public static T ConvertToManaged(nint unmanaged) => Unsafe.BitCast(unmanaged);
+}
+
+[CustomMarshaller(typeof(ByteSize), MarshalMode.Default, typeof(SlangSizeMarshaller))]
+internal static class SlangSizeMarshaller
+{
+ public static nuint ConvertToUnmanaged(ByteSize managed) => managed.Value;
+
+ public static ByteSize ConvertToManaged(nuint unmanaged) => (ByteSize)unmanaged;
+}
+
+[CustomMarshaller(typeof(Bool8), MarshalMode.Default, typeof(SlangBoolMarshaller))]
+internal static class SlangBoolMarshaller
+{
+ public static byte ConvertToUnmanaged(Bool8 managed) => Unsafe.BitCast(managed);
+
+ public static Bool8 ConvertToManaged(byte unmanaged) => Unsafe.BitCast(unmanaged);
+}
diff --git a/Brutal.Slang/Slang.cs b/Brutal.Slang/Slang.cs
index f220cc2..bd0f98d 100644
--- a/Brutal.Slang/Slang.cs
+++ b/Brutal.Slang/Slang.cs
@@ -6,25 +6,25 @@ namespace Brutal.SlangApi;
/// The Slang class provides access to the slang library for compiling shaders.
///
///
-/// Slang COM proxies (returned by ,
-/// , etc.) are released by the ComWrappers
-/// finalizer when GC reclaims the managed proxy. There is no deterministic
-/// Dispose. Callers don't need to do anything special. COM proxies in this
-/// binding represent shared-ownership references; the underlying slang object stays
-/// alive as long as anything (slang internals, other proxies, or the global session)
-/// holds a reference, regardless of when any single proxy is collected.
+/// Release returned COM proxies with on the thread using
+/// them, in reverse dependency order: code/diagnostics and components, modules,
+/// session, then global session. Keep parents alive until their children have
+/// been released. The garbage collector never releases a proxy, so one that is
+/// not passed to keeps its native object alive.
+/// Each returned proxy owns an independent reference; releasing one proxy does
+/// not invalidate another proxy for the same native object.
///
public static partial class Slang
{
///
/// instance used to bridge raw COM pointers obtained from
/// slang_* entry points (e.g. )
- /// into managed [GeneratedComInterface] proxies. The default
- /// implementation discovers proxy classes
+ /// into managed [GeneratedComInterface] proxies.
+ /// keeps ' discovery of the proxy classes
/// emitted by the source generator from the type's IID, so no per-interface
/// registration is needed.
///
- internal static readonly StrategyBasedComWrappers ComWrappers = new();
+ internal static readonly StrategyBasedComWrappers ComWrappers = new SlangComWrappers();
public static partial class PInvoke
{
@@ -34,6 +34,15 @@ public static partial class Slang
var nativeDll = NativeLibrary.Load("slang", assembly, DllImportSearchPath.AssemblyDirectory);
+ // Slang loads slang-glslang and slang-glsl-module by bare name at run time. Windows
+ // searches only the application and system directories for them, which misses a
+ // RID-less NuGet build's runtimes/win-x64/native folder, so load them from wherever
+ // slang came from; Slang's own LoadLibrary then finds the loaded modules. macOS and
+ // Linux resolve them through slang's rpath.
+ if (OperatingSystem.IsWindows())
+ foreach (var companion in (ReadOnlySpan)["slang-glslang", "slang-glsl-module"])
+ NativeLibrary.TryLoad(companion, assembly, DllImportSearchPath.AssemblyDirectory, out _);
+
NativeLibrary.SetDllImportResolver(
assembly,
(libraryName, _, _) => libraryName == "slang" ? nativeDll : IntPtr.Zero
@@ -93,10 +102,10 @@ public static partial class Slang
{
nint raw;
fixed (byte* p = data)
- raw = PInvoke.slang_createBlob(p, (Brutal.ByteSize64)data.Length);
+ raw = PInvoke.slang_createBlob(p, Brutal.ByteSize.Of(data));
if (raw == 0)
throw new SlangException((Result)(-1), "slang_createBlob returned a null pointer.");
- return (ISlangBlob)ComWrappers.GetOrCreateObjectForComInstance(raw, CreateObjectFlags.None);
+ return WrapComInstance((Result)0, raw)!;
}
///
@@ -151,9 +160,54 @@ public static partial class Slang
internal static T? WrapComInstance(Result hr, nint comInstance)
where T : class
{
- if (hr.IsFailure || comInstance == 0)
+ if (comInstance == 0)
return null;
- return (T)ComWrappers.GetOrCreateObjectForComInstance(comInstance, CreateObjectFlags.None);
+ try
+ {
+ return hr.IsFailure ? null : WrapBorrowedComInstance(comInstance);
+ }
+ finally
+ {
+ // The RCW retains its own reference. Consume the reference transferred by
+ // the native export, including when interface conversion throws.
+ Marshal.Release(comInstance);
+ }
+ }
+
+ internal static T? WrapBorrowedComInstance(nint pointer)
+ where T : class
+ {
+ if (pointer == 0)
+ return null;
+ var wrapper = ComWrappers.GetOrCreateObjectForComInstance(pointer, CreateObjectFlags.UniqueInstance);
+ // Only Release frees a proxy's native references. Its finalizer would release them
+ // on the finalizer thread, in no order relative to the proxy's session.
+ GC.SuppressFinalize(wrapper);
+ try
+ {
+ return (T)wrapper;
+ }
+ catch
+ {
+ ((ComObject)wrapper).FinalRelease();
+ throw;
+ }
+ }
+
+ ///
+ /// Releases a proxy returned by this binding immediately. This is the only way a
+ /// proxy's native reference is released: the garbage collector never does it.
+ /// Null and repeated releases are harmless. Do not use the proxy afterwards. Release children
+ /// before their owning session and release sessions before their global session.
+ /// Do not race release against another call using the same proxy.
+ ///
+ public static void Release(object? instance)
+ {
+ if (instance is null)
+ return;
+ if (instance is not ComObject wrapper)
+ throw new ArgumentException("Expected a Slang COM proxy.", nameof(instance));
+ wrapper.FinalRelease();
}
///
@@ -163,6 +217,31 @@ public static partial class Slang
/// count. Call on it when finished, or pass it to
/// APIs that take ownership.
///
- public static nint GetComInstance(object comObject) =>
- ComWrappers.GetOrCreateComInterfaceForObject(comObject, CreateComInterfaceFlags.None);
+ public static nint GetComInstance(object comObject)
+ {
+ ArgumentNullException.ThrowIfNull(comObject);
+ if (comObject is ComObject)
+ return GetComInstance((ISlangUnknown)comObject);
+ return System.Runtime.InteropServices.ComWrappers.TryGetComInstance(comObject, out var native)
+ ? native
+ : ComWrappers.GetOrCreateComInterfaceForObject(comObject, CreateComInterfaceFlags.None);
+ }
+
+ ///
+ /// Gets an owned pointer to the requested native interface, including its correct
+ /// subobject address. Release the returned reference after the native call.
+ ///
+ public static unsafe nint GetComInstance(T comObject)
+ where T : class
+ {
+ if (comObject is ComObject wrapper)
+ {
+ var table = ((IUnmanagedVirtualMethodTableProvider)wrapper).GetVirtualMethodTableInfoForKey(typeof(T));
+ var pointer = (nint)table.ThisPointer;
+ Marshal.AddRef(pointer);
+ GC.KeepAlive(wrapper);
+ return pointer;
+ }
+ return (nint)ComInterfaceMarshaller.ConvertToUnmanaged(comObject);
+ }
}
diff --git a/Brutal.Slang/SlangComWrappers.cs b/Brutal.Slang/SlangComWrappers.cs
new file mode 100644
index 0000000..e5dd05c
--- /dev/null
+++ b/Brutal.Slang/SlangComWrappers.cs
@@ -0,0 +1,40 @@
+using System.Runtime.InteropServices.Marshalling;
+
+namespace Brutal.SlangApi;
+
+// Some Slang 2026.7 objects implement a public interface but answer QueryInterface
+// only for a native interface derived from it, whose vtable therefore starts with the
+// public one. Preserve the public IIDs and prefer them; only retry E_NOINTERFACE
+// against the derived interface. See upstream
+// source/compiler-core/slang-artifact-associated{,-impl}.{h,cpp} (IMetadata) and
+// source/compiler-core/slang-artifact{,-impl}.{h,cpp} (ICompileResult).
+internal sealed class SlangComWrappers : StrategyBasedComWrappers
+{
+ protected override IIUnknownStrategy GetOrCreateIUnknownStrategy() => DerivedInterfaceQueryStrategy.Instance;
+
+ private sealed unsafe class DerivedInterfaceQueryStrategy : IIUnknownStrategy
+ {
+ internal static readonly DerivedInterfaceQueryStrategy Instance = new();
+ private const int NoInterface = unchecked((int)0x80004002);
+
+ private static readonly Dictionary DerivedIds = new()
+ {
+ // IArtifactPostEmitMetadata
+ [typeof(IMetadata).GUID] = new("5d03bce9-afb1-4fc8-a46f-3ce07b061b1b"),
+ // IArtifact
+ [typeof(ICompileResult).GUID] = new("f90acdb0-9a4a-414e-8545-8b26c92d9442"),
+ };
+
+ public void* CreateInstancePointer(void* unknown) => DefaultIUnknownStrategy.CreateInstancePointer(unknown);
+
+ public int QueryInterface(void* instancePtr, in System.Guid iid, out void* ppObj)
+ {
+ var result = DefaultIUnknownStrategy.QueryInterface(instancePtr, in iid, out ppObj);
+ if (result == NoInterface && DerivedIds.TryGetValue(iid, out var derived))
+ return DefaultIUnknownStrategy.QueryInterface(instancePtr, in derived, out ppObj);
+ return result;
+ }
+
+ public int Release(void* instancePtr) => DefaultIUnknownStrategy.Release(instancePtr);
+ }
+}
diff --git a/Brutal.Slang/SlangInterfaceMarshaller.cs b/Brutal.Slang/SlangInterfaceMarshaller.cs
new file mode 100644
index 0000000..15fec5c
--- /dev/null
+++ b/Brutal.Slang/SlangInterfaceMarshaller.cs
@@ -0,0 +1,23 @@
+using System.Runtime.InteropServices.Marshalling;
+
+namespace Brutal.SlangApi;
+
+[CustomMarshaller(
+ typeof(CustomMarshallerAttribute.GenericPlaceholder),
+ MarshalMode.Default,
+ typeof(SlangInterfaceMarshaller<>)
+)]
+internal static unsafe class SlangInterfaceMarshaller
+ where T : class
+{
+ public static T? ConvertToManaged(void* unmanaged) => Slang.WrapBorrowedComInstance((nint)unmanaged);
+
+ public static void* ConvertToUnmanaged(T? managed) =>
+ managed is null ? null : (void*)Slang.GetComInstance(managed);
+
+ public static void Free(void* unmanaged)
+ {
+ if (unmanaged != null)
+ Marshal.Release((nint)unmanaged);
+ }
+}
diff --git a/Brutal.Vulkan.Abstractions/LICENSES/BRUTAL-VULKAN-ABSTRACTIONS-THIRD-PARTY-NOTICES.txt b/Brutal.Vulkan.Abstractions/LICENSES/BRUTAL-VULKAN-ABSTRACTIONS-THIRD-PARTY-NOTICES.txt
index 7f19500..c800d2b 100644
--- a/Brutal.Vulkan.Abstractions/LICENSES/BRUTAL-VULKAN-ABSTRACTIONS-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Vulkan.Abstractions/LICENSES/BRUTAL-VULKAN-ABSTRACTIONS-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Vulkan.Abstractions
+Ahwoo.BRUTAL.Vulkan.Abstractions
Brutal.Vulkan.Abstractions builds on the Brutal.Vulkan bindings, which are generated from
the Khronos Vulkan API registry. This package contains no native library and no generated
diff --git a/Brutal.Vulkan.Vma/LICENSES/BRUTAL-VULKAN-VMA-THIRD-PARTY-NOTICES.txt b/Brutal.Vulkan.Vma/LICENSES/BRUTAL-VULKAN-VMA-THIRD-PARTY-NOTICES.txt
index 80198d6..dbdde53 100644
--- a/Brutal.Vulkan.Vma/LICENSES/BRUTAL-VULKAN-VMA-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Vulkan.Vma/LICENSES/BRUTAL-VULKAN-VMA-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Vulkan.Vma
+Ahwoo.BRUTAL.Vulkan.Vma
Brutal.Vulkan.Vma redistributes one third-party component, the Vulkan Memory Allocator. It
reaches this package by two routes: as native libraries, and as descriptive text taken from
diff --git a/Brutal.Vulkan/Generated/Constants/VK.gen.cs b/Brutal.Vulkan/Generated/Constants/VK.gen.cs
index 0667bcb..9cf8ee8 100644
--- a/Brutal.Vulkan/Generated/Constants/VK.gen.cs
+++ b/Brutal.Vulkan/Generated/Constants/VK.gen.cs
@@ -1077,5 +1077,156 @@ namespace Brutal.VulkanApi
public const int STD_VULKAN_VIDEO_CODEC_AV1_ENCODE_SPEC_VERSION =
STD_VULKAN_VIDEO_CODEC_AV1_ENCODE_API_VERSION_1_0_0;
public const string STD_VULKAN_VIDEO_CODEC_AV1_ENCODE_EXTENSION_NAME = "VK_STD_vulkan_video_codec_av1_encode";
+
+ ///
+ /// VK_API_VERSION_1_0 - Return API version number for Vulkan 1.0
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_1_0 returns the API version number for Vulkan 1.0.0.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// // Vulkan 1.0 version number
+ /// #define VK_API_VERSION_1_0 VK_MAKE_API_VERSION(0, 1, 0, 0)// Patch version should always be set to 0
+ ///
+ ///
+ public const int API_VERSION_1_0 = unchecked(
+ (int)((((uint)(0)) << 29) | (((uint)(1)) << 22) | (((uint)(0)) << 12) | ((uint)(0)))
+ );
+
+ ///
+ /// VK_API_VERSION_1_1 - Return API version number for Vulkan 1.1
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_1_1 returns the API version number for Vulkan 1.1.0.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_1
+ /// // Vulkan 1.1 version number
+ /// #define VK_API_VERSION_1_1 VK_MAKE_API_VERSION(0, 1, 1, 0)// Patch version should always be set to 0
+ ///
+ ///
+ public const int API_VERSION_1_1 = unchecked(
+ (int)((((uint)(0)) << 29) | (((uint)(1)) << 22) | (((uint)(1)) << 12) | ((uint)(0)))
+ );
+
+ ///
+ /// VK_API_VERSION_1_2 - Return API version number for Vulkan 1.2
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_1_2 returns the API version number for Vulkan 1.2.0.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_2
+ /// // Vulkan 1.2 version number
+ /// #define VK_API_VERSION_1_2 VK_MAKE_API_VERSION(0, 1, 2, 0)// Patch version should always be set to 0
+ ///
+ ///
+ public const int API_VERSION_1_2 = unchecked(
+ (int)((((uint)(0)) << 29) | (((uint)(1)) << 22) | (((uint)(2)) << 12) | ((uint)(0)))
+ );
+
+ ///
+ /// VK_API_VERSION_1_3 - Return API version number for Vulkan 1.3
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_1_3 returns the API version number for Vulkan 1.3.0.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_3
+ /// // Vulkan 1.3 version number
+ /// #define VK_API_VERSION_1_3 VK_MAKE_API_VERSION(0, 1, 3, 0)// Patch version should always be set to 0
+ ///
+ ///
+ public const int API_VERSION_1_3 = unchecked(
+ (int)((((uint)(0)) << 29) | (((uint)(1)) << 22) | (((uint)(3)) << 12) | ((uint)(0)))
+ );
+
+ ///
+ /// VK_API_VERSION_1_4 - Return API version number for Vulkan 1.4
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_1_4 returns the API version number for Vulkan 1.4.0.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_4
+ /// // Vulkan 1.4 version number
+ /// #define VK_API_VERSION_1_4 VK_MAKE_API_VERSION(0, 1, 4, 0)// Patch version should always be set to 0
+ ///
+ ///
+ public const int API_VERSION_1_4 = unchecked(
+ (int)((((uint)(0)) << 29) | (((uint)(1)) << 22) | (((uint)(4)) << 12) | ((uint)(0)))
+ );
+
+ ///
+ /// VK_HEADER_VERSION - Vulkan header file version number
+ ///
+ ///
+ ///
+ /// VK_HEADER_VERSION is the version number of the `{core_header}` header.
+ /// This value is kept synchronized with the patch version of the released
+ /// Specification.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// // Version of this file
+ /// #define VK_HEADER_VERSION 357
+ ///
+ ///
+ public const int HEADER_VERSION = 357;
+
+ ///
+ /// VK_HEADER_VERSION_COMPLETE - Vulkan header file complete version number
+ ///
+ ///
+ ///
+ /// VK_HEADER_VERSION_COMPLETE is the complete version number of the
+ /// `{core_header}` header, comprising the major, minor, and patch versions.
+ /// The major/minor values are kept synchronized with the complete version of
+ /// the released Specification.
+ /// This value is intended for use by automated tools to identify exactly which
+ /// version of the header was used during their generation.
+ ///
+ ///
+ /// Applications should not use this value as their
+ /// VkApplicationInfo::apiVersion.
+ /// Instead applications should explicitly select a specific fixed major/minor
+ /// API version using, for example, one of the VK_API_VERSION_*_* values.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// // Complete version of this file
+ /// #define VK_HEADER_VERSION_COMPLETE VK_MAKE_API_VERSION(0, 1, 4, VK_HEADER_VERSION)
+ ///
+ ///
+ public const int HEADER_VERSION_COMPLETE = unchecked(
+ (int)((((uint)(0)) << 29) | (((uint)(1)) << 22) | (((uint)(4)) << 12) | ((uint)(VK.HEADER_VERSION)))
+ );
+ public const int STD_VULKAN_VIDEO_CODEC_H264_DECODE_API_VERSION_1_0_0 = unchecked(
+ (int)((((uint)(1)) << 22) | (((uint)(0)) << 12) | ((uint)(0)))
+ );
+ public const int STD_VULKAN_VIDEO_CODEC_H264_ENCODE_API_VERSION_1_0_0 = unchecked(
+ (int)((((uint)(1)) << 22) | (((uint)(0)) << 12) | ((uint)(0)))
+ );
+ public const int STD_VULKAN_VIDEO_CODEC_H265_DECODE_API_VERSION_1_0_0 = unchecked(
+ (int)((((uint)(1)) << 22) | (((uint)(0)) << 12) | ((uint)(0)))
+ );
+ public const int STD_VULKAN_VIDEO_CODEC_H265_ENCODE_API_VERSION_1_0_0 = unchecked(
+ (int)((((uint)(1)) << 22) | (((uint)(0)) << 12) | ((uint)(0)))
+ );
+ public const int STD_VULKAN_VIDEO_CODEC_VP9_DECODE_API_VERSION_1_0_0 = unchecked(
+ (int)((((uint)(1)) << 22) | (((uint)(0)) << 12) | ((uint)(0)))
+ );
+ public const int STD_VULKAN_VIDEO_CODEC_AV1_DECODE_API_VERSION_1_0_0 = unchecked(
+ (int)((((uint)(1)) << 22) | (((uint)(0)) << 12) | ((uint)(0)))
+ );
+ public const int STD_VULKAN_VIDEO_CODEC_AV1_ENCODE_API_VERSION_1_0_0 = unchecked(
+ (int)((((uint)(1)) << 22) | (((uint)(0)) << 12) | ((uint)(0)))
+ );
}
}
diff --git a/Brutal.Vulkan/Generated/Macros/Vulkan.gen.cs b/Brutal.Vulkan/Generated/Macros/Vulkan.gen.cs
new file mode 100644
index 0000000..0474937
--- /dev/null
+++ b/Brutal.Vulkan/Generated/Macros/Vulkan.gen.cs
@@ -0,0 +1,157 @@
+namespace Brutal.VulkanApi
+{
+ public static partial class Vulkan
+ {
+ ///
+ /// VK_MAKE_VERSION - Construct an API version number
+ ///
+ ///
+ ///
+ /// VK_MAKE_VERSION constructs an API version number.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_MAKE_VERSION(major, minor, patch) \
+ /// ((((uint32_t)(major)) << 22U) | (((uint32_t)(minor)) << 12U) | ((uint32_t)(patch)))
+ ///
+ ///
+ /// is the major version number.
+ /// is the minor version number.
+ /// is the patch version number.
+ public static int MakeVersion(int major, int minor, int patch) =>
+ unchecked((int)((((uint)(major)) << 22) | (((uint)(minor)) << 12) | ((uint)(patch))));
+
+ ///
+ /// VK_VERSION_MAJOR - Extract API major version number
+ ///
+ ///
+ ///
+ /// VK_VERSION_MAJOR extracts the API major version number from a packed
+ /// version number:
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_VERSION_MAJOR(version) ((uint32_t)(version) >> 22U)
+ ///
+ ///
+ public static int VersionMajor(int version) => unchecked((int)((uint)(version) >> 22));
+
+ ///
+ /// VK_VERSION_MINOR - Extract API minor version number
+ ///
+ ///
+ ///
+ /// VK_VERSION_MINOR extracts the API minor version number from a packed
+ /// version number:
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_VERSION_MINOR(version) (((uint32_t)(version) >> 12U) & 0x3FFU)
+ ///
+ ///
+ public static int VersionMinor(int version) => unchecked((int)(((uint)(version) >> 12) & 0x3FF));
+
+ ///
+ /// VK_VERSION_PATCH - Extract API patch version number
+ ///
+ ///
+ ///
+ /// VK_VERSION_PATCH extracts the API patch version number from a packed
+ /// version number:
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_VERSION_PATCH(version) ((uint32_t)(version) & 0xFFFU)
+ ///
+ ///
+ public static int VersionPatch(int version) => unchecked((int)((uint)(version) & 0xFFF));
+
+ ///
+ /// VK_MAKE_API_VERSION - Construct an API version number
+ ///
+ ///
+ ///
+ /// VK_MAKE_API_VERSION constructs an API version number.
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_MAKE_API_VERSION(variant, major, minor, patch) \
+ /// ((((uint32_t)(variant)) << 29U) | (((uint32_t)(major)) << 22U) | (((uint32_t)(minor)) << 12U) | ((uint32_t)(patch)))
+ ///
+ ///
+ /// is the variant number.
+ /// is the major version number.
+ /// is the minor version number.
+ /// is the patch version number.
+ public static int MakeApiVersion(int variant, int major, int minor, int patch) =>
+ unchecked(
+ (int)((((uint)(variant)) << 29) | (((uint)(major)) << 22) | (((uint)(minor)) << 12) | ((uint)(patch)))
+ );
+
+ ///
+ /// VK_API_VERSION_VARIANT - Extract API variant number
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_VARIANT extracts the API variant number from a packed
+ /// version number:
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_API_VERSION_VARIANT(version) ((uint32_t)(version) >> 29U)
+ ///
+ ///
+ public static int ApiVersionVariant(int version) => unchecked((int)((uint)(version) >> 29));
+
+ ///
+ /// VK_API_VERSION_MAJOR - Extract API major version number
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_MAJOR extracts the API major version number from a
+ /// packed version number:
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_API_VERSION_MAJOR(version) (((uint32_t)(version) >> 22U) & 0x7FU)
+ ///
+ ///
+ public static int ApiVersionMajor(int version) => unchecked((int)(((uint)(version) >> 22) & 0x7F));
+
+ ///
+ /// VK_API_VERSION_MINOR - Extract API minor version number
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_MINOR extracts the API minor version number from a
+ /// packed version number:
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_API_VERSION_MINOR(version) (((uint32_t)(version) >> 12U) & 0x3FFU)
+ ///
+ ///
+ public static int ApiVersionMinor(int version) => unchecked((int)(((uint)(version) >> 12) & 0x3FF));
+
+ ///
+ /// VK_API_VERSION_PATCH - Extract API patch version number
+ ///
+ ///
+ ///
+ /// VK_API_VERSION_PATCH extracts the API patch version number from a
+ /// packed version number:
+ ///
+ ///
+ /// // Provided by VK_VERSION_1_0
+ /// #define VK_API_VERSION_PATCH(version) ((uint32_t)(version) & 0xFFFU)
+ ///
+ ///
+ public static int ApiVersionPatch(int version) => unchecked((int)((uint)(version) & 0xFFF));
+
+ ///
+ /// VK_MAKE_VIDEO_STD_VERSION
+ ///
+ public static int MakeVideoStdVersion(int major, int minor, int patch) =>
+ unchecked((int)((((uint)(major)) << 22) | (((uint)(minor)) << 12) | ((uint)(patch))));
+ }
+}
diff --git a/Brutal.Vulkan/ImportResolver.cs b/Brutal.Vulkan/ImportResolver.cs
index 098163b..d7c1e3b 100644
--- a/Brutal.Vulkan/ImportResolver.cs
+++ b/Brutal.Vulkan/ImportResolver.cs
@@ -16,19 +16,7 @@ public partial class Vulkan
static Vulkan()
{
// Load the correct Vulkan library for the platform
-
- if (OperatingSystem.IsWindows())
- Dll = NativeLibrary.Load("vulkan-1", typeof(Vulkan).Assembly, DllImportSearchPath.System32);
-
- // TODO: This is a hack which only works if SDK is installed, we need to package the Vulkan binary on macOS
- if (OperatingSystem.IsMacOS())
- Dll = NativeLibrary.Load("VulkanEx", typeof(Vulkan).Assembly, DllImportSearchPath.LegacyBehavior);
-
- if (OperatingSystem.IsLinux())
- Dll = NativeLibrary.Load("vulkan", typeof(Vulkan).Assembly, DllImportSearchPath.LegacyBehavior);
-
- if (Dll == nint.Zero)
- throw new NullReferenceException("Failed to load Vulkan library");
+ Dll = LoadVulkanLibrary();
// Assign the native library to the assembly resolver
NativeLibrary.SetDllImportResolver(
@@ -47,4 +35,37 @@ public partial class Vulkan
throw new NullReferenceException("Failed to load vkGetInstanceProcAddr from Vulkan library");
}
}
+
+ private static nint LoadVulkanLibrary()
+ {
+ var assembly = typeof(Vulkan).Assembly;
+
+ if (OperatingSystem.IsWindows())
+ return NativeLibrary.Load("vulkan-1", assembly, DllImportSearchPath.System32);
+
+ // Prefer the system Vulkan loader, falling back to the old names
+ string[] candidates = [];
+
+ // TODO: Package the Vulkan loader on macOS so it works without Homebrew or the SDK installed
+ if (OperatingSystem.IsMacOS())
+ candidates =
+ [
+ "libvulkan.1.dylib",
+ "/opt/homebrew/lib/libvulkan.1.dylib",
+ "/usr/local/lib/libvulkan.1.dylib",
+ "VulkanEx",
+ ];
+
+ // libvulkan.so (what "vulkan" resolves to) only ships in -dev packages
+ if (OperatingSystem.IsLinux())
+ candidates = ["libvulkan.so.1", "vulkan"];
+
+ foreach (var candidate in candidates)
+ {
+ if (NativeLibrary.TryLoad(candidate, assembly, DllImportSearchPath.LegacyBehavior, out var dll))
+ return dll;
+ }
+
+ throw new DllNotFoundException($"Failed to load Vulkan library, tried: {string.Join(", ", candidates)}");
+ }
}
diff --git a/Brutal.Vulkan/LICENSES/BRUTAL-VULKAN-THIRD-PARTY-NOTICES.txt b/Brutal.Vulkan/LICENSES/BRUTAL-VULKAN-THIRD-PARTY-NOTICES.txt
index 617d965..5ee3a0f 100644
--- a/Brutal.Vulkan/LICENSES/BRUTAL-VULKAN-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.Vulkan/LICENSES/BRUTAL-VULKAN-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.Vulkan
+Ahwoo.BRUTAL.Vulkan
Brutal.Vulkan contains two kinds of Khronos material, each reproduced below with the
license that governs it. The managed bindings are generated from the Vulkan API registry.
diff --git a/Brutal.Vulkan/Manual/Constants/VK.cs b/Brutal.Vulkan/Manual/Constants/VK.cs
index a65fa7d..2ba9901 100644
--- a/Brutal.Vulkan/Manual/Constants/VK.cs
+++ b/Brutal.Vulkan/Manual/Constants/VK.cs
@@ -3,14 +3,4 @@ namespace Brutal.VulkanApi;
public static partial class VK
{
public static readonly ByteSize WHOLE_SIZE = ByteSize.Of(unchecked((int)(~0UL)));
-
- // #define VK_MAKE_VIDEO_STD_VERSION(major, minor, patch) \
- // ((((uint32_t)(major)) << 22) | (((uint32_t)(minor)) << 12) | ((uint32_t)(patch)))
- private const int STD_VULKAN_VIDEO_CODEC_H264_DECODE_API_VERSION_1_0_0 = 1 << 22;
- private const int STD_VULKAN_VIDEO_CODEC_H264_ENCODE_API_VERSION_1_0_0 = 1 << 22;
- private const int STD_VULKAN_VIDEO_CODEC_H265_DECODE_API_VERSION_1_0_0 = 1 << 22;
- private const int STD_VULKAN_VIDEO_CODEC_H265_ENCODE_API_VERSION_1_0_0 = 1 << 22;
- private const int STD_VULKAN_VIDEO_CODEC_VP9_DECODE_API_VERSION_1_0_0 = 1 << 22;
- private const int STD_VULKAN_VIDEO_CODEC_AV1_DECODE_API_VERSION_1_0_0 = 1 << 22;
- private const int STD_VULKAN_VIDEO_CODEC_AV1_ENCODE_API_VERSION_1_0_0 = 1 << 22;
}
diff --git a/Brutal.ZLib/LICENSES/BRUTAL-ZLIB-THIRD-PARTY-NOTICES.txt b/Brutal.ZLib/LICENSES/BRUTAL-ZLIB-THIRD-PARTY-NOTICES.txt
index 01a53d2..0a69d5a 100644
--- a/Brutal.ZLib/LICENSES/BRUTAL-ZLIB-THIRD-PARTY-NOTICES.txt
+++ b/Brutal.ZLib/LICENSES/BRUTAL-ZLIB-THIRD-PARTY-NOTICES.txt
@@ -1,5 +1,5 @@
THIRD-PARTY LICENSE NOTICES
-RocketWerkz.Brutal.ZLib
+Ahwoo.BRUTAL.ZLib
This package ships one third-party component, zlib, as native libraries and as its
public C headers in source form. The license governing it is reproduced in full below.
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index 50f6de8..85bcd13 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -7,7 +7,7 @@ BRUTAL follows the [Contributor Covenant, version 2.1](https://www.contributor-c
- Be respectful. Criticise code and decisions, not people.
- **Don't direct abuse at maintainers or staff.** Disagreement is fine, but harassment isn't, and it will get you removed even if your technical point is correct.
- No harassment, hate speech, sexual content, doxxing, threats, scams, malware or spam.
-- Stay on topic. GitHub issues and PRs are for BRUTAL development. Use the [forums](https://forums.ahwoo.dev/forums/brutal/) for everything else.
+- Stay on topic. GitHub issues and PRs are for BRUTAL development. Use the [forums](https://forums.ahwoo.com/forums/brutal/) for everything else.
## Scope
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5629fdd..31c87eb 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,10 +1,10 @@
# Contributing to BRUTAL
-Thanks for your interest in BRUTAL. You can submit issues and pull requests. We're a small team, and maintaining a public framework is a lot of work, so please be patient with us. We'll see how things go at first and adjust our process as we learn. Feedback on that process is welcome on the [forums](https://forums.ahwoo.dev/forums/brutal/general/).
+Thanks for your interest in BRUTAL. You can submit issues and pull requests. We're a small team, and maintaining a public framework is a lot of work, so please be patient with us. We'll see how things go at first and adjust our process as we learn. Feedback on that process is welcome on the [forums](https://forums.ahwoo.com/forums/brutal/general/).
## The short version
-- **Questions and "how do I…?"** go to the [BRUTAL forums](https://forums.ahwoo.dev/forums/brutal/guides-and-help/), not GitHub issues.
+- **Questions and "how do I…?"** go to the [BRUTAL forums](https://forums.ahwoo.com/forums/brutal/guides-and-help/), not GitHub issues.
- **Bugs:** open an issue using the bug template, with a minimal repro.
- **Anything bigger than a small fix:** open an issue first and wait for a maintainer to agree the approach before you write the code.
- **Security problems:** report them privately. See [SECURITY.md](SECURITY.md).
@@ -20,7 +20,7 @@ Think of the relationship between the Linux kernel and a distribution like Ubunt
- add dependencies without prior discussion
- change public APIs without an agreed issue
-That isn't because we don't appreciate contributions. Adding everything is how the industry ended up with the kinds of engines BRUTAL exists to avoid. If you build something on top of BRUTAL, please share it in the [Tools and Libraries](https://forums.ahwoo.dev/forums/brutal/tools-and-libraries/) forum.
+That isn't because we don't appreciate contributions. Adding everything is how the industry ended up with the kinds of engines BRUTAL exists to avoid. If you build something on top of BRUTAL, please share it in the [Tools and Libraries](https://forums.ahwoo.com/forums/brutal/tools-and-libraries/) forum.
## Reporting bugs
@@ -45,7 +45,7 @@ Agentic tools can make you very productive. They also make it easy to submit lar
## Licensing of contributions
-BRUTAL is distributed under the [BRUTAL License](LICENSE). **Section 5.0 of the licence covers contributions.** By submitting a contribution you grant Ahwoo Limited and all recipients of BRUTAL a perpetual, worldwide, non-exclusive, royalty-free, irrevocable licence to include it in BRUTAL and use it under the licence's terms. You also confirm that you're legally entitled to grant that licence and that your contribution doesn't infringe anyone else's rights. Please read section 5.0 before opening a PR.
+BRUTAL is distributed under the [BRUTAL License](LICENSE.txt). **Section 5.0 of the licence covers contributions.** By submitting a contribution you grant Ahwoo Limited and all recipients of BRUTAL a perpetual, worldwide, non-exclusive, royalty-free, irrevocable licence to include it in BRUTAL and use it under the licence's terms. You also confirm that you're legally entitled to grant that licence and that your contribution doesn't infringe anyone else's rights. Please read section 5.0 before opening a PR.
Third-party components that BRUTAL redistributes keep their own licences, listed in the `LICENSES/` directory (section 4.0). Don't add third-party code without discussing it in an issue first.
@@ -65,7 +65,7 @@ You don't need to contribute to use BRUTAL. It's free, including for commercial
- **2.2:** the BRUTAL logo from [ahwoo.com/brutal-branding](https://ahwoo.com/brutal-branding) shown before gameplay starts
- **2.3:** `NOTICE.txt` shipped alongside your game
-For a logo waiver (for example non-profit projects, or where the logo would get in the way of the product's purpose) or a separate commercial licence, contact Ahwoo at **[CONTACT ADDRESS]**.
+For a logo waiver (for example non-profit projects, or where the logo would get in the way of the product's purpose) or a separate commercial licence, contact Ahwoo at **brutal@ahwoo.com**.
## Code of Conduct
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..ab9134d
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,56 @@
+BRUTAL License v1.0
+
+BRUTAL game development framework is Copyright (c) 2024 Ahwoo Limited.
+
+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:
+
+1.0. The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+2.0. Any game, application, or other software product that is distributed to
+end users and that incorporates, links to, or is built using the Software or
+substantial portion of it (a “Product”) is subject to the following
+conditions:
+
+2.1. The above copyright notice shall be included in the Credits screen or
+equivalent for all copies of the Product.
+
+2.2. The Brutal logo available from ahwoo.com/brutal-branding shall be
+displayed in all copies of the Product prior to commencement of gameplay or the
+Software’s primary function, unless permission has been granted in writing by
+Ahwoo Limited or the Product is not capable of displaying graphics. The logo
+shall be shown unaltered except for scaling, for long enough to be legible, and
+shall be no less prominent than logos for other parties.
+
+2.3. The NOTICE.txt file shall be distributed alongside all copies of the
+Product.
+
+3.0. 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.
+
+4.0. Where this package redistributes third-party components, they are listed,
+together with the licences that govern them, in the LICENSES/ directory at the
+root of this package. Those licences continue to apply to those components, and
+nothing stated here limits any right they grant you.
+
+5.0. Any person submitting any contribution to the Software, hereby grants
+Ahwoo Limited and all recipients of this Software a perpetual, worldwide,
+non-exclusive, no-charge, royalty-free, irrevocable license to include the
+contribution in the Software and use it under the terms of this license. Any
+person submitting any contribution represents that they are legally entitled to
+grant this license and that their contribution does not infringe upon any
+third-party rights.
+
+6.0. This Agreement is governed by and shall be construed in accordance with
+the laws of New Zealand, and the parties submit to the exclusive jurisdiction
+of the courts of New Zealand.
diff --git a/NOTICE.txt b/NOTICE.txt
new file mode 100644
index 0000000..b4f4087
--- /dev/null
+++ b/NOTICE.txt
@@ -0,0 +1,5 @@
+BRUTAL game development framework is Copyright (c) 2024 Ahwoo Limited.
+
+This product is built with BRUTAL, a game development framework by Ahwoo Limited, used under the BRUTAL License v1.0.
+
+www.ahwoo.com/brutal
diff --git a/README.md b/README.md
index 72bc63a..1caaef8 100644
--- a/README.md
+++ b/README.md
@@ -40,6 +40,7 @@ BRUTAL is not trying to be a general-purpose engine. There is no editor, no scen
| [Kitten Space Agency](https://ahwoo.com/app/100000/kitten-space-agency/) | RocketWerkz | Direct on BRUTAL |
| Torpedia | RocketWerkz | Direct on BRUTAL |
| Art of the Rail | RocketWerkz | Direct on BRUTAL |
+| [Gruntz](https://www.youtube.com/watch?v=ROB5IilenZE) | RocketWerkz | Direct on BRUTAL |
| Afterskies | Floating Origin Interactive | Direct on BRUTAL |
Ludeon report 2 to 4 times the performance of the Unity build in their own tests, with the vast majority of existing mods still compatible. See their [Steam announcement](https://steamcommunity.com/games/294100/announcements/detail/672882362547178634).
@@ -52,30 +53,31 @@ Each top-level folder in this repository is one library, published as a NuGet pa
| Library | What it is |
| --- | --- |
-| `brutal.core` | Base types, attributes, platform detection, pointer helpers, Roslyn analyzers |
-| `brutal.interop` | The custom interop layer that gives C# direct access to native APIs |
-| `brutal.memory` | Unmanaged memory management and allocators |
-| `brutal.collections` | Collections that don't allocate |
-| `brutal.strings` | String building and handling without allocation |
-| `brutal.maths`, `brutal.numerics` | Vector, matrix and numeric types |
-| `brutal.concurrency` | Job system and threading |
-| `brutal.logging` | Logging |
-| `brutal.localization` | Localization |
-| `brutal.vulkan` | Vulkan bindings, abstractions and the Vulkan Memory Allocator |
-| `brutal.opengl` | OpenGL bindings |
-| `brutal.glfw`, `brutal.sdl` | Windowing and input |
-| `brutal.imgui` | Dear ImGui and ImPlot bindings, docking branch |
-| `brutal.render` | Mesh utilities |
-| `brutal.texture`, `brutal.ktx`, `brutal.gli`, `brutal.stb` | Texture loading, KTX and compressed formats, image decoding |
-| `brutal.gltf`, `brutal.meshoptimizer` | glTF loading and mesh optimisation |
-| `brutal.freetype` | Font rasterisation |
-| `brutal.fmod`, `brutal.openal` | Audio |
-| `brutal.raknet` | Networking |
-| `brutal.jolt`, `brutal.box2d` | 3D and 2D physics |
-| `brutal.monitor`, `brutal.renderdoc` | Runtime monitoring and RenderDoc capture integration |
-| `brutal.nativefiledialog`, `brutal.notcurses`, `brutal.zlib` | Native file dialogs, terminal UI, compression |
+| `Brutal.Core` | Base types, attributes, platform detection, pointer helpers, Roslyn analyzers |
+| `Brutal.Interop` | The custom interop layer that gives C# direct access to native APIs |
+| `Brutal.Memory` | Unmanaged memory management and allocators |
+| `Brutal.Collections` | Collections that don't allocate |
+| `Brutal.Strings` | String building and handling without allocation |
+| `Brutal.Maths`, `Brutal.Numerics` | Vector, matrix and numeric types |
+| `Brutal.Concurrency` | Job system and threading |
+| `Brutal.Logging` | Logging |
+| `Brutal.Localization` | Localization |
+| `Brutal.Vulkan`, `Brutal.Vulkan.Abstractions`, `Brutal.Vulkan.Vma` | Vulkan bindings, abstractions and the Vulkan Memory Allocator |
+| `Brutal.OpenGl` | OpenGL bindings |
+| `Brutal.ShaderC`, `Brutal.Slang` | Shader compilation |
+| `Brutal.Glfw`, `Brutal.Sdl`, `Brutal.Sdl.Image`, `Brutal.Sdl.Mixer`, `Brutal.Sdl.Ttf` | Windowing and input, with SDL's image, audio mixing and font add-ons |
+| `Brutal.ImGui`, `Brutal.ImGui.*`, `Brutal.ImPlot` | Dear ImGui and ImPlot bindings, docking branch |
+| `Brutal.Render.Mesh` | Mesh utilities |
+| `Brutal.Texture`, `Brutal.Texture.Abstractions`, `Brutal.Ktx`, `Brutal.Gli`, `Brutal.Stb` | Texture loading, KTX and compressed formats, image decoding |
+| `Brutal.Gltf`, `Brutal.MeshOptimizer` | glTF loading and mesh optimisation |
+| `Brutal.FreeType` | Font rasterisation |
+| `Brutal.Fmod`, `Brutal.OpenAl` | Audio |
+| `Brutal.RakNet` | Networking |
+| `Brutal.Jolt`, `Brutal.Box2D` | 3D and 2D physics |
+| `Brutal.Monitor.Common`, `Brutal.Monitor.Host`, `Brutal.RenderDoc`, `Brutal.RenderDoc.ImGui` | Runtime monitoring and RenderDoc capture integration |
+| `Brutal.NativeFileDialog`, `Brutal.NotCurses`, `Brutal.ZLib` | Native file dialogs, terminal UI, compression |
-Third-party notices for each binding live in that library's `LICENSES` folder.
+Third-party notices for each library live in its `LICENSES` folder, `Brutal.ImGui/LICENSES` say.
## Getting started
@@ -123,7 +125,9 @@ Glfw.Terminate();
dotnet run
```
-That opens a window with no graphics API. What you add next is up to you:
+That opens a window with no graphics API. For a minimal sample of every package, see [samples](samples/README.md).
+
+What you add next is up to you:
- **Rendering:** `Ahwoo.Brutal.Vulkan.Abstractions` and `Ahwoo.Brutal.Vulkan.Vma` for a Vulkan renderer, `Ahwoo.Brutal.ShaderC` to compile shaders at runtime.
- **Debug UI:** `Ahwoo.Brutal.ImGui` and `Ahwoo.Brutal.ImPlot`.
@@ -152,7 +156,9 @@ The licence is based on MIT with an added attribution requirement. A game or pro
If you don't want to do that, we can arrange a separate commercial licence. We also waive the logo requirement for non-profit projects and where displaying it would be detrimental to the application's purpose.
-BRUTAL is open source. There are already OSI-approved licences that allow graphical attribution. Ours is not yet OSI approved because we have not submitted it yet. We intend to, and to develop the licence with community feedback. See [LICENSE](LICENSE) for the full text.
+BRUTAL is open source. There are already OSI-approved licences that allow graphical attribution. Ours is not yet OSI approved because we have not submitted it yet. We intend to, and to develop the licence with community feedback. See [LICENSE.txt](LICENSE.txt) for the full text.
+
+Third-party components keep their own licences. Section 4.0 points at the `LICENSES` folder at the root of each NuGet package; in this repository, those notices are in the `LICENSES` folder of each library that redistributes them.
## Contributing
diff --git a/samples/Demo/DemoBox2D.cs b/samples/Demo/DemoBox2D.cs
new file mode 100644
index 0000000..7c9df18
--- /dev/null
+++ b/samples/Demo/DemoBox2D.cs
@@ -0,0 +1,197 @@
+/*
+ * DemoBox2D
+ *
+ * Drops a pile of boxes onto the ground with Box2D and draws them with OpenGL every frame: the
+ * visual counterpart of the headless Hello/HelloBox2D.cs. Press Escape to close it.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Box2D@2026.10.2
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.OpenGl@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal;
+using Brutal.Box2DApi;
+using Brutal.GlfwApi;
+using Brutal.Numerics;
+using Brutal.OpenGlApi;
+
+// GLFW is the only library-wide state, set up here and terminated even if Run throws.
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+try
+{
+ Run();
+}
+finally
+{
+ Glfw.Terminate();
+}
+
+// Everything else: its using declarations dispose in reverse, the program and shaders, then the
+// window, then the physics world with all its bodies.
+static void Run()
+{
+ // Physics: a static ground and a handful of boxes dropped from different heights.
+ using var world = Box2D.CreateWorld(B2WorldDef.Default);
+
+ var ground = world.CreateBody(new B2BodyDef { Position = new float2(0, -0.5f) });
+ ground.CreatePolygonShape(B2ShapeDef.Default, Box2D.MakeBox(9, 0.5f)); // Top surface at y = 0.
+
+ var bodies = new List<(B2Body Body, float2 HalfSize, float3 Color)>
+ {
+ (ground, new float2(9, 0.5f), new float3(0.6f, 0.6f, 0.6f)),
+ };
+ for (var i = 0; i < 12; i++)
+ {
+ var body = world.CreateBody(
+ new B2BodyDef
+ {
+ Type = B2BodyType.Dynamic,
+ Position = new float2(-3 + i % 4 * 2f, 4 + i * 1.2f),
+ Rotation = new B2Rot(i * 0.4f),
+ }
+ );
+ body.CreatePolygonShape(B2ShapeDef.Default, Box2D.MakeBox(0.5f, 0.5f));
+ bodies.Add((body, new float2(0.5f, 0.5f), new float3(1.0f - i / 12f, 0.5f, i / 12f)));
+ }
+
+ // Window and OpenGL, as in Hello/HelloOpenGl.cs.
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
+ Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
+
+ if (Platform.IsMacOS)
+ Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
+
+ // A fixed size keeps the viewport and aspect ratio valid.
+ Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
+
+ using var window = Glfw.CreateWindow(new GlfwWindow.CreateInfo { Title = "Demo Box2D", Size = new int2(640, 480) });
+
+ window.MakeContextCurrent();
+ Glfw.SwapInterval(1);
+
+ unsafe
+ {
+ if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
+ throw new InvalidOperationException("Failed to initialize OpenGL");
+ }
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ using var vertexShader = OpenGl
+ .CreateShader(GlShaderType.Vertex)
+ .SetSource(
+ """
+ #version 410 core
+ layout (location = 0) in vec2 aPos;
+ layout (location = 1) in vec3 aColor;
+ out vec3 color;
+ void main()
+ {
+ color = aColor;
+ // Show world x in [-10, 10] and y in [-1, 14].
+ gl_Position = vec4(aPos.x / 10.0, (aPos.y - 6.5) / 7.5, 0.0, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var fragmentShader = OpenGl
+ .CreateShader(GlShaderType.Fragment)
+ .SetSource(
+ """
+ #version 410 core
+ in vec3 color;
+ out vec4 FragColor;
+ void main()
+ {
+ FragColor = vec4(color, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var program = OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
+
+ // Vertex arrays and buffers aren't disposable, so they're deleted at the end, while the window's
+ // context still exists.
+ var vertexArray = OpenGl.GenVertexArray().Bind();
+ var vertexBuffer = OpenGl.GenBuffer();
+ vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
+
+ OpenGl.VertexAttribute(new GlAttribute(0, 2, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 0));
+ OpenGl.VertexAttribute(
+ new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 2 * sizeof(float))
+ );
+ OpenGl.EnableVertexAttribArray(0);
+ OpenGl.EnableVertexAttribArray(1);
+
+ // Two triangles per box, five floats (x, y, r, g, b) per vertex.
+ var vertices = new float[bodies.Count * 6 * 5];
+ float2[] corners = [new(-1, -1), new(1, -1), new(1, 1), new(-1, -1), new(1, 1), new(-1, 1)];
+
+ OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
+
+ const float TIME_STEP = 1.0f / 60.0f;
+ var previousTime = Glfw.Time;
+ var accumulator = 0.0;
+
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+
+ // Step physics at a fixed rate whatever the refresh rate, capping the catch-up after a stall.
+ var now = Glfw.Time;
+ accumulator += Math.Min(now - previousTime, 0.25);
+ previousTime = now;
+ while (accumulator >= TIME_STEP)
+ {
+ world.Step(TIME_STEP, 4);
+ accumulator -= TIME_STEP;
+ }
+
+ var v = 0;
+ foreach (var (body, halfSize, color) in bodies)
+ {
+ var transform = body.GetTransform();
+ foreach (var corner in corners)
+ {
+ var local = corner * halfSize;
+ var p =
+ transform.P
+ + new float2(
+ transform.Q.C * local.X - transform.Q.S * local.Y,
+ transform.Q.S * local.X + transform.Q.C * local.Y
+ );
+ vertices[v++] = p.X;
+ vertices[v++] = p.Y;
+ vertices[v++] = color.X;
+ vertices[v++] = color.Y;
+ vertices[v++] = color.Z;
+ }
+ }
+
+ OpenGl.Clear(GlClearBit.Color);
+ program.Use();
+ vertexArray.Bind();
+ vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
+ OpenGl.BufferData(GlBindTarget.ArrayBuffer, vertices, GlBufferUsage.DynamicDraw);
+ OpenGl.Draw(GlTopology.Triangles, bodies.Count * 6, 1, 0, 0);
+ window.SwapBuffers();
+ }
+
+ OpenGl.DeleteVertexArrays([vertexArray]);
+ OpenGl.DeleteBuffers([vertexBuffer]);
+}
diff --git a/samples/Demo/DemoGltfViewer.cs b/samples/Demo/DemoGltfViewer.cs
new file mode 100644
index 0000000..28d0899
--- /dev/null
+++ b/samples/Demo/DemoGltfViewer.cs
@@ -0,0 +1,431 @@
+/*
+ * DemoGltfViewer
+ *
+ * Loads a glTF model, reorders it with meshoptimizer for the GPU's vertex cache and fetch, and
+ * draws it lit and slowly rotating with OpenGL. Pass a .gltf or .glb path to view your own
+ * model (`dotnet run Demo/DemoGltfViewer.cs -- model.glb`); without one it builds a torus knot,
+ * writes it out as a .glb with Brutal.Gltf and views that.
+ *
+ * It walks the file's scene graph, placing every triangle primitive with its node's matrix or
+ * translation, rotation and scale; other primitive modes, and quantized (non-float) positions,
+ * aren't supported. Materials, textures, cameras, lights, skins, morph targets and animations
+ * are ignored, so the model is drawn untextured in its rest pose. Press Escape to close it.
+ */
+
+// Brutal.Gltf uses reflection-based System.Text.Json, which Native AOT (the default for
+// file-based apps) disables.
+#:property PublishAot=false
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Gltf@2026.10.3
+#:package Ahwoo.Brutal.MeshOptimizer@2026.10.2
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.OpenGl@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using System.Runtime.InteropServices;
+using Brutal;
+using Brutal.GlfwApi;
+using Brutal.GltfApi;
+using Brutal.MeshOptimizer;
+using Brutal.Numerics;
+using Brutal.OpenGlApi;
+
+// GLFW is the only library-wide state, set up here and terminated even if Run throws.
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+try
+{
+ Run(args);
+}
+finally
+{
+ Glfw.Terminate();
+}
+
+// Everything else: its using declarations dispose in reverse, the program and shaders, then the
+// window, then the glTF loader.
+static void Run(string[] args)
+{
+ var path = args.Length > 0 ? args[0] : WriteTorusKnotGlb(Path.Combine(Path.GetTempPath(), "DemoGltfViewer.glb"));
+
+ // Every primitive goes into one shared vertex and index list, each mesh loaded once however many
+ // nodes use it; each draw is one of those primitives with the world transform of a node using it.
+ using var loader = new GltfLoader(path);
+ var gltf = loader.GltfJson;
+ List vertices = [];
+ List indices = [];
+ var meshPrimitives = new Dictionary>();
+ var draws = new List<(Primitive Primitive, float4x4 World)>();
+ var (transformsBefore, transformsAfter) = (0f, 0f);
+
+ // Draw the file's chosen scene, else its first, else every mesh once where it stands.
+ if ((gltf.Scene ?? (gltf.Scenes?.Length > 0 ? 0 : null)) is { } scene)
+ foreach (var root in gltf.Scenes![scene].Nodes ?? [])
+ AddNode(root, float4x4.Identity);
+ else
+ for (var mesh = 0; mesh < (gltf.Meshes?.Length ?? 0); mesh++)
+ draws.AddRange(LoadMesh(mesh).Select(p => (p, float4x4.Identity)));
+
+ if (draws.Count == 0)
+ throw new NotSupportedException($"{Path.GetFileName(path)} has no triangle meshes to draw");
+
+ var triangles = indices.Count / 3;
+ Console.WriteLine(
+ $"{Path.GetFileName(path)}: {draws.Count} draws, {triangles} triangles, {vertices.Count} vertices"
+ );
+ Console.WriteLine(
+ $"ACMR (vertex transforms per triangle): {transformsBefore / triangles:F2} -> {transformsAfter / triangles:F2}"
+ );
+
+ // Fit the camera to the placed model: centre it on the origin and back off far enough to see all of it.
+ float3[] points =
+ [
+ .. draws.SelectMany(d =>
+ vertices
+ .GetRange(d.Primitive.BaseVertex, d.Primitive.VertexCount)
+ .Select(v => float3.Transform(v.Position, d.World))
+ ),
+ ];
+ var min = points.Aggregate(float3.Min);
+ var max = points.Aggregate(float3.Max);
+ var centre = (min + max) / 2;
+ var radius = MathF.Max((max - min).Length() / 2, 1e-3f);
+
+ // Places a node and its children: a node has either a matrix or translation, rotation and scale,
+ // whichever it lacks is identity, and a child's world transform is its local one times its parent's.
+ void AddNode(int nodeIndex, float4x4 parentWorld)
+ {
+ var node = gltf.Nodes[nodeIndex];
+ var trs =
+ float4x4.CreateScale(node.Scale)
+ * float4x4.CreateFromQuaternion(node.Rotation)
+ * float4x4.CreateTranslation(node.Translation);
+ var world = node.Matrix * trs * parentWorld;
+ if (node.Mesh is { } mesh)
+ draws.AddRange(LoadMesh(mesh).Select(p => (p, world)));
+ foreach (var child in node.Children ?? [])
+ AddNode(child, world);
+ }
+
+ // Reads a mesh's triangle primitives, filling in indices and normals where the file has none,
+ // optimises each and appends it to the shared lists.
+ List LoadMesh(int meshIndex)
+ {
+ if (meshPrimitives.TryGetValue(meshIndex, out var loaded))
+ return loaded;
+ meshPrimitives[meshIndex] = loaded = [];
+
+ foreach (var primitive in gltf.Meshes![meshIndex].Primitives)
+ {
+ if (primitive.Mode != MeshPrimitive.ModeEnum.Triangles)
+ {
+ Console.WriteLine(
+ $"Skipping a {primitive.Mode} primitive in mesh {meshIndex}: only triangles are drawn"
+ );
+ continue;
+ }
+
+ var positions = ReadFloat3s(loader, primitive.Attributes["POSITION"]);
+ int[] ids = primitive.Indices is { } i
+ ? ReadIndices(loader, i)
+ : [.. Enumerable.Range(0, positions.Length)];
+ var normals = primitive.Attributes.TryGetValue("NORMAL", out var n)
+ ? ReadFloat3s(loader, n)
+ : SmoothNormals(positions, ids);
+ var verts = positions.Zip(normals, (p, q) => new Vertex(p, q)).ToArray();
+
+ // Reorder triangles so recently used vertices are reused, then vertices into first-use order.
+ unsafe
+ {
+ fixed (int* p = ids)
+ fixed (Vertex* v = verts)
+ {
+ // AnalyzeVertexCache arguments: cache size 16, warp size 0, primitive group size 0.
+ transformsBefore +=
+ MeshOptimizer.AnalyzeVertexCache(p, ids.Length, verts.Length, 16, 0, 0).Acmr * ids.Length / 3;
+ MeshOptimizer.OptimizeVertexCache(p, p, ids.Length, verts.Length);
+ MeshOptimizer.OptimizeVertexFetch(v, p, ids.Length, v, verts.Length, ByteSize.Of());
+ transformsAfter +=
+ MeshOptimizer.AnalyzeVertexCache(p, ids.Length, verts.Length, 16, 0, 0).Acmr * ids.Length / 3;
+ }
+ }
+
+ loaded.Add(new Primitive(indices.Count, ids.Length, vertices.Count, verts.Length));
+ indices.AddRange(ids);
+ vertices.AddRange(verts);
+ }
+ return loaded;
+ }
+
+ // Window and OpenGL, as in Hello/HelloOpenGl.cs.
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
+ Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
+
+ if (Platform.IsMacOS)
+ Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
+
+ // A fixed size, so the viewport and the projection's aspect ratio never need updating.
+ Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
+
+ using var window = Glfw.CreateWindow(
+ new GlfwWindow.CreateInfo { Title = "Demo glTF Viewer", Size = new int2(640, 480) }
+ );
+
+ window.MakeContextCurrent();
+ Glfw.SwapInterval(1);
+
+ unsafe
+ {
+ if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
+ throw new InvalidOperationException("Failed to initialize OpenGL");
+ }
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ using var vertexShader = OpenGl
+ .CreateShader(GlShaderType.Vertex)
+ .SetSource(
+ """
+ #version 410 core
+ layout (location = 0) in vec3 aPos;
+ layout (location = 1) in vec3 aNormal;
+ uniform mat4 model;
+ uniform mat4 viewProjection;
+ out vec3 normal;
+ void main()
+ {
+ normal = transpose(inverse(mat3(model))) * aNormal;
+ gl_Position = viewProjection * model * vec4(aPos, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var fragmentShader = OpenGl
+ .CreateShader(GlShaderType.Fragment)
+ .SetSource(
+ """
+ #version 410 core
+ in vec3 normal;
+ out vec4 FragColor;
+ void main()
+ {
+ // A warm key light and a cool fill from below, plus a little ambient.
+ vec3 n = normalize(normal);
+ vec3 key = vec3(1.0, 0.9, 0.75) * max(dot(n, normalize(vec3(0.4, 1.0, 0.6))), 0.0);
+ vec3 fill = vec3(0.25, 0.3, 0.45) * max(dot(n, normalize(vec3(-0.6, -0.4, -0.3))), 0.0);
+ FragColor = vec4(vec3(0.8) * (0.15 + key + fill), 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var program = OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
+
+ // Vertex arrays and buffers aren't disposable, so they're deleted at the end, while the window's
+ // context still exists.
+ var vertexArray = OpenGl.GenVertexArray().Bind();
+ var vertexBuffer = OpenGl.GenBuffer();
+ var indexBuffer = OpenGl.GenBuffer();
+ vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
+ OpenGl.BufferData(GlBindTarget.ArrayBuffer, vertices.ToArray(), GlBufferUsage.StaticDraw);
+ indexBuffer.Bind(GlBindTarget.ElementArrayBuffer); // Recorded in the vertex array.
+ OpenGl.BufferData(GlBindTarget.ElementArrayBuffer, indices.ToArray(), GlBufferUsage.StaticDraw);
+
+ OpenGl.VertexAttribute(new GlAttribute(0, 3, OpenGl.GL_FLOAT, GlScaling.Float, 6 * sizeof(float), 0));
+ OpenGl.VertexAttribute(
+ new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 6 * sizeof(float), 3 * sizeof(float))
+ );
+ OpenGl.EnableVertexAttribArray(0);
+ OpenGl.EnableVertexAttribArray(1);
+
+ OpenGl.Enable(GlCapability.DepthTest);
+ OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
+
+ // 45 degree field of view: a sphere of this radius just fits at radius / sin(22.5 degrees).
+ var view = float4x4.CreateLookAt(new float3(0, 0.4f, 1) * radius * 2.8f, float3.Zero, float3.UnitY);
+ var projection = float4x4.CreatePerspectiveFieldOfView(MathF.PI / 4, 640f / 480f, radius / 10, radius * 10);
+
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+
+ OpenGl.Clear(GlClearBit.Color | GlClearBit.Depth);
+ program.Use();
+ program.Uniform("viewProjection"u8, view * projection);
+ vertexArray.Bind();
+ var spin = float4x4.CreateTranslation(-centre) * float4x4.CreateRotationY((float)Glfw.Time * 0.5f);
+ foreach (var (primitive, world) in draws)
+ {
+ // The first index is passed as a byte offset into the index buffer.
+ program.Uniform("model"u8, world * spin);
+ OpenGl.DrawIndexed(
+ GlTopology.Triangles,
+ GlIndexType.UInt,
+ primitive.IndexCount,
+ 1,
+ primitive.FirstIndex * sizeof(int),
+ primitive.BaseVertex,
+ 0
+ );
+ }
+
+ window.SwapBuffers();
+ }
+
+ OpenGl.DeleteVertexArrays([vertexArray]);
+ OpenGl.DeleteBuffers([vertexBuffer, indexBuffer]);
+}
+
+// Reads a float VEC3 accessor, such as positions or normals, which may be interleaved with other data.
+static float3[] ReadFloat3s(GltfLoader loader, int accessorIndex)
+{
+ var accessor = loader.GltfJson.Accessors[accessorIndex];
+ if (accessor.ComponentType != Accessor.ComponentTypeEnum.Float || accessor.Type != Accessor.TypeEnum.Vec3)
+ throw new NotSupportedException($"Expected float VEC3 data, not {accessor.ComponentType} {accessor.Type}");
+
+ var bytes = loader.GetBufferView(accessor.BufferView!.Value)[accessor.ByteOffset..];
+ var stride = loader.GltfJson.BufferViews[accessor.BufferView.Value].ByteStride ?? 3 * sizeof(float);
+ var result = new float3[accessor.Count];
+ for (var i = 0; i < result.Length; i++)
+ result[i] = MemoryMarshal.Read(bytes[(i * stride)..]);
+ return result;
+}
+
+// Reads an index accessor of any of the three index sizes glTF allows, widening to 32-bit.
+static int[] ReadIndices(GltfLoader loader, int accessorIndex)
+{
+ var accessor = loader.GltfJson.Accessors[accessorIndex];
+ var bytes = loader.GetBufferView(accessor.BufferView!.Value)[accessor.ByteOffset..];
+ return accessor.ComponentType switch
+ {
+ Accessor.ComponentTypeEnum.UnsignedByte => [.. bytes[..accessor.Count].ToArray().Select(b => (int)b)],
+ Accessor.ComponentTypeEnum.UnsignedShort =>
+ [
+ .. MemoryMarshal.Cast(bytes)[..accessor.Count].ToArray().Select(s => (int)s),
+ ],
+ _ => MemoryMarshal.Cast(bytes)[..accessor.Count].ToArray(),
+ };
+}
+
+// Sums each triangle's area-weighted face normal into its vertices; flat when no vertices are shared.
+static float3[] SmoothNormals(float3[] positions, int[] indices)
+{
+ var normals = new float3[positions.Length];
+ foreach (var t in indices.Chunk(3))
+ {
+ var normal = float3.Cross(positions[t[1]] - positions[t[0]], positions[t[2]] - positions[t[0]]);
+ foreach (var index in t)
+ normals[index] += normal;
+ }
+ return [.. normals.Select(float3.NormalizeOrZero)];
+}
+
+// Sweeps a circle along a (2, 3) torus knot and writes the result as a .glb with Brutal.Gltf,
+// positions and indices only, so the viewer has to compute its normals.
+static string WriteTorusKnotGlb(string path)
+{
+ const int SEGMENTS = 256;
+ const int SIDES = 24;
+
+ static float3 Knot(float u)
+ {
+ var r = 2 + MathF.Cos(3 * u);
+ return new float3(r * MathF.Cos(2 * u), MathF.Sin(3 * u), r * MathF.Sin(2 * u));
+ }
+
+ // Vertex index of a point on the tube, wrapping around both the knot and the tube.
+ static int At(int ring, int around) => ring % SEGMENTS * SIDES + around % SIDES;
+
+ var positions = new List();
+ var indices = new List();
+ for (var s = 0; s < SEGMENTS; s++)
+ {
+ // A frame around the curve: tangent from a step ahead, then two perpendicular axes.
+ var u = s * MathF.Tau / SEGMENTS;
+ var (here, ahead) = (Knot(u), Knot(u + 0.01f));
+ var side = float3.Normalize(float3.Cross(ahead - here, ahead + here));
+ var up = float3.Normalize(float3.Cross(side, ahead - here));
+ for (var j = 0; j < SIDES; j++)
+ {
+ var v = j * MathF.Tau / SIDES;
+ positions.Add(here + (up * MathF.Cos(v) + side * MathF.Sin(v)) * 0.4f);
+
+ // Two triangles joining this point to the next ring, counter-clockwise seen from outside as glTF expects.
+ indices.AddRange([At(s, j), At(s + 1, j + 1), At(s + 1, j)]);
+ indices.AddRange([At(s, j), At(s, j + 1), At(s + 1, j + 1)]);
+ }
+ }
+
+ var positionBytes = MemoryMarshal.AsBytes(positions.ToArray().AsSpan()).ToArray();
+ var indexBytes = MemoryMarshal.AsBytes(indices.ToArray().AsSpan()).ToArray();
+ var (min, max) = (positions.Aggregate(float3.Min), positions.Aggregate(float3.Max));
+
+ // One binary buffer holding the positions then the indices, a view into each, and an
+ // accessor saying how to read each view; glTF requires min and max on positions.
+ var model = new Gltf
+ {
+ Asset = new Asset { Version = "2.0" },
+ Buffers = [new Brutal.GltfApi.Buffer { ByteLength = positionBytes.Length + indexBytes.Length }],
+ BufferViews =
+ [
+ new BufferView { Buffer = 0, ByteLength = positionBytes.Length },
+ new BufferView
+ {
+ Buffer = 0,
+ ByteOffset = positionBytes.Length,
+ ByteLength = indexBytes.Length,
+ },
+ ],
+ Accessors =
+ [
+ new Accessor
+ {
+ BufferView = 0,
+ ComponentType = Accessor.ComponentTypeEnum.Float,
+ Count = positions.Count,
+ Type = Accessor.TypeEnum.Vec3,
+ Min = [min.X, min.Y, min.Z],
+ Max = [max.X, max.Y, max.Z],
+ },
+ new Accessor
+ {
+ BufferView = 1,
+ ComponentType = Accessor.ComponentTypeEnum.UnsignedInt,
+ Count = indices.Count,
+ Type = Accessor.TypeEnum.Scalar,
+ },
+ ],
+ Meshes =
+ [
+ new Mesh
+ {
+ Primitives =
+ [
+ new MeshPrimitive
+ {
+ Attributes = new() { ["POSITION"] = 0 },
+ Indices = 1,
+ },
+ ],
+ },
+ ],
+ };
+ model.SaveBinaryModel([.. positionBytes, .. indexBytes], path);
+ return path;
+}
+
+record struct Vertex(float3 Position, float3 Normal);
+
+// Where a primitive lives in the shared index and vertex lists.
+record struct Primitive(int FirstIndex, int IndexCount, int BaseVertex, int VertexCount);
diff --git a/samples/Demo/DemoImGui.cs b/samples/Demo/DemoImGui.cs
new file mode 100644
index 0000000..06d0a01
--- /dev/null
+++ b/samples/Demo/DemoImGui.cs
@@ -0,0 +1,140 @@
+/*
+ * DemoImGui
+ *
+ * Dear ImGui on GLFW + OpenGL: a button, a slider and an ImPlot line plot, with fonts
+ * rasterised by FreeType. Press Escape to close it.
+ *
+ * Optionally pass a font:
+ *
+ * dotnet run Demo/DemoImGui.cs -- path/to/font.ttf
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.ImGui@2026.10.3
+#:package Ahwoo.Brutal.ImGui.Backends@2026.10.3
+#:package Ahwoo.Brutal.ImGui.FreeType@2026.10.3
+#:package Ahwoo.Brutal.ImPlot@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+#:package Ahwoo.Brutal.OpenGl@2026.10.2
+
+using Brutal;
+using Brutal.GlfwApi;
+using Brutal.ImGuiApi;
+using Brutal.ImGuiApi.Backends;
+using Brutal.ImGuiApi.FreeType;
+using Brutal.ImPlotApi;
+using Brutal.Numerics;
+using Brutal.OpenGlApi;
+
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+var context = ImGui.CreateContext();
+var plotContext = ImPlot.CreateContext();
+ImPlot.SetImGuiContext(context);
+
+try
+{
+ Run(args);
+}
+finally
+{
+ ImPlot.DestroyContext(plotContext);
+ ImGui.DestroyContext(context);
+ Glfw.Terminate();
+}
+
+static void Run(string[] args)
+{
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
+ Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
+
+ if (Platform.IsMacOS)
+ Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
+
+ // Declared first so it's disposed last: the backends below need the window and its GL context.
+ using var window = Glfw.CreateWindow(new GlfwWindow.CreateInfo { Title = "Demo ImGui", Size = new int2(800, 600) });
+
+ window.MakeContextCurrent();
+ Glfw.SwapInterval(1); // Wait for vsync instead of drawing as fast as possible.
+
+ unsafe
+ {
+ if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
+ throw new InvalidOperationException("Failed to initialize OpenGL");
+ }
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ ImGui.GetIO().IniFilename = null; // Don't write imgui.ini.
+
+ // Rasterize fonts with FreeType instead of the built-in stb_truetype.
+ var fonts = ImGui.GetIO().Fonts;
+ fonts.SetFontLoader(ImGuiFreeType.GetFontLoader());
+ if (args.Length > 0)
+ fonts.AddFontFromFileTTF(args[0], 24f); // Optional: dotnet run Demo/DemoImGui.cs -- path/to/font.ttf.
+
+ using var glfwBackend = new GlfwBackend(window, GlfwBackend.ClientApi.OpenGL);
+ using var openGlBackend = new OpenGlBackend();
+
+ var clicks = 0;
+ var frequency = 1f;
+ var xs = new float[200];
+ var ys = new float[200];
+
+ OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
+
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+
+ glfwBackend.NewFrame();
+ openGlBackend.NewFrame();
+ ImGui.NewFrame();
+ // Recycle the scratch memory that interpolated ImGui strings ($"...") use, once per frame.
+ ImString.SharedStorage.Reset();
+
+ var time = (float)Glfw.Time;
+ for (var i = 0; i < xs.Length; i++)
+ {
+ xs[i] = i * 0.05f;
+ ys[i] = MathF.Sin(xs[i] * frequency + time);
+ }
+
+ ImGui.SetNextWindowSize(new float2(500, 400), ImGuiCond.FirstUseEver);
+ if (ImGui.Begin("Demo ImGui"u8))
+ {
+ ImGui.Text("Hello from Dear ImGui!"u8);
+
+ if (ImGui.Button("Click me"u8))
+ clicks++;
+ ImGui.SameLine();
+ ImGui.Text($"Clicked {clicks} times");
+
+ ImGui.SliderFloat("Frequency"u8, ref frequency, 0.1f, 5f);
+
+ if (ImPlot.BeginPlot("Sine Wave"u8, new float2(-1, -1))) // Fill the rest of the window.
+ {
+ ImPlot.PlotLine("sin(x * f + t)"u8, xs, ys);
+ ImPlot.EndPlot();
+ }
+ }
+ ImGui.End();
+
+ ImGui.Render();
+
+ OpenGl.Clear(GlClearBit.Color);
+ openGlBackend.RenderDrawData(ImGui.GetDrawData());
+ window.SwapBuffers();
+ }
+}
diff --git a/samples/Demo/DemoJolt.cs b/samples/Demo/DemoJolt.cs
new file mode 100644
index 0000000..75679ea
--- /dev/null
+++ b/samples/Demo/DemoJolt.cs
@@ -0,0 +1,256 @@
+/*
+ * DemoJolt
+ *
+ * Drops a pile of boxes onto the ground with Jolt Physics and draws them in 3D with OpenGL every
+ * frame: the visual counterpart of the headless Hello/HelloJolt.cs. Press Escape to close it.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Jolt@2026.10.4
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.OpenGl@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal;
+using Brutal.GlfwApi;
+using Brutal.JoltApi;
+using Brutal.Numerics;
+using Brutal.OpenGlApi;
+
+const ushort STATIC_LAYER = 0;
+const ushort MOVING_LAYER = 1;
+
+// Library-wide state, shut down in reverse even if Run throws: Jolt needs an allocator, a factory
+// and its types registered before it can simulate anything, and GLFW provides the window.
+Jolt.RegisterDefaultAllocator();
+Factory.Instance = Factory.Create();
+Jolt.RegisterTypes();
+try
+{
+ if (!Glfw.Init())
+ {
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+ }
+
+ try
+ {
+ Run();
+ }
+ finally
+ {
+ Glfw.Terminate();
+ }
+}
+finally
+{
+ Jolt.UnregisterTypes();
+ Factory.DestroyInstance();
+}
+
+// Everything else: its using declarations dispose in reverse, so the OpenGL objects and window go
+// first, then the bodies' shapes and settings, then the physics system and what it was built from.
+static void Run()
+{
+ // Physics: a job system and collision layers.
+ using var tempAllocator = TempAllocatorImpl.Create(10 * 1024 * 1024);
+ using var jobSystem = JobSystemThreadPool.Create(2048, 8, -1);
+
+ using var broadPhaseLayers = BroadPhaseLayerInterfaceTable.Create(2, 2);
+ broadPhaseLayers.MapObjectToBroadPhaseLayer(STATIC_LAYER, 0);
+ broadPhaseLayers.MapObjectToBroadPhaseLayer(MOVING_LAYER, 1);
+
+ using var pairFilter = ObjectLayerPairFilterTable.Create(2);
+ pairFilter.EnableCollision(STATIC_LAYER, MOVING_LAYER);
+ pairFilter.EnableCollision(MOVING_LAYER, MOVING_LAYER);
+
+ using var broadPhaseFilter = ObjectVsBroadPhaseLayerFilterTable.Create(broadPhaseLayers, 2, pairFilter, 2);
+
+ using var physicsSystem = PhysicsSystem.Create();
+ physicsSystem.Init(1024, 0, 1024, 1024, broadPhaseLayers, broadPhaseFilter, pairFilter);
+ var bodyInterface = physicsSystem.GetBodyInterface();
+
+ var bodies = new List<(uint Body, float3 HalfSize, float3 Color)>();
+
+ var groundHalfSize = new float3(8, 0.5f, 8);
+ using var groundShape = BoxShapeSettings.Create(groundHalfSize, 0.05f, default);
+ using var groundSettings = BodyCreationSettings.Create(
+ groundShape,
+ new float3(0, -0.5f, 0), // Top surface at y = 0.
+ floatQuat.Identity,
+ MotionType.Static,
+ STATIC_LAYER
+ );
+ var boxHalfSize = new float3(0.5f);
+ using var boxShape = BoxShapeSettings.Create(boxHalfSize, 0.05f, default);
+
+ // Bodies are IDs, not disposable: they're removed and destroyed at the end, before their shapes
+ // and the physics system are disposed.
+ bodies.Add(
+ (bodyInterface.CreateAndAddBody(groundSettings, Activation.DontActivate), groundHalfSize, new float3(0.6f))
+ );
+
+ for (var i = 0; i < 20; i++)
+ {
+ using var boxSettings = BodyCreationSettings.Create(
+ boxShape,
+ new float3(-1.5f + i % 3 * 1.5f, 3 + i * 1.2f, -1.5f + i % 2 * 1.5f),
+ floatQuat.CreateFromYawPitchRoll(i * 0.5f, i * 0.3f, i * 0.7f),
+ MotionType.Dynamic,
+ MOVING_LAYER
+ );
+ var body = bodyInterface.CreateAndAddBody(boxSettings, Activation.Activate);
+ bodies.Add((body, boxHalfSize, new float3(1.0f - i / 20f, 0.5f, i / 20f)));
+ }
+
+ // Window and OpenGL, as in Hello/HelloOpenGl.cs.
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
+ Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
+
+ if (Platform.IsMacOS)
+ Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
+
+ // A fixed size keeps the viewport and aspect ratio valid.
+ Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
+
+ using var window = Glfw.CreateWindow(new GlfwWindow.CreateInfo { Title = "Demo Jolt", Size = new int2(640, 480) });
+
+ window.MakeContextCurrent();
+ Glfw.SwapInterval(1);
+
+ unsafe
+ {
+ if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
+ throw new InvalidOperationException("Failed to initialize OpenGL");
+ }
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ using var vertexShader = OpenGl
+ .CreateShader(GlShaderType.Vertex)
+ .SetSource(
+ """
+ #version 410 core
+ layout (location = 0) in vec3 aPos;
+ layout (location = 1) in vec3 aNormal;
+ uniform mat4 model;
+ uniform mat4 viewProjection;
+ out vec3 normal;
+ void main()
+ {
+ normal = mat3(model) * aNormal;
+ gl_Position = viewProjection * model * vec4(aPos, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var fragmentShader = OpenGl
+ .CreateShader(GlShaderType.Fragment)
+ .SetSource(
+ """
+ #version 410 core
+ in vec3 normal;
+ uniform vec3 color;
+ out vec4 FragColor;
+ void main()
+ {
+ // Simple directional light plus a little ambient.
+ float light = max(dot(normalize(normal), normalize(vec3(0.4, 1.0, 0.6))), 0.0);
+ FragColor = vec4(color * (0.3 + 0.7 * light), 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var program = OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
+
+ // A cube from -1 to 1: two triangles per face, each vertex with a position and a face normal.
+ var cube = new List();
+ foreach (
+ var normal in new[] { float3.UnitX, -float3.UnitX, float3.UnitY, -float3.UnitY, float3.UnitZ, -float3.UnitZ }
+ )
+ {
+ var u = new float3(normal.Y, normal.Z, normal.X);
+ var v = float3.Cross(normal, u);
+ float2[] corners = [new(-1, -1), new(1, -1), new(1, 1), new(-1, -1), new(1, 1), new(-1, 1)];
+ foreach (var corner in corners)
+ cube.Add(new Vertex(normal + u * corner.X + v * corner.Y, normal));
+ }
+
+ // Vertex arrays and buffers aren't disposable, so they're deleted at the end, while the
+ // window's context still exists.
+ var vertexArray = OpenGl.GenVertexArray().Bind();
+ var vertexBuffer = OpenGl.GenBuffer();
+ vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
+ OpenGl.BufferData(GlBindTarget.ArrayBuffer, cube.ToArray(), GlBufferUsage.StaticDraw);
+
+ OpenGl.VertexAttribute(new GlAttribute(0, 3, OpenGl.GL_FLOAT, GlScaling.Float, 6 * sizeof(float), 0));
+ OpenGl.VertexAttribute(
+ new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 6 * sizeof(float), 3 * sizeof(float))
+ );
+ OpenGl.EnableVertexAttribArray(0);
+ OpenGl.EnableVertexAttribArray(1);
+
+ OpenGl.Enable(GlCapability.DepthTest);
+ OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
+
+ var view = float4x4.CreateLookAt(new float3(8, 7, 12), new float3(0, 1.5f, 0), float3.UnitY);
+ var projection = float4x4.CreatePerspectiveFieldOfView(float.DegreesToRadians(45), 640f / 480f, 0.1f, 100f);
+
+ const float TIME_STEP = 1.0f / 60.0f;
+ var previousTime = Glfw.Time;
+ var accumulator = 0.0;
+
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+
+ // Step physics at a fixed rate whatever the refresh rate, capping the catch-up after a stall.
+ var now = Glfw.Time;
+ accumulator += Math.Min(now - previousTime, 0.25);
+ previousTime = now;
+ while (accumulator >= TIME_STEP)
+ {
+ physicsSystem.Update(TIME_STEP, 1, tempAllocator, jobSystem);
+ accumulator -= TIME_STEP;
+ }
+
+ OpenGl.Clear(GlClearBit.Color | GlClearBit.Depth);
+ program.Use();
+ program.Uniform("viewProjection"u8, view * projection);
+ vertexArray.Bind();
+
+ foreach (var (body, halfSize, color) in bodies)
+ {
+ bodyInterface.GetPositionAndRotation(body, out var position, out var rotation);
+ var model =
+ float4x4.CreateScale(halfSize)
+ * float4x4.CreateFromQuaternion(rotation)
+ * float4x4.CreateTranslation(position);
+
+ program.Uniform("model"u8, model);
+ program.Uniform("color"u8, color);
+ OpenGl.Draw(GlTopology.Triangles, cube.Count, 1, 0, 0);
+ }
+
+ window.SwapBuffers();
+ }
+
+ OpenGl.DeleteVertexArrays([vertexArray]);
+ OpenGl.DeleteBuffers([vertexBuffer]);
+
+ foreach (var (body, _, _) in bodies)
+ {
+ bodyInterface.RemoveBody(body);
+ bodyInterface.DestroyBody(body);
+ }
+}
+
+record struct Vertex(float3 Position, float3 Normal);
diff --git a/samples/Demo/DemoRenderDoc.cs b/samples/Demo/DemoRenderDoc.cs
new file mode 100644
index 0000000..003ede9
--- /dev/null
+++ b/samples/Demo/DemoRenderDoc.cs
@@ -0,0 +1,191 @@
+/*
+ * DemoRenderDoc
+ *
+ * Draws the coloured triangle from Hello/HelloOpenGl.cs and captures a frame with RenderDoc when
+ * you press F12. Captures work when the app is launched from RenderDoc (Windows or Linux), or on
+ * Windows when RenderDoc is installed in its default folder; otherwise (always on macOS) it still
+ * draws and F12 just prints a hint. Press Escape to close it.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.OpenGl@2026.10.2
+#:package Ahwoo.Brutal.RenderDoc@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+#:package Ahwoo.Brutal.Strings@2026.10.2
+
+using Brutal;
+using Brutal.GlfwApi;
+using Brutal.Numerics;
+using Brutal.OpenGlApi;
+using Brutal.RenderDocApi;
+using Brutal.Strings;
+
+const string HINT = "RenderDoc isn't loaded: launch this app from RenderDoc (Windows or Linux) to capture frames.";
+
+// Load the in-app API before any graphics API is initialized, so RenderDoc sees every GL call.
+RenderDoc.Initialize();
+
+if (RenderDoc.IsAvailable)
+{
+ // F12 is handled below with TriggerCapture, so turn off RenderDoc's own capture keys.
+ RenderDoc.SetCaptureKeys([]);
+ Console.WriteLine($"RenderDoc {RenderDoc.Version} loaded, press F12 to capture a frame.");
+ Console.WriteLine($"Captures are written to {Utf8.GetString(RenderDoc.CaptureFilePathTemplate)}*.rdc");
+}
+else
+{
+ Console.WriteLine(HINT);
+}
+
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+try
+{
+ Run();
+}
+finally
+{
+ Glfw.Terminate();
+}
+
+static void Run()
+{
+ // Window, shaders and triangle, as in Hello/HelloOpenGl.cs.
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
+ Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
+
+ if (Platform.IsMacOS)
+ Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
+
+ // A fixed size keeps the viewport and aspect ratio valid.
+ Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
+
+ // Declared first so it's disposed last, after the GL objects that need its context.
+ using var window = Glfw.CreateWindow(
+ new GlfwWindow.CreateInfo { Title = "Demo RenderDoc", Size = new int2(640, 480) }
+ );
+
+ window.MakeContextCurrent();
+ Glfw.SwapInterval(1);
+
+ unsafe
+ {
+ if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
+ throw new InvalidOperationException("Failed to initialize OpenGL");
+ }
+
+ window.OnKey += (handle, key, _, action, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+
+ if (key != GlfwKey.F12 || action != GlfwKeyAction.Press)
+ return;
+
+ if (!RenderDoc.IsAvailable)
+ {
+ Console.WriteLine(HINT);
+ return;
+ }
+
+ // Captures the next frame that is presented with SwapBuffers.
+ RenderDoc.TriggerCapture();
+ };
+
+ // Declared after the window, so the program is deleted while the GL context still exists.
+ using var program = LinkProgram();
+
+ // The vertex array and buffer aren't IDisposable, so they're deleted at the end, while the window's
+ // GL context still exists.
+ var vertexArray = OpenGl.GenVertexArray().Bind();
+ var vertexBuffer = OpenGl.GenBuffer();
+ vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
+ OpenGl.BufferData(
+ GlBindTarget.ArrayBuffer,
+ new Vertex[]
+ {
+ new(new float2(0.0f, 0.5f), new float3(1.0f, 0.0f, 0.0f)),
+ new(new float2(0.5f, -0.5f), new float3(0.0f, 1.0f, 0.0f)),
+ new(new float2(-0.5f, -0.5f), new float3(0.0f, 0.0f, 1.0f)),
+ },
+ GlBufferUsage.StaticDraw
+ );
+
+ OpenGl.VertexAttribute(new GlAttribute(0, 2, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 0));
+ OpenGl.VertexAttribute(
+ new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 2 * sizeof(float))
+ );
+ OpenGl.EnableVertexAttribArray(0);
+ OpenGl.EnableVertexAttribArray(1);
+
+ OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
+
+ var captureCount = 0u;
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+ OpenGl.Clear(GlClearBit.Color);
+ program.Use();
+ vertexArray.Bind();
+ OpenGl.Draw(GlTopology.Triangles, 3, 1, 0, 0);
+ window.SwapBuffers();
+
+ // A finished capture (from F12 or the RenderDoc UI) is added to RenderDoc's capture list.
+ if (RenderDoc.IsAvailable && RenderDoc.NumCaptures > captureCount)
+ {
+ captureCount = RenderDoc.NumCaptures;
+ if (RenderDoc.TryGetCapture((int)captureCount - 1, out var path, out _))
+ Console.WriteLine($"Captured {path}");
+ }
+ }
+
+ OpenGl.DeleteVertexArrays([vertexArray]);
+ OpenGl.DeleteBuffers([vertexBuffer]);
+}
+
+// The shaders are only needed until the program is linked, so they are disposed on return.
+static GlProgram LinkProgram()
+{
+ using var vertexShader = OpenGl
+ .CreateShader(GlShaderType.Vertex)
+ .SetSource(
+ """
+ #version 410 core
+ layout (location = 0) in vec2 aPos;
+ layout (location = 1) in vec3 aColor;
+ out vec3 color;
+ void main()
+ {
+ color = aColor;
+ gl_Position = vec4(aPos, 0.0, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var fragmentShader = OpenGl
+ .CreateShader(GlShaderType.Fragment)
+ .SetSource(
+ """
+ #version 410 core
+ in vec3 color;
+ out vec4 FragColor;
+ void main()
+ {
+ FragColor = vec4(color, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ return OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
+}
+
+record struct Vertex(float2 Position, float3 Color);
diff --git a/samples/Demo/DemoSdl.cs b/samples/Demo/DemoSdl.cs
new file mode 100644
index 0000000..6e1d802
--- /dev/null
+++ b/samples/Demo/DemoSdl.cs
@@ -0,0 +1,134 @@
+/*
+ * DemoSdl
+ *
+ * Opens an SDL window and uses its add-ons: Sdl.Image saves and loads a PNG, Sdl.Mixer beeps
+ * when you press Space, and Sdl.Ttf draws text if you pass a font. Press Escape to close it.
+ *
+ * Optionally pass a font:
+ *
+ * dotnet run Demo/DemoSdl.cs -- path/to/font.ttf
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Sdl@2026.10.3
+#:package Ahwoo.Brutal.Sdl.Image@2026.10.3
+#:package Ahwoo.Brutal.Sdl.Mixer@2026.10.3
+#:package Ahwoo.Brutal.Sdl.Ttf@2026.10.3
+
+using Brutal.SdlApi;
+using Brutal.SdlApi.Image;
+using Brutal.SdlApi.Mixer;
+using Brutal.SdlApi.Ttf;
+
+const uint DEFAULT_PLAYBACK_DEVICE = 0xFFFFFFFFu; // SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK
+
+Sdl.Init.Initialize(SdlInitFlags.Video | SdlInitFlags.Audio);
+SdlTtf.Init();
+SdlMixer.Init();
+try
+{
+ Run(args);
+}
+finally
+{
+ SdlMixer.Quit();
+ SdlTtf.Quit();
+ Sdl.Init.Quit();
+}
+
+// Unsafe for the surface and rectangle pointers and the mixer's null spec.
+static unsafe void Run(string[] args)
+{
+ // Declared in dependency order, so the using declarations dispose them in reverse when Run returns: the
+ // track, tone and mixer, then the text, font, image, renderer and window.
+ using var window = Sdl.Video.CreateWindow("Demo Sdl", 640, 480, SdlWindowFlags.Resizable);
+ using var renderer = Sdl.Render.CreateRenderer(window, null!); // null picks the best available driver.
+ Sdl.Render.SetRenderVSync(renderer, 1);
+
+ // Sdl.Image: paint a gradient, save it as a PNG, then load it back as a texture.
+ var imagePath = Path.Combine(Path.GetTempPath(), "DemoSdl.png");
+ var surface = Sdl.PInvoke.CreateSurface(256, 256, SdlPixelFormat.Rgba8888);
+ for (var y = 0; y < 256; y++)
+ for (var x = 0; x < 256; x++)
+ Sdl.PInvoke.WriteSurfacePixel(surface, x, y, (byte)x, (byte)y, 128, 255);
+
+ SdlImage.SavePNG(surface, imagePath);
+ Sdl.PInvoke.DestroySurface(surface);
+ using var image = SdlImage.LoadTexture(renderer, imagePath);
+
+ // Sdl.Ttf: render text with a font, if one was given (dotnet run Demo/DemoSdl.cs -- path/to/font.ttf).
+ // Without one, the font and text stay default handles, which Dispose skips.
+ var hasFont = args.Length > 0;
+ using var font = hasFont ? SdlTtf.OpenFont(args[0], 32f) : default;
+ using var text = hasFont ? RenderText(renderer, font, "Demo Sdl Ttf") : default;
+ var textSize = (w: 0f, h: 0f);
+ if (hasFont)
+ Sdl.Render.GetTextureSize(text, out textSize.w, out textSize.h);
+
+ // Sdl.Mixer: a 440 Hz tone, played whenever Space is pressed (key auto-repeat is ignored).
+ using var mixer = SdlMixer.CreateMixerDevice(DEFAULT_PLAYBACK_DEVICE, null);
+ using var tone = mixer.CreateSineWaveAudio(440, 0.25f, 250);
+ using var track = mixer.CreateTrack();
+ track.SetAudio(tone);
+
+ var running = true;
+ while (running)
+ {
+ while (Sdl.Events.PollEvent(out var ev))
+ {
+ if (ev.type is SdlEventType.Quit or SdlEventType.WindowCloseRequested)
+ running = false;
+ else if (ev.type == SdlEventType.KeyDown && ev.key.scancode == SdlScancode.Escape)
+ running = false;
+ else if (ev.type == SdlEventType.KeyDown && ev.key.scancode == SdlScancode.Space && ev.key.repeat == 0)
+ track.Play(0);
+ }
+
+ Sdl.Render.SetRenderDrawColor(renderer, 51, 77, 77, 255);
+ Sdl.Render.RenderClear(renderer);
+ Sdl.Render.SetRenderDrawColor(renderer, 255, 255, 255, 255);
+ Sdl.Render.RenderDebugText(renderer, 16, 16, "Demo Sdl - press Space to beep");
+
+ var imageRect = new SdlFRect
+ {
+ x = 16,
+ y = 40,
+ w = 256,
+ h = 256,
+ };
+ Sdl.Render.RenderTexture(renderer, image, null, &imageRect);
+
+ if (hasFont)
+ {
+ var textRect = new SdlFRect
+ {
+ x = 16,
+ y = 312,
+ w = textSize.w,
+ h = textSize.h,
+ };
+ Sdl.Render.RenderTexture(renderer, text, null, &textRect);
+ }
+
+ Sdl.Render.RenderPresent(renderer);
+ }
+
+ static SdlTexture RenderText(SdlRenderer renderer, TtfFont font, string message)
+ {
+ var surface = SdlTtf.RenderTextBlended(
+ font,
+ message,
+ 0,
+ new SdlColor
+ {
+ r = 255,
+ g = 255,
+ b = 255,
+ a = 255,
+ }
+ );
+ var texture = Sdl.Render.CreateTextureFromSurface(renderer, surface);
+ Sdl.PInvoke.DestroySurface(surface);
+ return texture;
+ }
+}
diff --git a/samples/Demo/DemoTexturedQuad.cs b/samples/Demo/DemoTexturedQuad.cs
new file mode 100644
index 0000000..f27cae8
--- /dev/null
+++ b/samples/Demo/DemoTexturedQuad.cs
@@ -0,0 +1,241 @@
+/*
+ * DemoTexturedQuad
+ *
+ * Generates a checkerboard with four mip levels, each tinted a different colour, saves it as a
+ * KTX2 file, loads it back with TextureLoader and draws it on a floor quad with OpenGL. The tints
+ * show where the GPU switches mip level as the floor recedes. Press Escape to close it.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.Ktx@2026.10.2
+#:package Ahwoo.Brutal.OpenGl@2026.10.2
+#:package Ahwoo.Brutal.Texture@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using System.Runtime.InteropServices;
+using Brutal;
+using Brutal.GlfwApi;
+using Brutal.KtxApi;
+using Brutal.KtxApi.Abstractions;
+using Brutal.Numerics;
+using Brutal.OpenGlApi;
+using Brutal.TextureApi;
+using Brutal.TextureApi.Ktx;
+
+const int SIZE = 256;
+const int LEVELS = 4;
+
+// GLFW is the only library-wide state, set up here and terminated even if Run throws.
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+try
+{
+ Run();
+}
+finally
+{
+ Glfw.Terminate();
+}
+
+// Everything else: its using declarations dispose in reverse, the program and shaders, then the window.
+static void Run()
+{
+ // Texture: a KTX2 texture with room for every mip level, as in Hello/HelloKtx.cs.
+ var createInfo = new KtxTextureCreateInfo
+ {
+ VkFormat = (uint)VkFormat.R8G8B8A8Unorm,
+ BaseWidth = SIZE,
+ BaseHeight = SIZE,
+ BaseDepth = 1,
+ NumDimensions = 2,
+ NumLevels = LEVELS,
+ NumLayers = 1,
+ NumFaces = 1,
+ };
+
+ var createResult = KtxTexture2.Create(
+ ref createInfo,
+ KtxTextureCreateStorageEnum.TextureCreateAllocStorage,
+ out var ktxTexture
+ );
+ if (createResult != KtxErrorCode.Success)
+ throw new KtxTextureException($"Failed to create KTX2 texture: {createResult}", createResult);
+
+ // Only needed until it's written, so it's disposed at the end of this block.
+ var path = Path.Combine(Path.GetTempPath(), "DemoTexturedQuad.ktx2");
+ using (ktxTexture)
+ {
+ // Each level halves in size; the checker squares shrink with it so they line up across levels.
+ byte4[] tints = [new(255, 255, 255, 255), new(255, 96, 96, 255), new(96, 255, 96, 255), new(96, 96, 255, 255)];
+ for (var level = 0; level < LEVELS; level++)
+ {
+ var size = SIZE >> level;
+ var square = 32 >> level;
+ var texels = new byte4[size * size];
+ for (var y = 0; y < size; y++)
+ for (var x = 0; x < size; x++)
+ texels[y * size + x] = (x / square + y / square) % 2 == 0 ? tints[level] : new byte4(40, 40, 40, 255);
+
+ ktxTexture.SetImageFromMemory((uint)level, 0, 0, MemoryMarshal.AsBytes(texels.AsSpan()));
+ }
+
+ ktxTexture.WriteToNamedFile(path);
+ }
+ Console.WriteLine($"Wrote {path} ({new FileInfo(path).Length} bytes)");
+
+ // TextureLoader picks the KTX backend from the file extension, as in Hello/HelloTexture.cs.
+ var texture = TextureLoader.LoadFromFile(path);
+ Console.WriteLine($"Loaded {texture.Format}, {texture.Extent.X}x{texture.Extent.Y}, {texture.LevelCount} levels");
+
+ // Window and OpenGL, as in Hello/HelloOpenGl.cs.
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
+ Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
+
+ if (Platform.IsMacOS)
+ Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
+
+ // A fixed size keeps the viewport and aspect ratio valid.
+ Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
+
+ using var window = Glfw.CreateWindow(
+ new GlfwWindow.CreateInfo { Title = "Demo Textured Quad", Size = new int2(640, 480) }
+ );
+
+ window.MakeContextCurrent();
+ Glfw.SwapInterval(1);
+
+ unsafe
+ {
+ if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
+ throw new InvalidOperationException("Failed to initialize OpenGL");
+ }
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ // Upload every level we loaded instead of letting OpenGL generate its own mips.
+ GlTexture[] glTextures = [default];
+ OpenGl.GenTextures(glTextures);
+
+ // OpenGL textures, vertex arrays and buffers aren't disposable, so they're deleted at the end,
+ // while the window's context still exists.
+ OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, glTextures[0].Id);
+ for (var level = 0; level < texture.LevelCount; level++)
+ {
+ var size = texture.Extent.X >> level;
+ unsafe
+ {
+ fixed (byte* data = texture.ImageData(level, 0, 0))
+ OpenGl.TexImage2D(
+ OpenGl.GL_TEXTURE_2D,
+ level,
+ (int)OpenGl.GL_RGBA8,
+ size,
+ size,
+ 0,
+ OpenGl.GL_RGBA,
+ OpenGl.GL_UNSIGNED_BYTE,
+ data
+ );
+ }
+ }
+ TextureLoader.Unload(texture);
+
+ // TexParameterFloat with an int calls glTexParameteri; the name is a binding quirk (brutal.opengl#14).
+ OpenGl.TexParameterFloat(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MAX_LEVEL, LEVELS - 1);
+ OpenGl.TexParameterFloat(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MIN_FILTER, (int)OpenGl.GL_LINEAR_MIPMAP_LINEAR);
+ OpenGl.TexParameterFloat(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MAG_FILTER, (int)OpenGl.GL_LINEAR);
+
+ using var vertexShader = OpenGl
+ .CreateShader(GlShaderType.Vertex)
+ .SetSource(
+ """
+ #version 410 core
+ layout (location = 0) in vec3 aPos;
+ layout (location = 1) in vec2 aUv;
+ uniform mat4 viewProjection;
+ out vec2 uv;
+ void main()
+ {
+ uv = aUv;
+ gl_Position = viewProjection * vec4(aPos, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var fragmentShader = OpenGl
+ .CreateShader(GlShaderType.Fragment)
+ .SetSource(
+ """
+ #version 410 core
+ in vec2 uv;
+ uniform sampler2D tex;
+ out vec4 FragColor;
+ void main()
+ {
+ FragColor = texture(tex, uv);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var program = OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
+
+ // A floor quad (two triangles) on y = 0 that repeats the texture eight times along its length.
+ var vertexArray = OpenGl.GenVertexArray().Bind();
+ var vertexBuffer = OpenGl.GenBuffer();
+ vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
+ OpenGl.BufferData(
+ GlBindTarget.ArrayBuffer,
+ new Vertex[]
+ {
+ new(new float3(-2, 0, 2), new float2(0, 0)),
+ new(new float3(2, 0, 2), new float2(2, 0)),
+ new(new float3(2, 0, -14), new float2(2, 8)),
+ new(new float3(-2, 0, 2), new float2(0, 0)),
+ new(new float3(2, 0, -14), new float2(2, 8)),
+ new(new float3(-2, 0, -14), new float2(0, 8)),
+ },
+ GlBufferUsage.StaticDraw
+ );
+
+ OpenGl.VertexAttribute(new GlAttribute(0, 3, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 0));
+ OpenGl.VertexAttribute(
+ new GlAttribute(1, 2, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 3 * sizeof(float))
+ );
+ OpenGl.EnableVertexAttribArray(0);
+ OpenGl.EnableVertexAttribArray(1);
+
+ OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
+
+ var view = float4x4.CreateLookAt(new float3(0, 1, 3), new float3(0, 0, -4), float3.UnitY);
+ var projection = float4x4.CreatePerspectiveFieldOfView(float.DegreesToRadians(60), 640f / 480f, 0.1f, 100f);
+
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+ OpenGl.Clear(GlClearBit.Color);
+ program.Use();
+ program.Uniform("viewProjection"u8, view * projection);
+ vertexArray.Bind();
+ OpenGl.Draw(GlTopology.Triangles, 6, 1, 0, 0);
+ window.SwapBuffers();
+ }
+
+ OpenGl.DeleteVertexArrays([vertexArray]);
+ OpenGl.DeleteBuffers([vertexBuffer]);
+ OpenGl.DeleteTextures(glTextures);
+}
+
+record struct Vertex(float3 Position, float2 Uv);
diff --git a/samples/Demo/DemoVulkan.cs b/samples/Demo/DemoVulkan.cs
new file mode 100644
index 0000000..3ed09bc
--- /dev/null
+++ b/samples/Demo/DemoVulkan.cs
@@ -0,0 +1,485 @@
+/*
+ * DemoVulkan
+ *
+ * Draws a coloured triangle with Vulkan: raw bindings, the Vulkan.Abstractions helpers, and a
+ * vertex buffer allocated with VMA. Shaders are compiled at startup with ShaderC.
+ *
+ * Press Escape to close it.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Vulkan@2026.10.3
+#:package Ahwoo.Brutal.Vulkan.Abstractions@2026.10.3
+#:package Ahwoo.Brutal.Vulkan.Vma@2026.10.3
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.ShaderC@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Memory@2026.10.2
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+#:package Ahwoo.Brutal.Strings@2026.10.2
+
+using Brutal;
+using Brutal.GlfwApi;
+using Brutal.Numerics;
+using Brutal.ShaderCApi;
+using Brutal.Strings;
+using Brutal.VulkanApi;
+using Brutal.VulkanApi.Abstractions;
+using Brutal.VulkanApi.Vma;
+
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+// GLFW can't find Brutal's Vulkan loader (libVulkanEx, not libvulkan.1) by itself, so touching Vulkan first loads it.
+_ = Vulkan.GetInstanceProcAddr;
+
+try
+{
+ Run();
+}
+finally
+{
+ Glfw.Terminate();
+}
+
+static unsafe void Run()
+{
+ Glfw.WindowHint(GlfwWindowHint.ClientApi, Glfw.Constants.GLFW_NO_API);
+ Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE); // A fixed size means no swapchain rebuilds.
+
+ // Declared first so it's disposed last, after the surface and everything else that draws to it.
+ using var window = Glfw.CreateWindow(
+ new GlfwWindow.CreateInfo { Title = "Demo Vulkan", Size = new int2(640, 480) }
+ );
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ // VulkanHelpers adds whatever this OS needs (e.g. portability enumeration for MoltenVK).
+ var instanceExtensions = new HashSet();
+ VulkanHelpers.AddPlatformRequiredExtensions(instanceExtensions);
+ var glfwExtensions = Glfw.GetRequiredInstanceExtensions(out var glfwExtensionCount);
+ for (var i = 0; i < glfwExtensionCount; i++)
+ instanceExtensions.Add(Utf8.GetString(glfwExtensions[i]));
+
+ using var instance = Vulkan.CreateInstance(
+ new Instance.CreateInfo
+ {
+ // For dynamic rendering.
+ AppInfo = new VkApplicationInfo { ApiVersion = (int)VulkanHelpers.Api.VERSION_1_3 },
+ Flags = VulkanHelpers.GetPlatformRequiredInstanceCreateFlags(),
+ EnabledExtensions = instanceExtensions,
+ EnabledLayers = [],
+ }
+ );
+
+ if (Glfw.CreateWindowSurface(instance.VkHandle, window, out var surfaceHandle) != (int)VkResult.Success)
+ throw new InvalidOperationException("Failed to create a Vulkan surface for the window");
+ var surface = new VkSurfaceKHR((nint)surfaceHandle);
+
+ // One queue draws and presents, so find a device with a queue family that can do both.
+ PhysicalDevice? physicalDevice = null;
+ var queueFamily = -1;
+ foreach (var candidate in instance.PhysicalDevices)
+ {
+ var families = new VkQueueFamilyProperties[candidate.GetQueueFamilyProperties_Count()];
+ candidate.GetQueueFamilyProperties_Write(families);
+
+ for (var i = 0; i < families.Length && physicalDevice is null; i++)
+ {
+ if ((families[i].QueueFlags & VkQueueFlags.GraphicsBit) != 0 && candidate.GetSurfaceSupportKHR(i, surface))
+ (physicalDevice, queueFamily) = (candidate, i);
+ }
+ }
+
+ if (physicalDevice is null)
+ throw new InvalidOperationException(
+ "No Vulkan device has a queue family that can draw and present to the window"
+ );
+
+ var deviceExtensions = new HashSet();
+ VulkanHelpers.AddSwapchainExtensions(deviceExtensions);
+ VulkanHelpers.AddMandatoryIfSupportedDeviceExtensions(deviceExtensions, physicalDevice);
+
+ var priority = 1.0f;
+ var vulkan13Features = new VkPhysicalDeviceVulkan13Features { DynamicRendering = true };
+
+ using var device = physicalDevice.CreateDevice(
+ new DeviceEx.CreateInfo
+ {
+ Extensions = deviceExtensions,
+ QueueCreateInfos =
+ [
+ new VkDeviceQueueCreateInfo
+ {
+ QueueFamilyIndex = queueFamily,
+ QueueCount = 1,
+ QueuePriorities = &priority,
+ },
+ ],
+ Next = &vulkan13Features,
+ }
+ );
+
+ var queue = device.GetQueue(queueFamily, 0);
+
+ // VMA: allocate a host-visible, persistently mapped vertex buffer and write the triangle into it.
+ var allocator = device.CreateVmaAllocator(
+ new VmaAllocatorCreateInfo
+ {
+ Instance = instance,
+ PhysicalDevice = physicalDevice,
+ Device = device,
+ VulkanApiVersion = (uint)VulkanHelpers.Api.VERSION_1_3,
+ }
+ );
+
+ ReadOnlySpan vertices =
+ [
+ new(new float2(0.0f, -0.5f), new float3(1.0f, 0.0f, 0.0f)),
+ new(new float2(0.5f, 0.5f), new float3(0.0f, 1.0f, 0.0f)),
+ new(new float2(-0.5f, 0.5f), new float3(0.0f, 0.0f, 1.0f)),
+ ];
+ var verticesSize = ByteSize.Of(vertices);
+
+ allocator.CreateBuffer(
+ new VkBufferCreateInfo { Size = verticesSize, Usage = VkBufferUsageFlags.VertexBufferBit },
+ new VmaAllocationCreateInfo
+ {
+ Usage = VmaMemoryUsage.Auto,
+ Flags = VmaAllocationCreateFlags.HostAccessSequentialWriteBit | VmaAllocationCreateFlags.MappedBit,
+ },
+ out var vertexBuffer,
+ out var vertexAllocation,
+ out var vertexAllocationInfo
+ );
+
+ vertices.CopyTo(new Span((void*)vertexAllocationInfo.PMappedData, vertices.Length));
+ allocator.FlushAllocation(vertexAllocation, ByteSize.Zero, verticesSize); // A no-op on host-coherent memory.
+
+ // Swapchain: one image view per swapchain image.
+ var capabilities = physicalDevice.GetSurfaceCapabilitiesKHR(surface);
+
+ // CurrentExtent is 0xFFFFFFFF (-1 as an int) when the surface lets the swapchain pick its size.
+ var extent = capabilities.CurrentExtent;
+ if (extent.Width == -1 && extent.Height == -1)
+ extent = new VkExtent2D(
+ Math.Clamp(window.FramebufferSize.X, capabilities.MinImageExtent.Width, capabilities.MaxImageExtent.Width),
+ Math.Clamp(window.FramebufferSize.Y, capabilities.MinImageExtent.Height, capabilities.MaxImageExtent.Height)
+ );
+
+ // Ask for double buffering, within the surface's limits (a MaxImageCount of 0 means no limit).
+ var imageCount = Math.Max(capabilities.MinImageCount, 2);
+ if (capabilities.MaxImageCount > 0)
+ imageCount = Math.Min(imageCount, capabilities.MaxImageCount);
+
+ // Opaque if the surface supports it, otherwise the first mode it does support.
+ VkCompositeAlphaFlagsKHR[] alphaModes =
+ [
+ VkCompositeAlphaFlagsKHR.OpaqueBitKHR,
+ VkCompositeAlphaFlagsKHR.PreMultipliedBitKHR,
+ VkCompositeAlphaFlagsKHR.PostMultipliedBitKHR,
+ VkCompositeAlphaFlagsKHR.InheritBitKHR,
+ ];
+ var compositeAlpha = alphaModes.First(mode => (capabilities.SupportedCompositeAlpha & mode) != 0);
+
+ Span surfaceFormats =
+ stackalloc VkSurfaceFormatKHR[physicalDevice.GetSurfaceFormatsKHR_Count(surface)];
+ physicalDevice.GetSurfaceFormatsKHR_Write(surface, surfaceFormats);
+ var format = surfaceFormats[0].Format;
+
+ var swapchain = device.CreateSwapchainKHR(
+ new VkSwapchainCreateInfoKHR
+ {
+ Surface = surface,
+ MinImageCount = imageCount,
+ ImageFormat = format,
+ ImageColorSpace = surfaceFormats[0].ColorSpace,
+ ImageExtent = extent,
+ ImageArrayLayers = 1,
+ ImageUsage = VkImageUsageFlags.ColorAttachmentBit,
+ ImageSharingMode = VkSharingMode.Exclusive,
+ PreTransform = capabilities.CurrentTransform,
+ CompositeAlpha = compositeAlpha,
+ PresentMode = VkPresentModeKHR.FifoKHR,
+ Clipped = true,
+ },
+ null
+ );
+
+ var images = new VkImage[device.GetSwapchainImagesKHR_Count(swapchain)];
+ device.GetSwapchainImagesKHR_Write(swapchain, images);
+
+ var colorRange = new VkImageSubresourceRange
+ {
+ AspectMask = VkImageAspectFlags.ColorBit,
+ LevelCount = 1,
+ LayerCount = 1,
+ };
+ var imageViews = new VkImageView[images.Length];
+ for (var i = 0; i < images.Length; i++)
+ imageViews[i] = device.CreateImageView(
+ new VkImageViewCreateInfo
+ {
+ Image = images[i],
+ ViewType = VkImageViewType._2D,
+ Format = format,
+ SubresourceRange = colorRange,
+ },
+ null
+ );
+
+ // Shaders: positions and colours come from the vertex buffer.
+ using var compiler = ShaderC.CreateCompiler();
+ using var options = ShaderC.CreateCompilerOptions();
+
+ VkShaderModule CompileShader(ReadOnlySpan glsl, ShaderKind kind)
+ {
+ using var spirv = compiler.Compile(glsl, kind, "shader"u8, "main"u8, options);
+ return ShaderModuleExtensions.FromSpirv(
+ device,
+ new ReadOnlySpan(spirv.GetBytes(), (int)spirv.GetLength()),
+ null
+ );
+ }
+
+ // ShaderStages owns the modules and destroys them on Dispose.
+ using var shaderStages = new ShaderStages(
+ device,
+ [
+ Presets.ShaderStage.Vertex(
+ CompileShader(
+ """
+ #version 450
+
+ layout(location = 0) in vec2 position;
+ layout(location = 1) in vec3 inColor;
+ layout(location = 0) out vec3 color;
+
+ void main()
+ {
+ gl_Position = vec4(position, 0.0, 1.0);
+ color = inColor;
+ }
+ """u8,
+ ShaderKind.VertexShader
+ )
+ ),
+ Presets.ShaderStage.Fragment(
+ CompileShader(
+ """
+ #version 450
+
+ layout(location = 0) in vec3 color;
+ layout(location = 0) out vec4 outColor;
+
+ void main()
+ {
+ outColor = vec4(color, 1.0);
+ }
+ """u8,
+ ShaderKind.FragmentShader
+ )
+ ),
+ ],
+ null
+ );
+
+ // Pipeline: Presets cover the common fixed-function state.
+ // VertexInput builds the binding and attributes from the Vertex struct's fields.
+ var vertexInput = new VertexInput(1, 2).AddBindingWithAttributes(0, 0, VkVertexInputRate.Vertex);
+ var viewport = new VkViewport
+ {
+ Width = extent.Width,
+ Height = extent.Height,
+ MaxDepth = 1,
+ };
+ var scissor = new VkRect2D(extent);
+ var viewportState = new VkPipelineViewportStateCreateInfo
+ {
+ ViewportCount = 1,
+ Viewports = &viewport,
+ ScissorCount = 1,
+ Scissors = &scissor,
+ };
+ var rendering = new VkPipelineRenderingCreateInfo { ColorAttachmentCount = 1, ColorAttachmentFormats = &format };
+
+ var pipelineLayout = device.CreatePipelineLayout([], [], null);
+ var pipeline = device.CreateGraphicsPipeline(
+ VkPipelineCache.NullHandle,
+ new VkGraphicsPipelineCreateInfo
+ {
+ Next = &rendering,
+ StageCount = shaderStages.Count,
+ Stages = shaderStages,
+ VertexInputState = vertexInput,
+ InputAssemblyState = Presets.InputAssembly.TriangleList,
+ ViewportState = &viewportState,
+ RasterizationState = Presets.Rasterization.Fill.CullNone,
+ MultisampleState = Presets.Multisample.None,
+ ColorBlendState = Presets.BlendState.BlendNone,
+ Layout = pipelineLayout,
+ },
+ null
+ );
+
+ // Commands and synchronisation: one frame in flight.
+ var commandPool = device.CreateCommandPool(
+ new VkCommandPoolCreateInfo
+ {
+ QueueFamilyIndex = queueFamily,
+ Flags = VkCommandPoolCreateFlags.ResetCommandBufferBit,
+ },
+ null
+ );
+ var commandBuffer = device.AllocateCommandBuffer(
+ new VkCommandBufferAllocateInfo { CommandPool = commandPool, Level = VkCommandBufferLevel.Primary }
+ );
+
+ var imageAvailable = device.CreateSemaphore(new VkSemaphoreCreateInfo(), null);
+ var renderFinished = images.Select(_ => device.CreateSemaphore(new VkSemaphoreCreateInfo(), null)).ToArray();
+ var frameFence = device.CreateFence(VkFenceCreateFlags.SignaledBit, null);
+
+ void TransitionImage(
+ VkImage image,
+ VkImageLayout from,
+ VkImageLayout to,
+ VkPipelineStageFlags srcStage,
+ VkPipelineStageFlags dstStage,
+ VkAccessFlags srcAccess,
+ VkAccessFlags dstAccess
+ )
+ {
+ commandBuffer.PipelineBarrier(
+ srcStage,
+ dstStage,
+ VkDependencyFlags.None,
+ [],
+ [],
+ [
+ new VkImageMemoryBarrier
+ {
+ SrcAccessMask = srcAccess,
+ DstAccessMask = dstAccess,
+ OldLayout = from,
+ NewLayout = to,
+ SrcQueueFamilyIndex = VK.QUEUE_FAMILY_IGNORED,
+ DstQueueFamilyIndex = VK.QUEUE_FAMILY_IGNORED,
+ Image = image,
+ SubresourceRange = colorRange,
+ },
+ ]
+ );
+ }
+
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+
+ device.WaitForFence(frameFence, -1);
+ device.ResetFences([frameFence]);
+
+ // The window can't be resized, so the swapchain is never rebuilt: ErrorOutOfDateKHR throws here and a
+ // SuboptimalKHR result is ignored. A resizable window would recreate the swapchain in both cases.
+ device.AcquireNextImageKHR(swapchain, -1, imageAvailable, VkFence.NullHandle, out var imageIndex);
+ var image = images[imageIndex];
+
+ commandBuffer.Reset();
+ commandBuffer.Begin(VkCommandBufferUsageFlags.OneTimeSubmitBit);
+
+ TransitionImage(
+ image,
+ VkImageLayout.Undefined,
+ VkImageLayout.ColorAttachmentOptimal,
+ VkPipelineStageFlags.ColorAttachmentOutputBit,
+ VkPipelineStageFlags.ColorAttachmentOutputBit,
+ VkAccessFlags.None,
+ VkAccessFlags.ColorAttachmentWriteBit
+ );
+
+ var colorAttachment = new VkRenderingAttachmentInfo
+ {
+ ImageView = imageViews[imageIndex],
+ ImageLayout = VkImageLayout.ColorAttachmentOptimal,
+ LoadOp = VkAttachmentLoadOp.Clear,
+ StoreOp = VkAttachmentStoreOp.Store,
+ ClearValue = new VkClearColorValue { Float32 = new float4(0.1f, 0.1f, 0.1f, 1.0f) },
+ };
+
+ commandBuffer.BeginRendering(
+ new VkRenderingInfo
+ {
+ RenderArea = new VkRect2D(extent),
+ LayerCount = 1,
+ ColorAttachmentCount = 1,
+ ColorAttachments = &colorAttachment,
+ }
+ );
+ commandBuffer.BindPipeline(VkPipelineBindPoint.Graphics, pipeline);
+ commandBuffer.BindVertexBuffers(0, [vertexBuffer], [new ByteSize64(0)]);
+ commandBuffer.Draw(3, 1, 0, 0);
+ commandBuffer.EndRendering();
+
+ TransitionImage(
+ image,
+ VkImageLayout.ColorAttachmentOptimal,
+ VkImageLayout.PresentSrcKHR,
+ VkPipelineStageFlags.ColorAttachmentOutputBit,
+ VkPipelineStageFlags.BottomOfPipeBit,
+ VkAccessFlags.ColorAttachmentWriteBit,
+ VkAccessFlags.None
+ );
+
+ commandBuffer.End();
+
+ var signalSemaphore = renderFinished[imageIndex];
+ queue.Submit(
+ [imageAvailable],
+ [VkPipelineStageFlags.ColorAttachmentOutputBit],
+ [commandBuffer],
+ [signalSemaphore],
+ frameFence
+ );
+
+ queue.PresentKHR(
+ new VkPresentInfoKHR
+ {
+ WaitSemaphoreCount = 1,
+ WaitSemaphores = &signalSemaphore,
+ SwapchainCount = 1,
+ Swapchains = &swapchain,
+ ImageIndices = &imageIndex,
+ }
+ );
+ }
+
+ // The handles above aren't IDisposable, so they're destroyed here once the GPU is idle, before the
+ // using declarations dispose the shader stages, device, instance and window.
+ device.WaitIdle();
+
+ allocator.DestroyBuffer(vertexBuffer, vertexAllocation);
+ device.DestroyVmaAllocator(allocator);
+ device.DestroyFence(frameFence, null);
+ device.DestroySemaphore(imageAvailable, null);
+ foreach (var semaphore in renderFinished)
+ device.DestroySemaphore(semaphore, null);
+ device.DestroyCommandPool(commandPool, null);
+ device.DestroyPipeline(pipeline, null);
+ device.DestroyPipelineLayout(pipelineLayout, null);
+ foreach (var imageView in imageViews)
+ device.DestroyImageView(imageView, null);
+ device.DestroySwapchainKHR(swapchain, null);
+ instance.DestroySurfaceKHR(surface, null);
+}
+
+struct Vertex(float2 position, float3 color)
+{
+ public float2 Position = position;
+ public float3 Color = color;
+}
diff --git a/samples/Hello/HelloBox2D.cs b/samples/Hello/HelloBox2D.cs
new file mode 100644
index 0000000..fd75169
--- /dev/null
+++ b/samples/Hello/HelloBox2D.cs
@@ -0,0 +1,45 @@
+/*
+ * HelloBox2D
+ *
+ * Drops a box onto the ground with Box2D and prints where it is as it falls and comes to rest.
+ * See Demo/DemoBox2D.cs for a version that draws a stack of boxes with OpenGL.
+ */
+
+#:package Ahwoo.Brutal.Box2D@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal.Box2DApi;
+using Brutal.Numerics;
+
+Run();
+
+static void Run()
+{
+ // Default gravity is (0, -10). Disposing the world also destroys its bodies and shapes.
+ using var world = Box2D.CreateWorld(B2WorldDef.Default);
+
+ // A static ground whose top surface is at y = 0.
+ var ground = world.CreateBody(new B2BodyDef { Position = new float2(0, -0.5f) });
+ ground.CreatePolygonShape(B2ShapeDef.Default, Box2D.MakeBox(5, 0.5f));
+
+ // A 1x1 dynamic box, 4 units above the ground.
+ var box = world.CreateBody(new B2BodyDef { Type = B2BodyType.Dynamic, Position = new float2(0, 4) });
+ box.CreatePolygonShape(B2ShapeDef.Default, Box2D.MakeBox(0.5f, 0.5f));
+
+ // Two seconds at 60 Hz; the box should land and settle with its centre at y = 0.5.
+ const float TIME_STEP = 1.0f / 60.0f;
+ for (var step = 0; step <= 120; step++)
+ {
+ if (step > 0)
+ world.Step(TIME_STEP, 4);
+
+ if (step % 20 == 0)
+ {
+ var position = box.GetPosition();
+ Console.WriteLine(
+ $"t = {step * TIME_STEP:F2}s position = ({position.X:F2}, {position.Y:F2}) awake = {box.IsAwake()}"
+ );
+ }
+ }
+}
diff --git a/samples/Hello/HelloCollections.cs b/samples/Hello/HelloCollections.cs
new file mode 100644
index 0000000..bcd2e4d
--- /dev/null
+++ b/samples/Hello/HelloCollections.cs
@@ -0,0 +1,35 @@
+/*
+ * HelloCollections
+ *
+ * Uses NativeList, a growable list backed by unmanaged memory: add, insert,
+ * remove, iterate and edit it as a span.
+ */
+
+#:package Ahwoo.Brutal.Collections@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+
+// RIAN: This package will be greatly improved in an upcoming release of custom allocators, and collections that use them.
+
+using Brutal.Collections;
+
+Run();
+
+static void Run()
+{
+ // A List-like collection backed by unmanaged memory, freed when Run returns.
+ using var list = new NativeList();
+
+ list.Add(1);
+ list.AddRange([2, 3, 4, 5]);
+ list.Insert(0, 0);
+ list.RemoveAt(3);
+
+ Console.WriteLine($"Count = {(int)list.Count}, Capacity = {(int)list.Capacity}");
+
+ foreach (var value in list)
+ Console.WriteLine(value);
+
+ var span = list.AsSpan();
+ span.Reverse();
+ Console.WriteLine($"Reversed in place: {string.Join(", ", span.ToArray())}");
+}
diff --git a/samples/Hello/HelloConcurrency.cs b/samples/Hello/HelloConcurrency.cs
new file mode 100644
index 0000000..9a9df9b
--- /dev/null
+++ b/samples/Hello/HelloConcurrency.cs
@@ -0,0 +1,27 @@
+/*
+ * HelloConcurrency
+ *
+ * Runs a few jobs across worker threads with the JobScheduler and waits for them to finish.
+ */
+
+#:package Ahwoo.Brutal.Concurrency@2026.10.2
+
+// RIAN: This job system is finely-tuned for the way RW projects like to implement concurrency, and has limitations we should document at some stage.
+
+using Brutal.Concurrency.Jobs;
+
+var scheduler = new JobScheduler(3, "HelloScheduler");
+
+// The second argument is an estimated cost, used to balance jobs across worker threads.
+for (var i = 1; i <= 6; i++)
+ scheduler.Queue(new HelloJob(i), 10);
+
+scheduler.ExecuteJobs();
+scheduler.Wait();
+
+Console.WriteLine("All jobs finished");
+
+class HelloJob(int id) : IJob
+{
+ public void Run() => Console.WriteLine($"Job {id} running on thread {Environment.CurrentManagedThreadId}");
+}
diff --git a/samples/Hello/HelloCore.cs b/samples/Hello/HelloCore.cs
new file mode 100644
index 0000000..34893cb
--- /dev/null
+++ b/samples/Hello/HelloCore.cs
@@ -0,0 +1,29 @@
+/*
+ * HelloCore
+ *
+ * Shows a few Brutal.Core basics: platform detection, ByteSize/ElementCount arithmetic and Ptr.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Core@2026.10.4
+
+// RIAN: This package mainly contains the absolute bare minimum types and methods we use often across our packages.
+
+using Brutal;
+using Brutal.Pointers;
+
+Console.WriteLine($"Running on {Platform.CurrentFamily}");
+
+var stride = ByteSize.Of();
+var total = stride * new ElementCount(1024);
+Console.WriteLine($"1024 floats = {total}");
+
+var alternative = ByteSize.Of(1024);
+Console.WriteLine($"1024 floats = {alternative}");
+
+unsafe
+{
+ var raw = stackalloc int[4] { 10, 20, 30, 40 };
+ Ptr p = raw;
+ Console.WriteLine($"p.Value = {p.Value}, p[2] = {p[2]}, p.Offset(1).Value = {p.Offset(1).Value}");
+}
diff --git a/samples/Hello/HelloFmod.cs b/samples/Hello/HelloFmod.cs
new file mode 100644
index 0000000..bdb2f71
--- /dev/null
+++ b/samples/Hello/HelloFmod.cs
@@ -0,0 +1,53 @@
+/*
+ * HelloFmod
+ *
+ * Starts FMOD, prints its version and plays a 440 Hz tone from FMOD's built-in oscillator.
+ *
+ * FMOD natives are not bundled: put your licensed FMOD 2.03 Core library (fmod.dll, libfmod.so
+ * or libfmod.dylib) on the library search path (PATH on Windows, LD_LIBRARY_PATH on Linux,
+ * DYLD_LIBRARY_PATH on macOS), or this throws DllNotFoundException.
+ */
+
+#:package Ahwoo.Brutal.Fmod@2026.10.4
+#:package Ahwoo.Brutal.Core@2026.10.4
+
+// RIAN: It needs to be stressed that we do not provide FMOD binaries, and you must obtain them from the official FMOD website.
+
+using Brutal.FmodApi;
+
+// The FMOD system owns everything else; closing and releasing it frees anything left behind.
+var system = Fmod.SystemCreate(Fmod.VERSION);
+system.Init(32, InitFlags.Normal, 0);
+
+try
+{
+ Run(system);
+}
+finally
+{
+ system.Close();
+ system.Release();
+}
+
+static void Run(FmodSystem system)
+{
+ system.GetVersion(out var version, out _);
+ Console.WriteLine($"FMOD version: {version >> 16:x}.{(version >> 8) & 0xff:x2}.{version & 0xff:x2}");
+
+ var dsp = system.CreateDspByType(DspType.Oscillator); // Generates a sine wave by default.
+ dsp.SetParameterFloat((int)DspOscillator.Rate, 440.0f);
+
+ var channel = system.PlayDsp(dsp, default, false);
+ channel.SetVolume(0.5f);
+
+ Console.WriteLine("Playing a 440 Hz tone...");
+ for (var i = 0; i < 100; i++)
+ {
+ system.Update();
+ Thread.Sleep(10);
+ }
+
+ // Channels and DSPs aren't IDisposable, so stop and release them by hand.
+ channel.Stop();
+ dsp.Release();
+}
diff --git a/samples/Hello/HelloGlfw.cs b/samples/Hello/HelloGlfw.cs
new file mode 100644
index 0000000..9a0b3d7
--- /dev/null
+++ b/samples/Hello/HelloGlfw.cs
@@ -0,0 +1,49 @@
+/*
+ * HelloGlfw
+ *
+ * Opens an empty GLFW window with no graphics API. Press Escape to close it.
+ */
+
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal.GlfwApi;
+using Brutal.Numerics;
+
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+try
+{
+ Run();
+}
+finally
+{
+ Glfw.Terminate();
+}
+
+static void Run()
+{
+ // Destroyed when Run returns, before GLFW is terminated.
+ using var window = Glfw.CreateWindow(
+ new GlfwWindow.CreateInfo
+ {
+ Title = "Hello Glfw",
+ Size = new int2(640, 480),
+ Monitor = GlfwMonitor.Null, // Windowed mode.
+ Share = null, // No shared context.
+ }
+ );
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ while (!window.ShouldClose)
+ Glfw.PollEvents();
+}
diff --git a/samples/Hello/HelloGli.cs b/samples/Hello/HelloGli.cs
new file mode 100644
index 0000000..b1e1dec
--- /dev/null
+++ b/samples/Hello/HelloGli.cs
@@ -0,0 +1,49 @@
+/*
+ * HelloGli
+ *
+ * Creates a texture with a full mip chain using GLI, saves it as a .dds and loads it back.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Gli@2026.10.2
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+// RIAN: This package may be deprecated in the future, as the extensions it supports may be covered by better packages.
+
+using Brutal.GliApi;
+using Brutal.Numerics;
+
+Run();
+
+static void Run()
+{
+ var extent = new int3(64, 64, 1);
+
+ // A 2D RGBA texture with a full mip chain (64x64 down to 1x1).
+ using var texture = new Gli.Texture(
+ Gli.Target._2D,
+ Gli.Format.RGBA8_UNorm_Pack8,
+ extent,
+ 1,
+ 1,
+ 7,
+ Gli.Swizzles.Identity
+ );
+
+ unsafe
+ {
+ // Only the top mip level is filled; the smaller levels are left empty.
+ new Span(texture.ImageData(0), extent.X * extent.Y).Fill(new byte4(255, 128, 0, 255));
+ }
+
+ var path = Path.Combine(Path.GetTempPath(), "HelloGli.dds");
+ texture.Save(path);
+ Console.WriteLine($"Wrote {path}");
+
+ using var loaded = new Gli.Texture(path);
+ Console.WriteLine($"Loaded {loaded.Target} {loaded.Format}, {loaded.Levels} levels, {loaded.Size} bytes");
+ for (var level = 0; level < loaded.Levels; level++)
+ Console.WriteLine(
+ $" Level {level}: {loaded.ImageExtent(level).X}x{loaded.ImageExtent(level).Y}, {loaded.ImageSize(level)} bytes"
+ );
+}
diff --git a/samples/Hello/HelloGltf.cs b/samples/Hello/HelloGltf.cs
new file mode 100644
index 0000000..238312f
--- /dev/null
+++ b/samples/Hello/HelloGltf.cs
@@ -0,0 +1,50 @@
+/*
+ * HelloGltf
+ *
+ * Parses a tiny inline glTF (one triangle), reads its vertex positions and saves it back out.
+ */
+
+// Brutal.Gltf uses reflection-based System.Text.Json, which Native AOT (the default for
+// file-based apps) disables.
+#:property PublishAot=false
+#:package Ahwoo.Brutal.Gltf@2026.10.3
+
+using System.Runtime.InteropServices;
+using Brutal.GltfApi;
+
+// A single triangle, with its vertex positions embedded as a base64 buffer.
+float[] positions = [0, 0, 0, 1, 0, 0, 0, 1, 0];
+var buffer = Convert.ToBase64String(MemoryMarshal.AsBytes(positions.AsSpan()));
+
+var json = $$"""
+{
+ "asset": { "version": "2.0" },
+ "scene": 0,
+ "scenes": [{ "nodes": [0] }],
+ "nodes": [{ "name": "Triangle", "mesh": 0 }],
+ "meshes": [{ "primitives": [{ "attributes": { "POSITION": 0 } }] }],
+ "buffers": [{ "uri": "data:application/octet-stream;base64,{{buffer}}", "byteLength": 36 }],
+ "bufferViews": [{ "buffer": 0, "byteLength": 36 }],
+ "accessors": [{ "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0] }]
+}
+""";
+
+var model = GltfUtility.DeserializeModelJson(json);
+Console.WriteLine(
+ $"glTF {model.Asset.Version}: {model.Scenes.Length} scene, {model.Nodes.Length} node, {model.Meshes.Length} mesh"
+);
+
+var node = model.Nodes[0];
+var accessor = model.Accessors[model.Meshes[node.Mesh!.Value].Primitives[0].Attributes["POSITION"]];
+
+// Reading from byte 0 works because this buffer holds only tightly packed positions; real files need the
+// accessor and buffer view offsets and stride (see ReadFloat3s in Demo/DemoGltfViewer.cs). The second
+// argument is the folder that relative buffer URIs are resolved against.
+var vertices = MemoryMarshal.Cast(model.LoadBinaryBuffer(0, Path.GetTempPath()));
+Console.WriteLine($"Node '{node.Name}' has {accessor.Count} vertices:");
+for (var i = 0; i < accessor.Count; i++)
+ Console.WriteLine($" ({vertices[i * 3]}, {vertices[i * 3 + 1]}, {vertices[i * 3 + 2]})");
+
+var path = Path.Combine(Path.GetTempPath(), "HelloGltf.gltf");
+model.SaveModel(path);
+Console.WriteLine($"Wrote {path}");
diff --git a/samples/Hello/HelloImGui.cs b/samples/Hello/HelloImGui.cs
new file mode 100644
index 0000000..be08edb
--- /dev/null
+++ b/samples/Hello/HelloImGui.cs
@@ -0,0 +1,115 @@
+/*
+ * HelloImGui
+ *
+ * Dear ImGui with its GLFW and OpenGL backends: some text, a button and a slider.
+ * Press Escape to close it. See Demo/DemoImGui.cs for FreeType fonts and ImPlot.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.ImGui@2026.10.3
+#:package Ahwoo.Brutal.ImGui.Backends@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+#:package Ahwoo.Brutal.OpenGl@2026.10.2
+
+// RIAN: Please look at this example carefully, especially how the SharedStorage is reset once per frame.
+// The shared storage (leveraged for allocation-free string interpolation) will OoM eventually if you don't.
+
+using Brutal;
+using Brutal.GlfwApi;
+using Brutal.ImGuiApi;
+using Brutal.ImGuiApi.Backends;
+using Brutal.Numerics;
+using Brutal.OpenGlApi;
+
+// GLFW and OpenGL are just the host here: a window and a GL context for ImGui to draw into.
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+var context = ImGui.CreateContext();
+
+try
+{
+ Run();
+}
+finally
+{
+ ImGui.DestroyContext(context);
+ Glfw.Terminate();
+}
+
+static void Run()
+{
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
+ Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
+
+ if (Platform.IsMacOS)
+ Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
+
+ // Declared first so it's disposed last: the backends below need the window and its GL context.
+ using var window = Glfw.CreateWindow(
+ new GlfwWindow.CreateInfo { Title = "Hello ImGui", Size = new int2(800, 600) }
+ );
+
+ window.MakeContextCurrent();
+ Glfw.SwapInterval(1); // Wait for vsync instead of drawing as fast as possible.
+
+ unsafe
+ {
+ if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
+ throw new InvalidOperationException("Failed to load OpenGL functions with GLAD");
+ }
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ ImGui.GetIO().IniFilename = null; // Don't write imgui.ini.
+
+ // ImGui.Backends: feed GLFW input to ImGui and render its draw lists with OpenGL.
+ using var glfwBackend = new GlfwBackend(window, GlfwBackend.ClientApi.OpenGL);
+ using var openGlBackend = new OpenGlBackend();
+
+ var clicks = 0;
+ var value = 0.5f;
+
+ OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
+
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+
+ glfwBackend.NewFrame();
+ openGlBackend.NewFrame();
+ ImGui.NewFrame();
+ // Recycle the scratch memory that interpolated ImGui strings ($"...") use, once per frame.
+ ImString.SharedStorage.Reset();
+
+ ImGui.SetNextWindowSize(new float2(400, 200), ImGuiCond.FirstUseEver);
+ if (ImGui.Begin("Hello ImGui"u8))
+ {
+ ImGui.Text("Hello from Dear ImGui!"u8);
+
+ if (ImGui.Button("Click me"u8))
+ clicks++;
+ ImGui.SameLine();
+ ImGui.Text($"Clicked {clicks} times");
+
+ ImGui.SliderFloat("Value"u8, ref value, 0f, 1f);
+ }
+ ImGui.End();
+
+ ImGui.Render();
+
+ OpenGl.Clear(GlClearBit.Color);
+ openGlBackend.RenderDrawData(ImGui.GetDrawData());
+ window.SwapBuffers();
+ }
+}
diff --git a/samples/Hello/HelloImGuiAbstractions.cs b/samples/Hello/HelloImGuiAbstractions.cs
new file mode 100644
index 0000000..8860513
--- /dev/null
+++ b/samples/Hello/HelloImGuiAbstractions.cs
@@ -0,0 +1,85 @@
+/*
+ * HelloImGuiAbstractions
+ *
+ * The in-game ConsoleWindow and its TerminalInterface: registers [TerminalAction] commands, runs
+ * a few command lines with typed arguments, then draws the console headless.
+ * See Hello/HelloImGui.cs for Dear ImGui on screen.
+ */
+
+#:package Ahwoo.Brutal.ImGui.Abstractions@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.ImGui@2026.10.3
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+// RIAN: This sample primarly showcases the console interface that all RW projects use.
+
+using Brutal.ImGuiApi;
+using Brutal.ImGuiApi.Abstractions;
+using Brutal.Numerics;
+
+var context = ImGui.CreateContext();
+
+try
+{
+ Run();
+}
+finally
+{
+ ImGui.DestroyContext(context);
+}
+
+static void Run()
+{
+ var io = ImGui.GetIO();
+ io.IniFilename = null; // Don't write imgui.ini.
+ io.DisplaySize = new float2(800, 600); // No window, so tell ImGui how big the screen is.
+ io.DeltaTime = 1f / 60f;
+
+ // Claim a renderer that handles texture requests so ImGui builds the font atlas during the frame.
+ // Nothing uploads it here, which is fine for a headless frame.
+ io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures;
+
+ // Disposed when Run returns, before the ImGui context is destroyed.
+ using var console = new ConsoleWindow();
+ console.DisableMessageFading();
+
+ // Commands are plain methods; the terminal parses arguments into their parameter types.
+ console.Terminal.RegisterCommand(Hello);
+ console.Terminal.RegisterCommand(Add);
+ console.Terminal.OnOutput += (message, type) => Say($"[{type}] {message}"); // Parse errors land here.
+
+ // What a player would type into the console; ';' separates commands on one line.
+ string[] lines = ["hello World", "add 2 3; add 40", "add two 3"];
+ foreach (var line in lines)
+ {
+ Console.WriteLine($"> {line}");
+ console.Submit(line);
+ }
+
+ // Draw the open console as a game would each frame; it sizes itself to its log, which takes a
+ // frame to measure, so draw two.
+ console.Show();
+ for (var frame = 0; frame < 2; frame++)
+ {
+ ImGui.NewFrame();
+ var viewport = ImGui.GetMainViewport();
+ console.Draw(viewport.Pos, viewport.Size, io.DeltaTime);
+ ImGui.Render();
+ }
+
+ var drawData = ImGui.GetDrawData();
+ Console.WriteLine($"Console drawn: {drawData.TotalVtxCount} vertices, {drawData.TotalIdxCount} indices");
+
+ // Print to the in-game console, and echo to stdout since there's no window to see it in.
+ void Say(string message)
+ {
+ console.Print(message);
+ Console.WriteLine(message);
+ }
+
+ [TerminalAction("hello", "Prints a greeting")]
+ void Hello(string name) => Say($"Hello, {name}!");
+
+ [TerminalAction("add", "Adds two integers")]
+ void Add(int a, int b = 2) => Say($"{a} + {b} = {a + b}");
+}
diff --git a/samples/Hello/HelloImGuiExtensions.cs b/samples/Hello/HelloImGuiExtensions.cs
new file mode 100644
index 0000000..6b9a1c4
--- /dev/null
+++ b/samples/Hello/HelloImGuiExtensions.cs
@@ -0,0 +1,114 @@
+/*
+ * HelloImGuiExtensions
+ *
+ * ImGuiEx widgets that bind straight to C# enums, driven headless by simulated mouse clicks.
+ * See Hello/HelloImGui.cs for Dear ImGui on screen.
+ */
+
+#:package Ahwoo.Brutal.ImGui.Extensions@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.ImGui@2026.10.3
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+// RIAN: This package contains small extras for ImGui that we like, but possibly needs a better name as it's very opinionated.
+
+using Brutal.ImGuiApi;
+using Brutal.ImGuiApi.Extensions;
+using Brutal.Numerics;
+
+var context = ImGui.CreateContext();
+
+try
+{
+ Run();
+}
+finally
+{
+ ImGui.DestroyContext(context);
+}
+
+static void Run()
+{
+ var io = ImGui.GetIO();
+ io.IniFilename = null; // Don't write imgui.ini.
+ io.DisplaySize = new float2(800, 600); // No window, so tell ImGui how big the screen is.
+ io.DeltaTime = 1f / 60f;
+
+ // Claim a renderer that handles texture requests so ImGui builds the font atlas during the frame.
+ // Nothing uploads it here, which is fine for a headless frame.
+ io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures;
+
+ var shape = Shape.Circle;
+ var layers = Layers.Ground;
+ var triangleCenter = float2.Zero;
+ var waterCenter = float2.Zero;
+
+ Console.WriteLine($"Before: shape = {shape}, layers = {layers}");
+
+ // No backend, so feed ImGui a click on "Triangle" then on "Water". A new window takes
+ // a frame to settle its layout, so the clicks start on frame 2.
+ for (var frame = 0; frame < 7; frame++)
+ {
+ switch (frame)
+ {
+ case 2:
+ io.AddMousePosEvent(triangleCenter.X, triangleCenter.Y);
+ io.AddMouseButtonEvent(0, true);
+ break;
+ case 4:
+ io.AddMousePosEvent(waterCenter.X, waterCenter.Y);
+ io.AddMouseButtonEvent(0, true);
+ break;
+ case 3:
+ case 5:
+ io.AddMouseButtonEvent(0, false);
+ break;
+ }
+
+ ImGui.NewFrame();
+
+ ImGui.Begin("Hello ImGui Extensions"u8);
+
+ // ImGuiEx widgets take the enum by ref, no casting to and from int.
+ ImGuiEx.RadioButton("Circle"u8, ref shape, Shape.Circle);
+ ImGui.SameLine();
+ ImGuiEx.RadioButton("Square"u8, ref shape, Shape.Square);
+ ImGui.SameLine();
+ ImGuiEx.RadioButton("Triangle"u8, ref shape, Shape.Triangle);
+ triangleCenter = (ImGui.GetItemRectMin() + ImGui.GetItemRectMax()) * 0.5f;
+
+ ImGuiEx.Combo("Shape"u8, ref shape, "Circle\0Square\0Triangle\0"u8);
+
+ // Works for [Flags] enums too: each checkbox toggles one bit.
+ ImGuiEx.CheckboxFlags("Ground"u8, ref layers, Layers.Ground);
+ ImGuiEx.CheckboxFlags("Water"u8, ref layers, Layers.Water);
+ waterCenter = (ImGui.GetItemRectMin() + ImGui.GetItemRectMax()) * 0.5f;
+ ImGuiEx.CheckboxFlags("Sky"u8, ref layers, Layers.Sky);
+
+ ImGui.End();
+
+ ImGui.Render();
+ }
+
+ Console.WriteLine($"After: shape = {shape}, layers = {layers}");
+
+ // Plus a few non-widget helpers, e.g. colour conversion on a float4.
+ var red = ImGuiEx.ColorConvertHSVtoRGB(new float4(0f, 1f, 1f, 1f));
+ Console.WriteLine($"HSV(0, 1, 1) -> RGB({red.X}, {red.Y}, {red.Z})");
+}
+
+enum Shape
+{
+ Circle,
+ Square,
+ Triangle,
+}
+
+[Flags]
+enum Layers
+{
+ None = 0,
+ Ground = 1,
+ Water = 2,
+ Sky = 4,
+}
diff --git a/samples/Hello/HelloImGuiFreeType.cs b/samples/Hello/HelloImGuiFreeType.cs
new file mode 100644
index 0000000..ff308b2
--- /dev/null
+++ b/samples/Hello/HelloImGuiFreeType.cs
@@ -0,0 +1,72 @@
+/*
+ * HelloImGuiFreeType
+ *
+ * Rasterises Dear ImGui's font atlas with FreeType instead of stb_truetype, headless, and
+ * prints the atlas size and glyph count. See Demo/DemoImGui.cs for FreeType fonts on screen.
+ *
+ * Optionally pass a font:
+ *
+ * dotnet run Hello/HelloImGuiFreeType.cs -- path/to/font.ttf
+ */
+
+#:package Ahwoo.Brutal.ImGui@2026.10.3
+#:package Ahwoo.Brutal.ImGui.FreeType@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+#:package Ahwoo.Brutal.Strings@2026.10.2
+
+using Brutal.ImGuiApi;
+using Brutal.ImGuiApi.FreeType;
+using Brutal.Numerics;
+using Brutal.Strings;
+
+var context = ImGui.CreateContext();
+
+try
+{
+ Run(args);
+}
+finally
+{
+ ImGui.DestroyContext(context);
+}
+
+static void Run(string[] args)
+{
+ var io = ImGui.GetIO();
+ io.IniFilename = null; // Don't write imgui.ini.
+ io.DisplaySize = new float2(800, 600); // No window, so tell ImGui how big the screen is.
+ io.DeltaTime = 1f / 60f;
+ io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures; // We "upload" the atlas ourselves below.
+
+ // ImGui.FreeType: swap the font loader before adding any fonts.
+ var fonts = io.Fonts;
+ fonts.SetFontLoader(ImGuiFreeType.GetFontLoader());
+ var font = args.Length > 0 ? fonts.AddFontFromFileTTF(args[0], 24f) : fonts.AddFontDefault();
+
+ // Glyphs are rasterised lazily, so draw some text to bake them into the atlas.
+ ImGui.NewFrame();
+ ImGui.PushFont(font, 24f);
+ ImGui.Begin("Hello ImGui FreeType"u8);
+ ImGui.Text("The quick brown fox jumps over the lazy dog 0123456789"u8);
+ ImGui.End();
+ ImGui.PopFont();
+ ImGui.Render();
+
+ // A real renderer would create a GPU texture here; just mark each one as uploaded.
+ var drawData = ImGui.GetDrawData();
+ for (var i = 0; i < drawData.Textures.Value.Count; i++)
+ {
+ var texture = drawData.Textures.Value[i];
+ if (texture.Status is ImTextureStatus.WantCreate or ImTextureStatus.WantUpdates)
+ {
+ texture.SetTexID(new ImTextureID(i + 1));
+ texture.SetStatus(ImTextureStatus.OK);
+ }
+ }
+
+ ImString loaderName = fonts.FontLoaderName; // A null-terminated UTF-8 name, owned by the atlas.
+ Console.WriteLine($"Font loader: {Utf8.GetString(loaderName)}");
+ Console.WriteLine($"Atlas: {fonts.TexData.Width}x{fonts.TexData.Height}, {fonts.TexData.Format}");
+ Console.WriteLine($"Glyphs baked at 24px: {font.GetFontBaked(24f).Glyphs.Count}");
+}
diff --git a/samples/Hello/HelloImPlot.cs b/samples/Hello/HelloImPlot.cs
new file mode 100644
index 0000000..5dc4036
--- /dev/null
+++ b/samples/Hello/HelloImPlot.cs
@@ -0,0 +1,77 @@
+/*
+ * HelloImPlot
+ *
+ * Plots a sine wave with ImPlot for one headless Dear ImGui frame and prints how much geometry
+ * it produced. See Demo/DemoImGui.cs for an ImPlot plot on screen.
+ */
+
+#:package Ahwoo.Brutal.ImGui@2026.10.3
+#:package Ahwoo.Brutal.ImPlot@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal.ImGuiApi;
+using Brutal.ImPlotApi;
+using Brutal.Numerics;
+
+var context = ImGui.CreateContext();
+
+// ImPlot keeps its own context alongside ImGui's.
+var plotContext = ImPlot.CreateContext();
+ImPlot.SetImGuiContext(context);
+
+try
+{
+ Run();
+}
+finally
+{
+ ImPlot.DestroyContext(plotContext);
+ ImGui.DestroyContext(context);
+}
+
+static void Run()
+{
+ var io = ImGui.GetIO();
+ io.IniFilename = null; // Don't write imgui.ini.
+ io.DisplaySize = new float2(800, 600); // No window, so tell ImGui how big the screen is.
+ io.DeltaTime = 1f / 60f;
+
+ // Claim a renderer that handles texture requests so ImGui builds the font atlas during the frame.
+ // Nothing uploads it here, which is fine for a headless frame.
+ io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures;
+
+ var xs = new float[200];
+ var ys = new float[200];
+ for (var i = 0; i < xs.Length; i++)
+ {
+ xs[i] = i * 0.05f;
+ ys[i] = MathF.Sin(xs[i]);
+ }
+
+ ImGui.NewFrame();
+
+ ImGui.SetNextWindowSize(new float2(500, 400));
+ ImGui.Begin("Hello ImPlot"u8);
+ if (ImPlot.BeginPlot("Sine Wave"u8, new float2(-1, -1))) // Fill the window.
+ {
+ // Auto-fit only kicks in on the next frame, so give this single frame its limits up front.
+ ImPlot.SetupAxesLimits(0, 10, -1.1, 1.1);
+ ImPlot.PlotLine("sin(x)"u8, xs, ys);
+ ImPlot.EndPlot();
+ }
+ ImGui.End();
+
+ ImGui.Render();
+
+ // A renderer would draw these; here we just count them.
+ var drawData = ImGui.GetDrawData();
+ var commands = 0;
+ for (var i = 0; i < drawData.CmdListsCount; i++)
+ commands += drawData.CmdLists[i].CmdBuffer.Count;
+
+ Console.WriteLine($"Plotted {xs.Length} points");
+ Console.WriteLine(
+ $"Draw data: {drawData.CmdListsCount} lists, {drawData.TotalVtxCount} vertices, {drawData.TotalIdxCount} indices, {commands} commands"
+ );
+}
diff --git a/samples/Hello/HelloJolt.cs b/samples/Hello/HelloJolt.cs
new file mode 100644
index 0000000..6710c4d
--- /dev/null
+++ b/samples/Hello/HelloJolt.cs
@@ -0,0 +1,98 @@
+/*
+ * HelloJolt
+ *
+ * Drops a box onto the ground with Jolt Physics and prints where it is as it falls and
+ * comes to rest. See Demo/DemoJolt.cs for a version that draws a pile of boxes in 3D with OpenGL.
+ */
+
+#:package Ahwoo.Brutal.Jolt@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal.JoltApi;
+using Brutal.Numerics;
+
+const ushort STATIC_LAYER = 0;
+const ushort MOVING_LAYER = 1;
+
+// Jolt needs an allocator, a factory and its types registered before anything else; Run creates the
+// job system and collision layers.
+Jolt.RegisterDefaultAllocator();
+Factory.Instance = Factory.Create();
+Jolt.RegisterTypes();
+
+try
+{
+ Run();
+}
+finally
+{
+ Jolt.UnregisterTypes();
+ Factory.DestroyInstance();
+}
+
+static void Run()
+{
+ // Declared in dependency order, so they're disposed in reverse when Run returns.
+ using var tempAllocator = TempAllocatorImpl.Create(10 * 1024 * 1024);
+ using var jobSystem = JobSystemThreadPool.Create(2048, 8, -1);
+
+ // One broad phase layer per object layer; moving objects collide with static ones and each other.
+ using var broadPhaseLayers = BroadPhaseLayerInterfaceTable.Create(2, 2);
+ broadPhaseLayers.MapObjectToBroadPhaseLayer(STATIC_LAYER, 0);
+ broadPhaseLayers.MapObjectToBroadPhaseLayer(MOVING_LAYER, 1);
+
+ using var pairFilter = ObjectLayerPairFilterTable.Create(2);
+ pairFilter.EnableCollision(STATIC_LAYER, MOVING_LAYER);
+ pairFilter.EnableCollision(MOVING_LAYER, MOVING_LAYER);
+
+ using var broadPhaseFilter = ObjectVsBroadPhaseLayerFilterTable.Create(broadPhaseLayers, 2, pairFilter, 2);
+
+ using var physicsSystem = PhysicsSystem.Create();
+ physicsSystem.Init(1024, 0, 1024, 1024, broadPhaseLayers, broadPhaseFilter, pairFilter);
+ var bodyInterface = physicsSystem.GetBodyInterface(); // Default gravity is (0, -9.81, 0).
+
+ // A static ground whose top surface is at y = 0.
+ using var groundShape = BoxShapeSettings.Create(new float3(5, 0.5f, 5), 0.05f, default);
+ using var groundSettings = BodyCreationSettings.Create(
+ groundShape,
+ new float3(0, -0.5f, 0),
+ floatQuat.Identity,
+ MotionType.Static,
+ STATIC_LAYER
+ );
+ var ground = bodyInterface.CreateAndAddBody(groundSettings, Activation.DontActivate);
+
+ // A 1x1x1 dynamic box, 4 units above the ground.
+ using var boxShape = BoxShapeSettings.Create(new float3(0.5f), 0.05f, default);
+ using var boxSettings = BodyCreationSettings.Create(
+ boxShape,
+ new float3(0, 4, 0),
+ floatQuat.Identity,
+ MotionType.Dynamic,
+ MOVING_LAYER
+ );
+ var box = bodyInterface.CreateAndAddBody(boxSettings, Activation.Activate);
+
+ // Two seconds at 60 Hz; the box should land and settle with its centre near y = 0.5.
+ // (Jolt allows a couple of centimetres of penetration, so expect about 0.48.)
+ const float TIME_STEP = 1.0f / 60.0f;
+ for (var step = 0; step <= 120; step++)
+ {
+ if (step > 0)
+ physicsSystem.Update(TIME_STEP, 1, tempAllocator, jobSystem);
+
+ if (step % 20 == 0)
+ {
+ var position = bodyInterface.GetPosition(box);
+ Console.WriteLine(
+ $"t = {step * TIME_STEP:F2}s position = ({position.X:F2}, {position.Y:F2}, {position.Z:F2}) active = {bodyInterface.IsActive(box)}"
+ );
+ }
+ }
+
+ // Bodies are IDs, not IDisposable: remove and destroy them while the physics system still exists.
+ bodyInterface.RemoveBody(box);
+ bodyInterface.DestroyBody(box);
+ bodyInterface.RemoveBody(ground);
+ bodyInterface.DestroyBody(ground);
+}
diff --git a/samples/Hello/HelloKtx.cs b/samples/Hello/HelloKtx.cs
new file mode 100644
index 0000000..8655e97
--- /dev/null
+++ b/samples/Hello/HelloKtx.cs
@@ -0,0 +1,57 @@
+/*
+ * HelloKtx
+ *
+ * Creates a KTX2 texture, fills it with a checkerboard, writes it to disk and loads it back.
+ */
+
+#:package Ahwoo.Brutal.Ktx@2026.10.2
+
+using Brutal.KtxApi;
+using Brutal.KtxApi.Abstractions;
+
+const int SIZE = 64;
+
+Run();
+
+static void Run()
+{
+ var createInfo = new KtxTextureCreateInfo
+ {
+ VkFormat = (uint)VkFormat.R8G8B8A8Unorm,
+ BaseWidth = SIZE,
+ BaseHeight = SIZE,
+ BaseDepth = 1,
+ NumDimensions = 2,
+ NumLevels = 1,
+ NumLayers = 1,
+ NumFaces = 1,
+ };
+
+ KtxTexture2.Create(ref createInfo, KtxTextureCreateStorageEnum.TextureCreateAllocStorage, out var texture);
+
+ var path = Path.Combine(Path.GetTempPath(), "HelloKtx.ktx2");
+
+ // The texture is only needed until it is written, so it is disposed at the end of this block.
+ using (texture)
+ {
+ // Fill mip level 0 with a checkerboard.
+ var pixels = new byte[SIZE * SIZE * 4];
+ for (var y = 0; y < SIZE; y++)
+ for (var x = 0; x < SIZE; x++)
+ pixels.AsSpan((y * SIZE + x) * 4, 4).Fill((x / 8 + y / 8) % 2 == 0 ? (byte)255 : (byte)0);
+
+ texture.SetImageFromMemory(0, 0, 0, pixels);
+ texture.WriteToNamedFile(path);
+ }
+
+ Console.WriteLine($"Wrote {path}");
+
+ KtxTexture2.CreateFromMemory(File.ReadAllBytes(path), KtxTextureCreateFlagBits.LoadImageDataBit, out var loaded);
+
+ using (loaded)
+ {
+ Console.WriteLine(
+ $"Loaded {loaded.BaseWidth}x{loaded.BaseHeight} {loaded.GetVkFormat()}, {loaded.NumLevels} level(s), {loaded.DataSize} bytes"
+ );
+ }
+}
diff --git a/samples/Hello/HelloLocalization.cs b/samples/Hello/HelloLocalization.cs
new file mode 100644
index 0000000..b4335f4
--- /dev/null
+++ b/samples/Hello/HelloLocalization.cs
@@ -0,0 +1,24 @@
+/*
+ * HelloLocalization
+ *
+ * Formats localised strings with named variables, then swaps in a French translation.
+ */
+
+#:package Ahwoo.Brutal.Localization@2026.10.3
+
+using System.Diagnostics.CodeAnalysis;
+using Brutal.Localization;
+
+var greeting = LStrings.Create("Greeting", "Hello {NAME}, you have {COUNT} new messages");
+
+Console.WriteLine(greeting.Format("Alice", 3));
+
+// A string provider supplies the localized text; replacement variables may be reordered.
+var french = new Dictionary { ["Greeting"] = "{COUNT} nouveaux messages pour vous, {NAME}" };
+
+bool FrenchProvider(LString lString, [NotNullWhen(true)] out string? text) =>
+ french.TryGetValue(lString.Id.ToString(), out text);
+
+LStrings.SetLocalizedStringProvider(FrenchProvider);
+
+Console.WriteLine(greeting.Format("Alice", 3));
diff --git a/samples/Hello/HelloLogging.cs b/samples/Hello/HelloLogging.cs
new file mode 100644
index 0000000..a31e8d3
--- /dev/null
+++ b/samples/Hello/HelloLogging.cs
@@ -0,0 +1,28 @@
+/*
+ * HelloLogging
+ *
+ * Sets up logging to the console and writes messages to the default and a named category.
+ */
+
+#:package Ahwoo.Brutal.Logging@2026.10.3
+
+// RIAN: This is a very-very thin wrapper around Microsoft.Extensions.Logging, but it provides a simpler API and a default category for quick logging.
+
+using Brutal.Logging;
+using Microsoft.Extensions.Logging;
+using static Brutal.Logging.DefaultCategory;
+
+LogSystem.Initialize(builder =>
+{
+ builder.SetMinimumLevel(LogLevel.Trace);
+ builder.AddConsole();
+});
+
+// The default "Log" category.
+Log.Info("Hello from Brutal.Logging");
+Log.Warning($"The answer is {42}");
+
+// Named categories group messages by system.
+var network = LogCategory.Make("Network");
+network.Debug("Connecting...");
+network.Error("Connection refused");
diff --git a/samples/Hello/HelloMaths.cs b/samples/Hello/HelloMaths.cs
new file mode 100644
index 0000000..f372370
--- /dev/null
+++ b/samples/Hello/HelloMaths.cs
@@ -0,0 +1,24 @@
+/*
+ * HelloMaths
+ *
+ * Uses the Random extensions to generate numbers, points in shapes and random directions.
+ */
+
+#:package Ahwoo.Brutal.Maths@2026.10.3
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+// RIAN: This library will be expanded in a future release, once the System.Numerics mirror is pulled out of Brutal.Numerics into its own flavor package
+// We don't actually like the System.Numerics functions all that much, we only have them as compatibility at this stage.
+
+using Brutal.Maths;
+using Brutal.Numerics;
+
+var random = new Random(1234); // Fixed seed so every run prints the same values.
+
+Console.WriteLine($"Float in [5, 10): {random.NextSingle(5f, 10f)}");
+Console.WriteLine($"Point in 4x2 rect: {random.NextSinglePointInRectangle(4f, 2f)}");
+Console.WriteLine($"Point in unit circle: {random.NextSinglePointInCircle(1f)}");
+Console.WriteLine($"Point in unit sphere: {random.NextSinglePointInSphere(1f)}");
+
+var direction = random.NextSingleUnit3();
+Console.WriteLine($"Random direction: {direction} (length {direction.Length()})");
diff --git a/samples/Hello/HelloMemory.cs b/samples/Hello/HelloMemory.cs
new file mode 100644
index 0000000..1d08f7f
--- /dev/null
+++ b/samples/Hello/HelloMemory.cs
@@ -0,0 +1,31 @@
+/*
+ * HelloMemory
+ *
+ * Allocates, uses and frees unmanaged memory with Mem, and owns a pointer with PtrOwner.
+ */
+
+#:package Ahwoo.Brutal.Memory@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+
+// RIAN: This package is due for a big update for custom allocators.
+
+using Brutal;
+using Brutal.Memory;
+
+Run();
+
+static void Run()
+{
+ // Allocate 8 ints of unmanaged memory and use it as a Span. It isn't owned by anything, so free it yourself.
+ var numbers = Mem.AllocZeroed(new ElementCount(8));
+ for (var i = 0; i < numbers.Length; i++)
+ numbers[i] = i * i;
+
+ Console.WriteLine($"Squares: {string.Join(", ", numbers.ToArray())}");
+ Console.WriteLine($"Allocated {ByteSize.Of(numbers)} unmanaged");
+ Mem.Free(numbers);
+
+ // PtrOwner frees its allocation when disposed.
+ using var pi = new PtrOwner(Math.PI);
+ Console.WriteLine($"PtrOwner holds {pi.Value}");
+}
diff --git a/samples/Hello/HelloMeshOptimizer.cs b/samples/Hello/HelloMeshOptimizer.cs
new file mode 100644
index 0000000..184f646
--- /dev/null
+++ b/samples/Hello/HelloMeshOptimizer.cs
@@ -0,0 +1,40 @@
+/*
+ * HelloMeshOptimizer
+ *
+ * Shuffles a grid mesh's triangles, reorders them with meshoptimizer and compares cache efficiency.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.MeshOptimizer@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+
+using Brutal.MeshOptimizer;
+
+const int GRID_SIZE = 32;
+const int VERTEX_COUNT = (GRID_SIZE + 1) * (GRID_SIZE + 1);
+
+// Build a grid of triangles, then shuffle them to make a cache-unfriendly index buffer.
+var triangles = new List();
+for (var y = 0; y < GRID_SIZE; y++)
+for (var x = 0; x < GRID_SIZE; x++)
+{
+ var i = y * (GRID_SIZE + 1) + x;
+ triangles.Add([i, i + 1, i + GRID_SIZE + 1]);
+ triangles.Add([i + 1, i + GRID_SIZE + 2, i + GRID_SIZE + 1]);
+}
+
+var indices = triangles.OrderBy(_ => Random.Shared.Next()).SelectMany(t => t).ToArray();
+
+unsafe
+{
+ fixed (int* p = indices)
+ {
+ // AnalyzeVertexCache arguments: cache size 16, warp size 0, primitive group size 0.
+ var before = MeshOptimizer.AnalyzeVertexCache(p, indices.Length, VERTEX_COUNT, 16, 0, 0);
+ MeshOptimizer.OptimizeVertexCache(p, p, indices.Length, VERTEX_COUNT);
+ var after = MeshOptimizer.AnalyzeVertexCache(p, indices.Length, VERTEX_COUNT, 16, 0, 0);
+
+ Console.WriteLine($"{indices.Length / 3} triangles, {VERTEX_COUNT} vertices");
+ Console.WriteLine($"ACMR (vertex transforms per triangle): {before.Acmr:F2} -> {after.Acmr:F2}");
+ }
+}
diff --git a/samples/Hello/HelloMonitorHost.cs b/samples/Hello/HelloMonitorHost.cs
new file mode 100644
index 0000000..2721c18
--- /dev/null
+++ b/samples/Hello/HelloMonitorHost.cs
@@ -0,0 +1,41 @@
+/*
+ * HelloMonitorHost
+ *
+ * Starts the Monitor (a crash/log watchdog subprocess), logs a few lines to a file and prints them.
+ */
+
+#:package Ahwoo.Brutal.Monitor.Host@2026.10.3
+#:package Ahwoo.Brutal.Monitor.Common@2026.10.3
+
+// RIAN: We use this package for crash detection and dump collection at runtime.
+
+using Brutal.Monitor.Common;
+using Microsoft.Extensions.Logging;
+using Monitor = Brutal.Monitor.Monitor;
+
+Run();
+
+static void Run()
+{
+ var logDirectory = Path.Combine(Path.GetTempPath(), "HelloMonitor");
+ Directory.CreateDirectory(logDirectory);
+
+ string? logFile;
+
+ // Disposing the monitor flushes the log and stops the subprocess, so the log is read after this block.
+ using (var monitor = new Monitor("HelloMonitor")) // Starts the watchdog subprocess.
+ {
+ monitor.AddLogger(new LoggerOptions { LogDirectory = logDirectory });
+
+ var logger = monitor.LogProvider.CreateLogger("Hello");
+ logger.LogInformation("Hello from the Monitor host!");
+ for (var i = 0; i < 3; i++)
+ logger.LogWarning("Tick {Tick}", i);
+
+ logFile = monitor.LogProvider.LogFilePath;
+ Console.WriteLine($"Subprocess running: {monitor.SubprocessRunning}");
+ }
+
+ Console.WriteLine($"Log written to {logFile}:");
+ Console.WriteLine(File.ReadAllText(logFile!));
+}
diff --git a/samples/Hello/HelloNativeFileDialog.cs b/samples/Hello/HelloNativeFileDialog.cs
new file mode 100644
index 0000000..d6d448c
--- /dev/null
+++ b/samples/Hello/HelloNativeFileDialog.cs
@@ -0,0 +1,34 @@
+/*
+ * HelloNativeFileDialog
+ *
+ * Opens the operating system's native file picker and prints the file you chose.
+ */
+
+#:package Ahwoo.Brutal.NativeFileDialog@2026.10.3
+
+// RIAN: We only use this package for tooling, we prefer in-game file pickers for games.
+
+using Brutal.NativeFileDialogApi;
+
+NativeFileDialog.Initialize();
+try
+{
+ Run();
+}
+finally
+{
+ NativeFileDialog.Shutdown();
+}
+
+static void Run()
+{
+ var path = NativeFileDialog.OpenDialog(
+ new FileDialogInfo { FilterList = [new FilterItem { Name = "Text files", Spec = "txt,md" }] },
+ out var result
+ );
+
+ if (result == NativeFileDialog.Result.Okay)
+ Console.WriteLine($"You picked: {path}");
+ else
+ Console.WriteLine($"No file picked ({result})");
+}
diff --git a/samples/Hello/HelloNotCurses.cs b/samples/Hello/HelloNotCurses.cs
new file mode 100644
index 0000000..1d12375
--- /dev/null
+++ b/samples/Hello/HelloNotCurses.cs
@@ -0,0 +1,29 @@
+/*
+ * HelloNotCurses
+ *
+ * Draws coloured text with notcurses and waits for a key. Run it in a real terminal.
+ */
+
+#:package Ahwoo.Brutal.NotCurses@2026.10.1
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+// RIAN: I'm the only one who uses this for tooling, please don't use it in your server applications.
+
+using Brutal.NotCursesApi;
+using Brutal.Numerics;
+
+Run();
+
+static void Run()
+{
+ using var nc = NotCursesHandle.Init(); // Takes over the terminal until disposed.
+
+ var plane = nc.StdPlane();
+ plane.SetFgRgb(0x66DD55);
+ plane.PutStr(new int2(2, 1), $"Hello from notcurses {NotCurses.Version}!");
+ plane.SetFgRgb(0xFFFFFF);
+ plane.PutStr(new int2(2, 3), "Press any key to exit.");
+ nc.Render();
+
+ nc.GetBlocking(out _);
+}
diff --git a/samples/Hello/HelloNumerics.cs b/samples/Hello/HelloNumerics.cs
new file mode 100644
index 0000000..b6747ea
--- /dev/null
+++ b/samples/Hello/HelloNumerics.cs
@@ -0,0 +1,28 @@
+/*
+ * HelloNumerics
+ *
+ * Vector and matrix basics: float3 arithmetic, dot/cross products and transforming by a float4x4.
+ */
+
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+// RIAN: This package current contains a mirror of the System.Numerics math library for compatibility in porting, but will be reduced
+// to only the types in a future release. Math libraries are opinionated and should be picked by the developer, not the framework.
+
+using Brutal.Numerics;
+
+var a = new float3(1, 0, 0);
+var b = new float3(0, 1, 0);
+
+Console.WriteLine($"a + b = {a + b}");
+Console.WriteLine($"a * 3 = {a * 3}");
+Console.WriteLine($"dot(a, b) = {float3.Dot(a, b)}");
+Console.WriteLine($"cross(a, b) = {float3.Cross(a, b)}");
+Console.WriteLine($"|a + b| = {(a + b).Length()}");
+
+// Rotate 90 degrees around Z, then move 10 units along X.
+var transform = float4x4.CreateRotationZ(MathF.PI / 2) * float4x4.CreateTranslation(10, 0, 0);
+Console.WriteLine($"transformed = {float3.Transform(a, transform)}");
+
+var size = new int2(640, 480);
+Console.WriteLine($"int2 size = {size}");
diff --git a/samples/Hello/HelloOpenAl.cs b/samples/Hello/HelloOpenAl.cs
new file mode 100644
index 0000000..1aa7af8
--- /dev/null
+++ b/samples/Hello/HelloOpenAl.cs
@@ -0,0 +1,43 @@
+/*
+ * HelloOpenAl
+ *
+ * Opens the default audio device with OpenAL and plays a generated one-second 440 Hz tone.
+ */
+
+#:package Ahwoo.Brutal.OpenAl@2026.10.3
+
+using System.Runtime.InteropServices;
+using Brutal.OpenAlApi;
+
+using var device = Alc.OpenDevice(); // Default output device.
+Run(device);
+
+static void Run(Device device)
+{
+ using var context = device.CreateContext();
+ context.MakeCurrent();
+
+ Console.WriteLine($"Opened device: {device.Specifier}");
+
+ // One second of a 440 Hz sine wave as 16-bit mono PCM.
+ const int SAMPLE_RATE = 44_100;
+ var pcm = new short[SAMPLE_RATE];
+ for (var i = 0; i < pcm.Length; i++)
+ pcm[i] = (short)(Math.Sin(2 * Math.PI * 440 * i / SAMPLE_RATE) * short.MaxValue * 0.5);
+
+ var buffer = Al.GenBuffer();
+ buffer.SetData(AlFormat.Mono16, MemoryMarshal.AsBytes(pcm), SAMPLE_RATE);
+
+ var source = Al.GenSource();
+ source.Buffer = buffer;
+ source.Play();
+
+ Console.WriteLine("Playing a 440 Hz tone...");
+ while (source.State == AlSourceState.Playing)
+ Thread.Sleep(10);
+
+ // Buffers and sources aren't IDisposable, so delete them by hand.
+ Al.DeleteSources([source]);
+ Al.DeleteBuffers([buffer]);
+ Context.MakeCurrent(null); // Release the context before it is destroyed.
+}
diff --git a/samples/Hello/HelloOpenGl.cs b/samples/Hello/HelloOpenGl.cs
new file mode 100644
index 0000000..9842969
--- /dev/null
+++ b/samples/Hello/HelloOpenGl.cs
@@ -0,0 +1,145 @@
+/*
+ * HelloOpenGl
+ *
+ * Opens a GLFW window and draws a coloured triangle with OpenGL. Press Escape to close it.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Glfw@2026.10.5
+#:package Ahwoo.Brutal.OpenGl@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+// RIAN: Our OpenGL samples run on 4.1 for compatibility with macOS, but we should support up to 4.6 no problem.
+
+using Brutal;
+using Brutal.GlfwApi;
+using Brutal.Numerics;
+using Brutal.OpenGlApi;
+
+if (!Glfw.Init())
+{
+ var errorCode = Glfw.GetError(out var errorMessage);
+ throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
+}
+
+try
+{
+ Run();
+}
+finally
+{
+ Glfw.Terminate();
+}
+
+static void Run()
+{
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
+ Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
+ Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
+
+ if (Platform.IsMacOS)
+ Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
+
+ // A fixed size keeps the viewport and aspect ratio valid.
+ Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
+
+ using var window = Glfw.CreateWindow(
+ new GlfwWindow.CreateInfo { Title = "Hello OpenGL", Size = new int2(640, 480) }
+ );
+
+ window.MakeContextCurrent();
+ Glfw.SwapInterval(1); // Wait for vsync instead of drawing as fast as possible.
+
+ unsafe
+ {
+ if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
+ throw new InvalidOperationException("Failed to load the OpenGL functions with GLAD");
+ }
+
+ window.OnKey += (handle, key, _, _, _) =>
+ {
+ if (key == GlfwKey.Escape)
+ handle.ShouldClose = true;
+ };
+
+ // Declared after the window, so the program is deleted while the GL context still exists.
+ using var program = LinkProgram();
+
+ var vertexArray = OpenGl.GenVertexArray().Bind();
+ var vertexBuffer = OpenGl.GenBuffer();
+ vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
+ OpenGl.BufferData(
+ GlBindTarget.ArrayBuffer,
+ new Vertex[]
+ {
+ new(new float2(0.0f, 0.5f), new float3(1.0f, 0.0f, 0.0f)),
+ new(new float2(0.5f, -0.5f), new float3(0.0f, 1.0f, 0.0f)),
+ new(new float2(-0.5f, -0.5f), new float3(0.0f, 0.0f, 1.0f)),
+ },
+ GlBufferUsage.StaticDraw
+ );
+
+ OpenGl.VertexAttribute(new GlAttribute(0, 2, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 0));
+ OpenGl.VertexAttribute(
+ new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 2 * sizeof(float))
+ );
+ OpenGl.EnableVertexAttribArray(0);
+ OpenGl.EnableVertexAttribArray(1);
+
+ OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
+
+ while (!window.ShouldClose)
+ {
+ Glfw.PollEvents();
+ OpenGl.Clear(GlClearBit.Color);
+ program.Use();
+ vertexArray.Bind();
+ OpenGl.Draw(GlTopology.Triangles, 3, 1, 0, 0);
+ window.SwapBuffers();
+ }
+
+ // Vertex arrays and buffers aren't IDisposable, so delete them by hand while the GL context still exists.
+ OpenGl.DeleteVertexArrays([vertexArray]);
+ OpenGl.DeleteBuffers([vertexBuffer]);
+}
+
+// The shaders are only needed until the program is linked, so they are disposed on return.
+static GlProgram LinkProgram()
+{
+ using var vertexShader = OpenGl
+ .CreateShader(GlShaderType.Vertex)
+ .SetSource(
+ """
+ #version 410 core
+ layout (location = 0) in vec2 aPos;
+ layout (location = 1) in vec3 aColor;
+ out vec3 color;
+ void main()
+ {
+ color = aColor;
+ gl_Position = vec4(aPos, 0.0, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ using var fragmentShader = OpenGl
+ .CreateShader(GlShaderType.Fragment)
+ .SetSource(
+ """
+ #version 410 core
+ in vec3 color;
+ out vec4 FragColor;
+ void main()
+ {
+ FragColor = vec4(color, 1.0);
+ }
+ """u8
+ )
+ .Compile();
+
+ return OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
+}
+
+record struct Vertex(float2 Position, float3 Color);
diff --git a/samples/Hello/HelloRakNet.cs b/samples/Hello/HelloRakNet.cs
new file mode 100644
index 0000000..fcc35ad
--- /dev/null
+++ b/samples/Hello/HelloRakNet.cs
@@ -0,0 +1,85 @@
+/*
+ * HelloRakNet
+ *
+ * Starts a RakNet server and client in one process, connects them on localhost and sends a message.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.RakNet@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Strings@2026.10.2
+
+// RIAN: I believe this package is about to get a refresh with full plugin support (NAT punchthrough, etc).
+
+using Brutal.RakNetApi;
+using Brutal.Strings;
+
+const ushort PORT = 60_000;
+
+Run();
+
+static void Run()
+{
+ // Disposing a peer destroys it, which happens after it has been shut down at the end.
+ using var server = RakNetLibrary.CreateInstance();
+ using var client = RakNetLibrary.CreateInstance();
+
+ // The server can fail to start if something else is already using the port.
+ var serverSocket = new SocketDescriptor(PORT);
+ var serverStartup = server.Startup(4, new Span(ref serverSocket));
+ if (serverStartup != StartupResult.RaknetStarted)
+ throw new InvalidOperationException($"Server failed to start on port {PORT}: {serverStartup}");
+ server.SetMaximumIncomingConnections(4);
+
+ var clientSocket = new SocketDescriptor(0); // Any free port.
+ client.Startup(1, new Span(ref clientSocket));
+
+ unsafe
+ {
+ client.Connect("127.0.0.1"u8, PORT, default, null);
+
+ // Everything is local, so give up if the exchange takes more than a few seconds.
+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
+ var running = true;
+ while (running)
+ {
+ if (DateTime.UtcNow > deadline)
+ throw new TimeoutException("Timed out connecting and exchanging a message over localhost");
+
+ for (var packet = client.Receive(); packet != null; packet = client.Receive())
+ {
+ if ((DefaultMessageIDTypes)packet->Data[0] == DefaultMessageIDTypes.ConnectionRequestAccepted)
+ {
+ Console.WriteLine("Client: connected to server");
+
+ byte[] message = [(byte)DefaultMessageIDTypes.UserPacketEnum, .. "Hello, RakNet!"u8];
+ client.Send(
+ message,
+ PacketPriority.HighPriority,
+ PacketReliability.ReliableOrdered,
+ 0,
+ new AddressOrGUID(packet->SystemAddress),
+ false
+ );
+ }
+ client.DeallocatePacket(packet);
+ }
+
+ for (var packet = server.Receive(); packet != null; packet = server.Receive())
+ {
+ if ((DefaultMessageIDTypes)packet->Data[0] == DefaultMessageIDTypes.UserPacketEnum)
+ {
+ var text = Utf8.GetString(packet->Data + 1, (int)packet->Length - 1);
+ Console.WriteLine($"Server: received \"{text}\"");
+ running = false;
+ }
+ server.DeallocatePacket(packet);
+ }
+
+ Thread.Sleep(10);
+ }
+ }
+
+ client.Shutdown(300);
+ server.Shutdown(300);
+}
diff --git a/samples/Hello/HelloRenderDoc.cs b/samples/Hello/HelloRenderDoc.cs
new file mode 100644
index 0000000..165ac07
--- /dev/null
+++ b/samples/Hello/HelloRenderDoc.cs
@@ -0,0 +1,23 @@
+/*
+ * HelloRenderDoc
+ *
+ * Checks whether RenderDoc's in-application API is available (not on macOS) and prints its state.
+ */
+
+#:package Ahwoo.Brutal.RenderDoc@2026.10.3
+
+// RIAN: Use this package to debug your rendering more easily.
+
+using Brutal.RenderDocApi;
+
+// Call as early as possible, before any graphics API is initialized.
+RenderDoc.Initialize();
+
+Console.WriteLine($"RenderDoc available: {RenderDoc.IsAvailable}, state: {RenderDoc.State}");
+
+if (RenderDoc.IsAvailable)
+ Console.WriteLine($"RenderDoc API version: {RenderDoc.Version}");
+else
+ Console.WriteLine(
+ "RenderDoc loads when the app is launched from RenderDoc (Windows or Linux), or on Windows when it is installed in C:\\Program Files\\RenderDoc."
+ );
diff --git a/samples/Hello/HelloRenderDocImGui.cs b/samples/Hello/HelloRenderDocImGui.cs
new file mode 100644
index 0000000..d7cf094
--- /dev/null
+++ b/samples/Hello/HelloRenderDocImGui.cs
@@ -0,0 +1,67 @@
+/*
+ * HelloRenderDocImGui
+ *
+ * Draws the RenderDoc ImGui window headlessly and prints how much geometry it produced. The window
+ * adds View > RenderDoc to the main menu bar. When the app was launched from RenderDoc (Windows or
+ * Linux) the window shows the overlay, capture options, a TriggerCapture button and the list of
+ * captures; otherwise (always on macOS) its title reads "RenderDoc (loading failed)" and it only
+ * has a Help link and a load/unload button. See Demo/DemoRenderDoc.cs for capturing frames.
+ */
+
+#:package Ahwoo.Brutal.ImGui@2026.10.3
+#:package Ahwoo.Brutal.RenderDoc@2026.10.3
+#:package Ahwoo.Brutal.RenderDoc.ImGui@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal.ImGuiApi;
+using Brutal.Numerics;
+using Brutal.RenderDocApi;
+
+// Call as early as possible, before any graphics API is initialized.
+RenderDoc.Initialize();
+
+var context = ImGui.CreateContext();
+try
+{
+ Run();
+}
+finally
+{
+ ImGui.DestroyContext(context);
+}
+
+static void Run()
+{
+ var io = ImGui.GetIO();
+ io.IniFilename = null; // Don't write imgui.ini.
+ io.DisplaySize = new float2(800, 600); // No window, so tell ImGui how big the screen is.
+ io.DeltaTime = 1f / 60f;
+
+ // Claim a renderer that handles texture requests so ImGui builds the font atlas during the frame.
+ // Nothing uploads it here, which is fine for a headless frame.
+ io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures;
+
+ // The window starts hidden; View > RenderDoc toggles it. Show it straight away.
+ RenderDocWindow.Instance.Visible = true;
+
+ // The window sizes itself to fit, and ImGui hides auto-sized windows on their first frame while
+ // it measures them, so run two frames to see it drawn.
+ for (var frame = 0; frame < 2; frame++)
+ {
+ ImGui.NewFrame();
+ RenderDocWindow.Instance.OnImGui(); // Call once per frame, between NewFrame and Render.
+ ImGui.Render();
+ }
+
+ // A renderer would draw these; here we just count them.
+ var drawData = ImGui.GetDrawData();
+ var commands = 0;
+ for (var i = 0; i < drawData.CmdListsCount; i++)
+ commands += drawData.CmdLists[i].CmdBuffer.Count;
+
+ Console.WriteLine($"RenderDoc available: {RenderDoc.IsAvailable}, state: {RenderDoc.State}");
+ Console.WriteLine(
+ $"Draw data: {drawData.CmdListsCount} lists, {drawData.TotalVtxCount} vertices, {drawData.TotalIdxCount} indices, {commands} commands"
+ );
+}
diff --git a/samples/Hello/HelloRenderMesh.cs b/samples/Hello/HelloRenderMesh.cs
new file mode 100644
index 0000000..c2918d3
--- /dev/null
+++ b/samples/Hello/HelloRenderMesh.cs
@@ -0,0 +1,29 @@
+/*
+ * HelloRenderMesh
+ *
+ * Generates a procedural sphere mesh and prints its vertex and triangle counts.
+ */
+
+#:package Ahwoo.Brutal.Render.Mesh@2026.10.2
+#:package Ahwoo.Brutal.Collections@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal;
+using Brutal.Collections;
+using Brutal.Numerics;
+using Brutal.Render.Mesh;
+
+Run();
+
+static void Run()
+{
+ using var positions = new NativeStrideList(ByteSize.Of(), 0);
+ using var normals = new NativeStrideList(ByteSize.Of(), 0);
+ using var indices = new NativeStrideList(ByteSize.Of(), 0);
+
+ var sphere = new ProcGenMesh(positions, indices, normals);
+ ProcGenMeshLibrary.GenerateSphere(sphere, origin: float3.Zero, radius: 1.0f, resolution: 16);
+
+ Console.WriteLine($"Generated a sphere with {sphere.VertexCount} vertices and {sphere.IndexCount / 3} triangles");
+}
diff --git a/samples/Hello/HelloSdl.cs b/samples/Hello/HelloSdl.cs
new file mode 100644
index 0000000..d08963b
--- /dev/null
+++ b/samples/Hello/HelloSdl.cs
@@ -0,0 +1,65 @@
+/*
+ * HelloSdl
+ *
+ * Opens an SDL window with a renderer and draws a filled rectangle each frame.
+ * Press Escape to close it.
+ * See Demo/DemoSdl.cs for the Sdl.Image, Sdl.Mixer and Sdl.Ttf add-ons.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Sdl@2026.10.3
+
+// RIAN: We don't use SDL in any of our projects today, but feedback is appreciated.
+
+using Brutal.SdlApi;
+
+Sdl.Init.Initialize(SdlInitFlags.Video);
+try
+{
+ Run();
+}
+finally
+{
+ Sdl.Init.Quit();
+}
+
+static void Run()
+{
+ // Disposed in reverse when Run returns: the renderer, then its window, before SDL quits.
+ using var window = Sdl.Video.CreateWindow("Hello Sdl", 640, 480, SdlWindowFlags.Resizable);
+ using var renderer = Sdl.Render.CreateRenderer(window, null!); // null picks the best available driver.
+ Sdl.Render.SetRenderVSync(renderer, 1);
+
+ var running = true;
+ while (running)
+ {
+ while (Sdl.Events.PollEvent(out var ev))
+ {
+ if (ev.type is SdlEventType.Quit or SdlEventType.WindowCloseRequested)
+ running = false;
+ else if (ev.type == SdlEventType.KeyDown && ev.key.scancode == SdlScancode.Escape)
+ running = false;
+ }
+
+ Sdl.Render.SetRenderDrawColor(renderer, 51, 77, 77, 255);
+ Sdl.Render.RenderClear(renderer);
+
+ Sdl.Render.SetRenderDrawColor(renderer, 230, 128, 51, 255);
+ unsafe
+ {
+ var rect = new SdlFRect
+ {
+ x = 220,
+ y = 140,
+ w = 200,
+ h = 200,
+ };
+ Sdl.Render.RenderFillRect(renderer, &rect);
+ }
+
+ Sdl.Render.SetRenderDrawColor(renderer, 255, 255, 255, 255);
+ Sdl.Render.RenderDebugText(renderer, 16, 16, "Hello Sdl");
+
+ Sdl.Render.RenderPresent(renderer);
+ }
+}
diff --git a/samples/Hello/HelloSdlImage.cs b/samples/Hello/HelloSdlImage.cs
new file mode 100644
index 0000000..b872a4a
--- /dev/null
+++ b/samples/Hello/HelloSdlImage.cs
@@ -0,0 +1,45 @@
+/*
+ * HelloSdlImage
+ *
+ * Paints a gradient into an SDL surface, saves it as a PNG with Sdl.Image, loads it back and
+ * prints its size and pixel format. Runs headless (no window).
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Sdl@2026.10.3
+#:package Ahwoo.Brutal.Sdl.Image@2026.10.3
+
+using Brutal.SdlApi;
+using Brutal.SdlApi.Image;
+
+Run();
+
+static void Run()
+{
+ // Versions are packed as major * 1_000_000 + minor * 1000 + patch.
+ var version = SdlImage.Version();
+ Console.WriteLine($"SDL_image {version / 1_000_000}.{version / 1000 % 1000}.{version % 1000}");
+
+ var path = Path.Combine(Path.GetTempPath(), "HelloSdlImage.png");
+
+ // Surfaces are raw pointers rather than IDisposable handles, so each is destroyed by hand.
+ unsafe
+ {
+ // Surfaces are plain CPU-side pixel buffers, so no video subsystem is needed.
+ var surface = Sdl.PInvoke.CreateSurface(128, 64, SdlPixelFormat.Rgba8888);
+ for (var y = 0; y < surface->h; y++)
+ for (var x = 0; x < surface->w; x++)
+ Sdl.PInvoke.WriteSurfacePixel(surface, x, y, (byte)(x * 2), (byte)(y * 4), 128, 255);
+
+ SdlImage.SavePNG(surface, path);
+ Sdl.PInvoke.DestroySurface(surface);
+ Console.WriteLine($"Saved {path} ({new FileInfo(path).Length} bytes)");
+
+ // Load picks the decoder from the file contents; the loaded format need not match what was saved.
+ var loaded = SdlImage.Load(path);
+ Console.WriteLine(
+ $"Loaded {loaded->w}x{loaded->h}, format {Sdl.PInvoke.GetPixelFormatName(loaded->format)}, pitch {loaded->pitch}"
+ );
+ Sdl.PInvoke.DestroySurface(loaded);
+ }
+}
diff --git a/samples/Hello/HelloSdlMixer.cs b/samples/Hello/HelloSdlMixer.cs
new file mode 100644
index 0000000..80407d9
--- /dev/null
+++ b/samples/Hello/HelloSdlMixer.cs
@@ -0,0 +1,52 @@
+/*
+ * HelloSdlMixer
+ *
+ * Opens the default audio device with Sdl.Mixer, plays a half-second 440 Hz tone and waits for it
+ * to finish. Runs headless (no window).
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Sdl@2026.10.3
+#:package Ahwoo.Brutal.Sdl.Mixer@2026.10.3
+
+using Brutal.SdlApi;
+using Brutal.SdlApi.Mixer;
+
+const uint DEFAULT_PLAYBACK_DEVICE = 0xFFFFFFFFu; // SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK
+
+Sdl.Init.Initialize(SdlInitFlags.Audio);
+SdlMixer.Init();
+try
+{
+ Run();
+}
+finally
+{
+ SdlMixer.Quit();
+ Sdl.Init.Quit();
+}
+
+// Unsafe for the null and &spec pointer arguments.
+static unsafe void Run()
+{
+ // Disposed in reverse when Run returns: the track, the tone, then the mixer.
+ using var mixer = SdlMixer.CreateMixerDevice(DEFAULT_PLAYBACK_DEVICE, null); // null accepts the device's format.
+ SdlAudioSpec spec;
+ mixer.GetFormat(&spec);
+ Console.WriteLine(
+ $"Mixer: {spec.freq} Hz, {spec.channels} channel(s), {Sdl.PInvoke.GetAudioFormatName(spec.format)}"
+ );
+
+ // A generated sine wave, so there is no audio file to ship.
+ using var tone = mixer.CreateSineWaveAudio(440, 0.25f, 500);
+ using var track = mixer.CreateTrack();
+ track.SetAudio(tone);
+ track.Play(0);
+ Console.WriteLine($"Playing a 440 Hz sine wave for {tone.FramesToMS(tone.GetDuration())} ms");
+
+ // Playback happens on SDL's audio thread; poll until the track runs out, with a safety timeout.
+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(3);
+ while (track.Playing() && DateTime.UtcNow < deadline)
+ Thread.Sleep(10);
+ Console.WriteLine("Done");
+}
diff --git a/samples/Hello/HelloSdlTtf.cs b/samples/Hello/HelloSdlTtf.cs
new file mode 100644
index 0000000..cab4b9b
--- /dev/null
+++ b/samples/Hello/HelloSdlTtf.cs
@@ -0,0 +1,77 @@
+/*
+ * HelloSdlTtf
+ *
+ * Opens a font with Sdl.Ttf, renders a line of text to an SDL surface, prints its pixel size and
+ * saves it as a BMP. Runs headless (no window).
+ *
+ * Pass a font, or it tries a common system font for your OS:
+ *
+ * dotnet run Hello/HelloSdlTtf.cs -- path/to/font.ttf
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Sdl@2026.10.3
+#:package Ahwoo.Brutal.Sdl.Ttf@2026.10.3
+
+using Brutal.SdlApi;
+using Brutal.SdlApi.Ttf;
+
+// yuck, sorry
+string[] systemFonts =
+[
+ "/System/Library/Fonts/Supplemental/Arial.ttf", // macOS
+ @"C:\Windows\Fonts\arial.ttf", // Windows
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", // Debian, Ubuntu
+ "/usr/share/fonts/TTF/DejaVuSans.ttf", // Arch
+ "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf", // Fedora
+];
+
+var fontPath = args.Length > 0 ? args[0] : systemFonts.FirstOrDefault(File.Exists);
+if (fontPath is null)
+{
+ Console.WriteLine("No system font found. Usage: dotnet run Hello/HelloSdlTtf.cs -- path/to/font.ttf");
+ return;
+}
+
+SdlTtf.Init();
+try
+{
+ Run(fontPath);
+}
+finally
+{
+ SdlTtf.Quit();
+}
+
+static void Run(string fontPath)
+{
+ // Closed when Run returns, before Sdl.Ttf quits.
+ using var font = SdlTtf.OpenFont(fontPath, 32f);
+ Console.WriteLine($"Font: {SdlTtf.GetFontFamilyName(font)} {SdlTtf.GetFontStyleName(font)} ({fontPath})");
+
+ var bmpPath = Path.Combine(Path.GetTempPath(), "HelloSdlTtf.bmp");
+ unsafe
+ {
+ // Blended renders anti-aliased text onto a transparent surface; length 0 means null-terminated.
+ var surface = SdlTtf.RenderTextBlended(
+ font,
+ "Hello, Sdl.Ttf!",
+ 0,
+ new SdlColor
+ {
+ r = 255,
+ g = 255,
+ b = 255,
+ a = 255,
+ }
+ );
+
+ Console.WriteLine($"Rendered text: {surface->w}x{surface->h} pixels");
+
+ Sdl.PInvoke.SaveBMP(surface, bmpPath);
+ Console.WriteLine($"Saved {bmpPath}");
+
+ // The surface is a raw pointer rather than an IDisposable handle, so destroy it by hand.
+ Sdl.PInvoke.DestroySurface(surface);
+ }
+}
diff --git a/samples/Hello/HelloShaderC.cs b/samples/Hello/HelloShaderC.cs
new file mode 100644
index 0000000..f5f45cc
--- /dev/null
+++ b/samples/Hello/HelloShaderC.cs
@@ -0,0 +1,37 @@
+/*
+ * HelloShaderC
+ *
+ * Compiles a small inline GLSL vertex shader to SPIR-V with shaderc and prints its size.
+ */
+
+#:package Ahwoo.Brutal.ShaderC@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Strings@2026.10.2
+
+using Brutal.ShaderCApi;
+
+Run();
+
+static void Run()
+{
+ // Disposed in reverse when Run returns: the result, the options, then the compiler.
+ using var compiler = ShaderC.CreateCompiler();
+ using var options = ShaderC.CreateCompilerOptions();
+
+ using var result = compiler.Compile(
+ """
+ #version 450
+
+ void main()
+ {
+ gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
+ }
+ """u8,
+ ShaderKind.VertexShader,
+ "hello.vert"u8,
+ "main"u8,
+ options
+ );
+
+ Console.WriteLine($"Compiled GLSL to {result.GetLength().Value} bytes of SPIR-V");
+}
diff --git a/samples/Hello/HelloSlang.cs b/samples/Hello/HelloSlang.cs
new file mode 100644
index 0000000..4689800
--- /dev/null
+++ b/samples/Hello/HelloSlang.cs
@@ -0,0 +1,48 @@
+/*
+ * HelloSlang
+ *
+ * Compiles a small inline Slang vertex shader to SPIR-V and prints its size.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Slang@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Strings@2026.10.2
+
+using Brutal.SlangApi;
+
+Run();
+
+static void Run()
+{
+ // The global session is a COM proxy that the GC releases, so only the request needs disposing.
+ var globalSession = Slang.CreateGlobalSession();
+
+ using var request = globalSession.CreateCompileRequest();
+ request.SetCodeGenTarget(CompileTarget.Spirv);
+
+ var translationUnit = request.AddTranslationUnit(SourceLanguage.Slang, "hello"u8);
+ request.AddTranslationUnitSourceString(
+ translationUnit,
+ "hello.slang"u8,
+ """
+ [shader("vertex")]
+ float4 vertexMain(float3 position : POSITION) : SV_Position
+ {
+ return float4(position, 1.0);
+ }
+ """u8
+ );
+
+ var entryPoint = request.AddEntryPoint(translationUnit, "vertexMain"u8, Stage.Vertex);
+
+ var compileResult = request.Compile();
+ if (compileResult.IsFailure)
+ throw new SlangException(compileResult, $"Slang compile failed: {request.GetDiagnosticOutput()}");
+
+ unsafe
+ {
+ request.GetEntryPointCode(entryPoint, out var size);
+ Console.WriteLine($"Compiled Slang to {size} of SPIR-V");
+ }
+}
diff --git a/samples/Hello/HelloStb.cs b/samples/Hello/HelloStb.cs
new file mode 100644
index 0000000..d7372c3
--- /dev/null
+++ b/samples/Hello/HelloStb.cs
@@ -0,0 +1,40 @@
+/*
+ * HelloStb
+ *
+ * Writes a generated gradient to a PNG with stb_image_write, reads it back with stb_image and
+ * prints a pixel.
+ */
+
+#:package Ahwoo.Brutal.Stb@2026.10.3
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+// RIAN: Warning this library is handy for PNG, but it's pretty slow at runtime.
+
+using System.Runtime.InteropServices;
+using Brutal.Numerics;
+using Brutal.StbApi;
+
+const int WIDTH = 64;
+const int HEIGHT = 64;
+
+Run();
+
+static void Run()
+{
+ // Generate an RGB gradient.
+ var pixels = new byte3[WIDTH * HEIGHT];
+ for (var y = 0; y < HEIGHT; y++)
+ {
+ for (var x = 0; x < WIDTH; x++)
+ pixels[y * WIDTH + x] = new byte3((byte)(x * 4), (byte)(y * 4), 128);
+ }
+
+ var path = Path.Combine(Path.GetTempPath(), "HelloStb.png");
+ Stb.WritePng(path, WIDTH, HEIGHT, 3, MemoryMarshal.AsBytes(pixels.AsSpan()));
+ Console.WriteLine($"Wrote {path}");
+
+ // Freed when Run returns.
+ using var image = Stb.Load(path);
+ Console.WriteLine($"Loaded {image.Width}x{image.Height}, {image.Channels} channels");
+ Console.WriteLine($"Pixel (63, 0) = {image.AsSpan()[63]}");
+}
diff --git a/samples/Hello/HelloStrings.cs b/samples/Hello/HelloStrings.cs
new file mode 100644
index 0000000..b092afe
--- /dev/null
+++ b/samples/Hello/HelloStrings.cs
@@ -0,0 +1,25 @@
+/*
+ * HelloStrings
+ *
+ * Works with UTF-8 text using String8 and StringBuilder, which are designed to avoid
+ * allocations.
+ */
+
+#:package Ahwoo.Brutal.Strings@2026.10.2
+
+using Brutal.Strings;
+
+var greeting = new String8("Hello, café!");
+
+Console.WriteLine($"Text: {greeting.ToString16()}");
+Console.WriteLine($"UTF-8 bytes: {greeting.Length}, code points: {Unicode.GetRuneCount(greeting.AsSpan())}");
+Console.WriteLine($"Starts with \"Hello\": {greeting.StartsWith("Hello"u8)}");
+
+// A StringBuilder that writes UTF-8 bytes directly.
+var builder = new StringBuilder();
+builder.Append($"Pi is roughly {Math.PI:F3}");
+builder.AppendLine();
+builder.Append("Built as UTF-8"u8);
+
+Console.WriteLine(builder.ToString());
+Console.WriteLine($"Builder holds {builder.WrittenSpan.Length} UTF-8 bytes");
diff --git a/samples/Hello/HelloTexture.cs b/samples/Hello/HelloTexture.cs
new file mode 100644
index 0000000..d68c83b
--- /dev/null
+++ b/samples/Hello/HelloTexture.cs
@@ -0,0 +1,54 @@
+/*
+ * HelloTexture
+ *
+ * Prints texture format descriptors, fills a GenericTexture with a gradient, saves it as .png
+ * and .ktx2, then loads both back with TextureLoader.
+ */
+
+#:package Ahwoo.Brutal.Texture@2026.10.3
+#:package Ahwoo.Brutal.Texture.Abstractions@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using System.Runtime.InteropServices;
+using Brutal.Numerics;
+using Brutal.TextureApi;
+using Brutal.TextureApi.Abstractions;
+
+Run();
+
+static void Run()
+{
+ // Format descriptors describe how texels are laid out in memory.
+ foreach (var format in new[] { TextureFormat.R8G8B8A8_UNorm, TextureFormat.BC7_UNorm_Block })
+ {
+ var descriptor = format.Descriptor();
+ Console.WriteLine(
+ $"{format}: {descriptor.BlockSizeInBytes} per {descriptor.BlockWidth}x{descriptor.BlockHeight} block, compressed: {descriptor.IsBlockCompressed}"
+ );
+ }
+
+ var pngPath = Path.Combine(Path.GetTempPath(), "HelloTexture.png");
+ var ktxPath = Path.Combine(Path.GetTempPath(), "HelloTexture.ktx2");
+
+ // GenericTexture is a plain in-memory texture you can fill and pass to any writer or uploader.
+ // Textures aren't IDisposable, so each one is destroyed or unloaded by hand.
+ var texture = GenericTexture.Defaults.RGBA8UNorm(new int2(64, 64));
+ var texels = MemoryMarshal.Cast(texture.Data);
+ for (var i = 0; i < texels.Length; i++)
+ texels[i] = new byte4((byte)(i % 64 * 4), (byte)(i / 64 * 4), 128, 255);
+
+ TextureWriter.SaveToFile(texture, pngPath);
+ TextureWriter.SaveToFile(texture, ktxPath);
+ texture.Destroy();
+
+ // TextureLoader picks the right backend (stb, KTX or GLI) from the file extension.
+ foreach (var path in new[] { pngPath, ktxPath })
+ {
+ var loaded = TextureLoader.LoadFromFile(path);
+ Console.WriteLine(
+ $"{Path.GetFileName(path)}: {loaded.GetType().Name}, {loaded.Format}, {loaded.Extent.X}x{loaded.Extent.Y}, {loaded.Data.Length} bytes"
+ );
+ TextureLoader.Unload(loaded);
+ }
+}
diff --git a/samples/Hello/HelloVulkan.cs b/samples/Hello/HelloVulkan.cs
new file mode 100644
index 0000000..4d282c7
--- /dev/null
+++ b/samples/Hello/HelloVulkan.cs
@@ -0,0 +1,105 @@
+/*
+ * HelloVulkan
+ *
+ * Creates a Vulkan instance, lists the physical devices and their queue families, then creates
+ * and destroys a logical device with one queue. Nothing is drawn, so no window is needed.
+ * See Demo/DemoVulkan.cs for a version that draws a triangle in a window.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Vulkan@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Strings@2026.10.2
+
+// RIAN: This is NOT a best-practices Vulkan sample. There are many shortcuts taken that you should not take in production code.
+
+using Brutal;
+using Brutal.Strings;
+using Brutal.VulkanApi;
+
+// Vulkan packs versions as major << 22 | minor << 12 | patch.
+const int API_VERSION_1_3 = 1 << 22 | 3 << 12;
+static string FormatVersion(int version) => $"{(version >> 22) & 0x7F}.{(version >> 12) & 0x3FF}.{version & 0xFFF}";
+
+// MoltenVK is a "portability" driver: macOS only lists it if the instance opts in to portability enumeration.
+var extensions = new HashSet();
+var flags = VkInstanceCreateFlags.None;
+if (Platform.IsMacOS)
+{
+ extensions.Add(VK.KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
+ flags |= VkInstanceCreateFlags.EnumeratePortabilityBitKHR;
+}
+
+// Everything else hangs off the instance, so it lives at the top level and is disposed after Run returns.
+using var instance = Vulkan.CreateInstance(
+ new Instance.CreateInfo
+ {
+ AppInfo = new VkApplicationInfo { ApiVersion = API_VERSION_1_3 },
+ Flags = flags,
+ EnabledExtensions = extensions,
+ EnabledLayers = [], // Set VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation to validate without changing code.
+ }
+);
+
+Run(instance);
+
+static void Run(Instance instance)
+{
+ // The instance enumerates its physical devices when it's created.
+ Console.WriteLine($"Found {instance.PhysicalDevices.Length} physical device(s)");
+
+ foreach (var physicalDevice in instance.PhysicalDevices)
+ {
+ var properties = physicalDevice.GetProperties();
+ unsafe
+ {
+ Console.WriteLine($" {Utf8.GetString(properties.DeviceName)}");
+ }
+ Console.WriteLine($" type {properties.DeviceType}");
+ // MoltenVK reports the major.minor the instance asked for, not the newest it supports.
+ Console.WriteLine($" API version {FormatVersion(properties.ApiVersion)}");
+
+ var families = new VkQueueFamilyProperties[physicalDevice.GetQueueFamilyProperties_Count()];
+ physicalDevice.GetQueueFamilyProperties_Write(families);
+ for (var i = 0; i < families.Length; i++)
+ Console.WriteLine($" queue family {i}: {families[i].QueueCount} x {families[i].QueueFlags}");
+ }
+
+ if (instance.PhysicalDevices.Length == 0)
+ return;
+
+ // Create a device on the first physical device, with one queue from the first family that can do graphics.
+ var device0 = instance.PhysicalDevices[0];
+ var queueFamily = device0.GetFirstQueueFamilyWithFlag(VkQueueFlags.GraphicsBit);
+
+ // A portability driver also requires VK_KHR_portability_subset to be enabled on the device.
+ var deviceExtensions = new HashSet();
+ if (device0.SupportsExtension(VK.KHR_PORTABILITY_SUBSET_EXTENSION_NAME))
+ deviceExtensions.Add(VK.KHR_PORTABILITY_SUBSET_EXTENSION_NAME);
+
+ unsafe
+ {
+ var priority = 1.0f;
+ // Disposed at the end of this block, before Run returns and the instance is disposed.
+ using var device = device0.CreateDevice(
+ new Device.CreateInfo
+ {
+ Extensions = deviceExtensions,
+ QueueCreateInfos =
+ [
+ new VkDeviceQueueCreateInfo
+ {
+ QueueFamilyIndex = queueFamily,
+ QueueCount = 1,
+ QueuePriorities = &priority,
+ },
+ ],
+ }
+ );
+
+ var queue = device.GetQueue(queueFamily, 0);
+ Console.WriteLine($"Created a device with one queue from family {queue.Family}");
+
+ device.WaitIdle();
+ }
+}
diff --git a/samples/Hello/HelloVulkanAbstractions.cs b/samples/Hello/HelloVulkanAbstractions.cs
new file mode 100644
index 0000000..7e9cfe8
--- /dev/null
+++ b/samples/Hello/HelloVulkanAbstractions.cs
@@ -0,0 +1,113 @@
+/*
+ * HelloVulkanAbstractions
+ *
+ * Sets up Vulkan with the Vulkan.Abstractions helpers, then builds a pipeline's vertex input
+ * layout from plain C# structs and prints what it produced.
+ * Nothing is drawn, so no window is needed.
+ * See Demo/DemoVulkan.cs for a version that draws a triangle in a window.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Vulkan@2026.10.3
+#:package Ahwoo.Brutal.Vulkan.Abstractions@2026.10.3
+#:package Ahwoo.Brutal.Collections@2026.10.2
+#:package Ahwoo.Brutal.Core@2026.10.4
+#:package Ahwoo.Brutal.Numerics@2026.10.2
+
+using Brutal.Numerics;
+using Brutal.VulkanApi;
+using Brutal.VulkanApi.Abstractions;
+
+// VulkanHelpers knows what each OS needs, e.g. portability enumeration for MoltenVK on macOS.
+var instanceExtensions = new HashSet();
+VulkanHelpers.AddPlatformRequiredExtensions(instanceExtensions);
+
+// Unlike the raw HelloVulkan sample, this turns validation on whenever the layer is installed.
+var layers = new HashSet();
+if (VulkanHelpers.Validation.IsSupported)
+ VulkanHelpers.AddValidationLayers(layers);
+
+Console.WriteLine($"Instance extensions: [{string.Join(", ", instanceExtensions)}]");
+Console.WriteLine($"Instance layers: [{string.Join(", ", layers)}]");
+
+// Everything else hangs off the instance, so it lives at the top level and is disposed after Run returns.
+using var instance = Vulkan.CreateInstance(
+ new Instance.CreateInfo
+ {
+ AppInfo = new VkApplicationInfo { ApiVersion = (int)VulkanHelpers.Api.VERSION_1_3 },
+ Flags = VulkanHelpers.GetPlatformRequiredInstanceCreateFlags(),
+ EnabledExtensions = instanceExtensions,
+ EnabledLayers = layers,
+ }
+);
+
+Run(instance);
+
+static void Run(Instance instance)
+{
+ var physicalDevice = instance.PhysicalDevices[0];
+ var queueFamily = physicalDevice.GetFirstQueueFamilyWithFlag(VkQueueFlags.GraphicsBit);
+
+ // Adds the device extensions that must be enabled whenever they're supported (VK_KHR_portability_subset).
+ var deviceExtensions = new HashSet();
+ VulkanHelpers.AddMandatoryIfSupportedDeviceExtensions(deviceExtensions, physicalDevice);
+ Console.WriteLine($"Device extensions: [{string.Join(", ", deviceExtensions)}]");
+
+ unsafe
+ {
+ // DeviceEx is a Device that can also allocate buffers and images itself (IBufferAllocator, IImageAllocator).
+ // It's disposed at the end of this block, before Run returns and the instance is disposed.
+ var priority = 1.0f;
+ using var device = physicalDevice.CreateDevice(
+ new DeviceEx.CreateInfo
+ {
+ Extensions = deviceExtensions,
+ QueueCreateInfos =
+ [
+ new VkDeviceQueueCreateInfo
+ {
+ QueueFamilyIndex = queueFamily,
+ QueueCount = 1,
+ QueuePriorities = &priority,
+ },
+ ],
+ }
+ );
+ Console.WriteLine($"Created a {device.GetType().Name} with one queue from family {queueFamily}");
+
+ // VertexInput reads the struct fields to fill in strides, formats, offsets and locations.
+ // Binding 0 is per vertex, binding 1 per instance; a float4x4 takes four locations.
+ var vertexInput = new VertexInput(2, 7)
+ .AddBindingWithAttributes(0, 0, VkVertexInputRate.Vertex)
+ .AddBindingWithAttributes(3, 1, VkVertexInputRate.Instance);
+
+ // Test() checks the layout is valid and returns Ok or the problem it found.
+ Console.WriteLine($"Vertex input: {vertexInput.Test()}");
+ foreach (var binding in vertexInput.Bindings)
+ Console.WriteLine($" binding {binding.Binding}: stride {binding.Stride}, {binding.InputRate}");
+ foreach (var attribute in vertexInput.Attributes)
+ Console.WriteLine(
+ $" location {attribute.Location}: binding {attribute.Binding}, offset {attribute.Offset}, {attribute.Format}"
+ );
+
+ // It converts straight to the struct that VkGraphicsPipelineCreateInfo.VertexInputState points at.
+ VkPipelineVertexInputStateCreateInfo* state = vertexInput;
+ Console.WriteLine(
+ $"VertexInputState: {state->VertexBindingDescriptionCount} bindings, {state->VertexAttributeDescriptionCount} attributes"
+ );
+ }
+}
+
+struct Vertex(float3 position, float2 texCoord, byte4 color)
+{
+ public float3 Position = position;
+ public float2 TexCoord = texCoord;
+
+ [FixedPointConversion(Behavior.Normalize)] // Four bytes read as 0..1 floats in the shader.
+ public byte4 Color = color;
+}
+
+struct InstanceData(float4x4 transform)
+{
+ public float4x4 Transform = transform;
+}
diff --git a/samples/Hello/HelloVulkanVma.cs b/samples/Hello/HelloVulkanVma.cs
new file mode 100644
index 0000000..16a5f7d
--- /dev/null
+++ b/samples/Hello/HelloVulkanVma.cs
@@ -0,0 +1,99 @@
+/*
+ * HelloVulkanVma
+ *
+ * Creates a VMA allocator, allocates a buffer the CPU can write to through a persistent mapping,
+ * writes a few numbers into it and prints them back. Nothing is drawn, so no window is needed.
+ * See Demo/DemoVulkan.cs for VMA feeding a vertex buffer to draw a triangle in a window.
+ */
+
+#:property AllowUnsafeBlocks=true
+#:package Ahwoo.Brutal.Vulkan@2026.10.3
+#:package Ahwoo.Brutal.Vulkan.Vma@2026.10.3
+#:package Ahwoo.Brutal.Core@2026.10.4
+
+using Brutal;
+using Brutal.VulkanApi;
+using Brutal.VulkanApi.Vma;
+
+const int API_VERSION_1_3 = 1 << 22 | 3 << 12;
+
+// A plain Vulkan instance and device; see Hello/HelloVulkan.cs for what the macOS portability bits are for.
+HashSet instanceExtensions = Platform.IsMacOS ? [VK.KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME] : [];
+var instanceFlags = Platform.IsMacOS ? VkInstanceCreateFlags.EnumeratePortabilityBitKHR : VkInstanceCreateFlags.None;
+
+// Everything else hangs off the instance, so it lives at the top level and is disposed after Run returns.
+using var instance = Vulkan.CreateInstance(
+ new Instance.CreateInfo
+ {
+ AppInfo = new VkApplicationInfo { ApiVersion = API_VERSION_1_3 },
+ Flags = instanceFlags,
+ EnabledExtensions = instanceExtensions,
+ EnabledLayers = [],
+ }
+);
+
+Run(instance);
+
+static unsafe void Run(Instance instance)
+{
+ var physicalDevice = instance.PhysicalDevices[0];
+ var queueFamily = physicalDevice.GetFirstQueueFamilyWithFlag(VkQueueFlags.TransferBit);
+
+ var deviceExtensions = new HashSet();
+ if (physicalDevice.SupportsExtension(VK.KHR_PORTABILITY_SUBSET_EXTENSION_NAME))
+ deviceExtensions.Add(VK.KHR_PORTABILITY_SUBSET_EXTENSION_NAME);
+
+ var priority = 1.0f;
+ // Disposed when Run returns, after the allocator is destroyed and before the instance.
+ using var device = physicalDevice.CreateDevice(
+ new Device.CreateInfo
+ {
+ Extensions = deviceExtensions,
+ QueueCreateInfos =
+ [
+ new VkDeviceQueueCreateInfo
+ {
+ QueueFamilyIndex = queueFamily,
+ QueueCount = 1,
+ QueuePriorities = &priority,
+ },
+ ],
+ }
+ );
+
+ // VMA must be told the API version the instance was created with.
+ var allocator = device.CreateVmaAllocator(
+ new VmaAllocatorCreateInfo
+ {
+ Instance = instance,
+ PhysicalDevice = physicalDevice,
+ Device = device,
+ VulkanApiVersion = API_VERSION_1_3,
+ }
+ );
+
+ // Auto picks the memory type, HostAccessSequentialWrite asks for one the CPU can write to,
+ // and Mapped keeps it mapped for the buffer's whole lifetime.
+ const int COUNT = 4;
+ allocator.CreateBuffer(
+ new VkBufferCreateInfo { Size = ByteSize.Of() * COUNT, Usage = VkBufferUsageFlags.TransferSrcBit },
+ new VmaAllocationCreateInfo
+ {
+ Usage = VmaMemoryUsage.Auto,
+ Flags = VmaAllocationCreateFlags.HostAccessSequentialWriteBit | VmaAllocationCreateFlags.MappedBit,
+ },
+ out var buffer,
+ out var allocation,
+ out var allocationInfo
+ );
+
+ // PMappedData points straight at the buffer's memory, so there's no map or unmap call.
+ var mapped = new Span((void*)allocationInfo.PMappedData, COUNT);
+ for (var i = 0; i < COUNT; i++)
+ mapped[i] = (i + 1) * 10;
+ Console.WriteLine($"Buffer holds: {string.Join(", ", mapped.ToArray())}");
+
+ // The allocator isn't IDisposable, so the buffer and then the allocator are destroyed by hand.
+ allocator.DestroyBuffer(buffer, allocation);
+ device.DestroyVmaAllocator(allocator);
+}
diff --git a/samples/README.md b/samples/README.md
new file mode 100644
index 0000000..888d1a4
--- /dev/null
+++ b/samples/README.md
@@ -0,0 +1,135 @@
+# BRUTAL Samples
+
+Small, self-contained samples for the BRUTAL packages. Each sample is a single C# file that you can run directly with the [.NET 10 SDK](https://dotnet.microsoft.com/download), with no project file. From a fresh clone of the repository:
+
+```sh
+cd samples/Hello
+dotnet run HelloGlfw.cs
+```
+
+Or from the repository root, `dotnet run samples/Hello/HelloGlfw.cs`.
+
+The samples come in two kinds:
+
+- **[Hello/](Hello)** has one sample per package. Each is the smallest useful starting point for that package.
+- **[Demo/](Demo)** has fuller programs that combine several packages.
+
+These samples are deliberately minimal.
+
+### Error handling
+
+Error handling is kept light on purpose. The samples check the failures you're likely to hit, such as a window that can't be created, a missing GPU feature or a file that doesn't exist, and let everything else throw.
+
+## Requirements
+
+- The [.NET 10 SDK](https://dotnet.microsoft.com/download).
+- Windows x64, Linux x64 or macOS on Apple silicon. The packages bundle native libraries for these three.
+- **Vulkan samples:** the packages ship Brutal's own Vulkan helper library, which loads the system's Vulkan loader, and the loader then finds your GPU driver. On Windows both come with your GPU driver. On Linux, install the Vulkan loader and a driver, for example `libvulkan1` and `mesa-vulkan-drivers` on Debian or Ubuntu. On macOS, install the [Vulkan SDK](https://vulkan.lunarg.com/sdk/home), which provides the loader and MoltenVK.
+- **Windowed samples:** a desktop session. On Linux that means X11 or Wayland.
+- **Audio samples:** an audio output device.
+- **HelloNativeFileDialog on Linux:** GTK 3.
+- **HelloFmod:** your own licensed FMOD libraries; see the file's header.
+- **HelloNotCurses:** a real terminal.
+
+## Start here
+
+- **Foundations:** [HelloCore](Hello/HelloCore.cs), then [HelloMemory](Hello/HelloMemory.cs), [HelloCollections](Hello/HelloCollections.cs) and [HelloStrings](Hello/HelloStrings.cs).
+- **Windowing:** [HelloGlfw](Hello/HelloGlfw.cs) for an empty window, then [HelloImGui](Hello/HelloImGui.cs) for debug UI.
+- **Graphics:** [HelloOpenGl](Hello/HelloOpenGl.cs) for the shortest path to a triangle. For Vulkan, [HelloVulkan](Hello/HelloVulkan.cs) then [DemoVulkan](Demo/DemoVulkan.cs) for the triangle.
+- **Audio:** [HelloOpenAl](Hello/HelloOpenAl.cs).
+- **Physics:** [HelloBox2D](Hello/HelloBox2D.cs) or [HelloJolt](Hello/HelloJolt.cs), then their demos.
+
+## Foundations
+
+| Sample | What it shows |
+| --- | --- |
+| [HelloCore.cs](Hello/HelloCore.cs) | Platform detection, `ByteSize`/`ElementCount` arithmetic and `Ptr` |
+| [HelloMemory.cs](Hello/HelloMemory.cs) | Allocating and freeing unmanaged memory with `Mem`, and owning a pointer with `PtrOwner` |
+| [HelloCollections.cs](Hello/HelloCollections.cs) | `NativeList`, a growable list backed by unmanaged memory |
+| [HelloStrings.cs](Hello/HelloStrings.cs) | UTF-8 text with `String8` and `StringBuilder`, which are designed to avoid allocations |
+| [HelloNumerics.cs](Hello/HelloNumerics.cs) | Vector and matrix basics with `float3` and `float4x4` |
+| [HelloMaths.cs](Hello/HelloMaths.cs) | The `Random` extensions: ranges, points in shapes and random directions |
+| [HelloConcurrency.cs](Hello/HelloConcurrency.cs) | Running jobs across worker threads with `JobScheduler` |
+| [HelloLogging.cs](Hello/HelloLogging.cs) | Logging to the console with the default and named categories |
+| [HelloLocalization.cs](Hello/HelloLocalization.cs) | Localised strings with named variables, and swapping in a translation |
+
+## Windowing and UI
+
+| Sample | What it shows |
+| --- | --- |
+| [HelloGlfw.cs](Hello/HelloGlfw.cs) | An empty GLFW window |
+| [HelloSdl.cs](Hello/HelloSdl.cs) | An SDL window with a renderer drawing a filled rectangle |
+| [HelloSdlImage.cs](Hello/HelloSdlImage.cs) | Saving a generated image as PNG with Sdl.Image and loading it back |
+| [HelloSdlTtf.cs](Hello/HelloSdlTtf.cs) | Rendering text to a surface with Sdl.Ttf, using a system font if you don't pass one |
+| [HelloImGui.cs](Hello/HelloImGui.cs) | Dear ImGui on its GLFW and OpenGL backends with some text, a button and a slider |
+| [HelloImGuiFreeType.cs](Hello/HelloImGuiFreeType.cs) | Building the ImGui font atlas with FreeType, without a window |
+| [HelloImPlot.cs](Hello/HelloImPlot.cs) | Plotting a sine wave with ImPlot in one headless frame |
+| [HelloImGuiAbstractions.cs](Hello/HelloImGuiAbstractions.cs) | The in-game console: registering `[TerminalAction]` commands and running command lines |
+| [HelloImGuiExtensions.cs](Hello/HelloImGuiExtensions.cs) | `ImGuiEx` widgets bound straight to C# enums |
+| [HelloNativeFileDialog.cs](Hello/HelloNativeFileDialog.cs) | The operating system's native file picker |
+| [HelloNotCurses.cs](Hello/HelloNotCurses.cs) | Coloured text in the terminal with notcurses (run it in a real terminal) |
+
+## Graphics
+
+| Sample | What it shows |
+| --- | --- |
+| [HelloOpenGl.cs](Hello/HelloOpenGl.cs) | A coloured triangle with OpenGL |
+| [HelloVulkan.cs](Hello/HelloVulkan.cs) | Creating a Vulkan instance, listing GPUs and their queue families, and creating a device |
+| [HelloVulkanAbstractions.cs](Hello/HelloVulkanAbstractions.cs) | The Vulkan.Abstractions setup helpers, and a vertex input layout built from C# structs |
+| [HelloVulkanVma.cs](Hello/HelloVulkanVma.cs) | Creating a VMA allocator and a mapped buffer, writing to it and reading it back |
+| [HelloShaderC.cs](Hello/HelloShaderC.cs) | Compiling GLSL to SPIR-V with shaderc |
+| [HelloSlang.cs](Hello/HelloSlang.cs) | Compiling Slang to SPIR-V |
+| [HelloRenderMesh.cs](Hello/HelloRenderMesh.cs) | Generating a procedural sphere mesh |
+
+## Textures and assets
+
+| Sample | What it shows |
+| --- | --- |
+| [HelloStb.cs](Hello/HelloStb.cs) | Writing and reading a PNG with stb_image |
+| [HelloTexture.cs](Hello/HelloTexture.cs) | Texture format descriptors, filling a `GenericTexture`, and saving and loading it as PNG and KTX2 with `TextureWriter` and `TextureLoader` |
+| [HelloKtx.cs](Hello/HelloKtx.cs) | Creating, writing and loading a KTX2 texture |
+| [HelloGli.cs](Hello/HelloGli.cs) | A texture with a full mip chain, saved and loaded as DDS with GLI |
+| [HelloGltf.cs](Hello/HelloGltf.cs) | Parsing a tiny inline glTF, reading its vertices and saving it back out |
+| [HelloMeshOptimizer.cs](Hello/HelloMeshOptimizer.cs) | Reordering triangles for the vertex cache with meshoptimizer |
+
+## Audio
+
+| Sample | What it shows |
+| --- | --- |
+| [HelloOpenAl.cs](Hello/HelloOpenAl.cs) | Playing a generated tone with OpenAL |
+| [HelloSdlMixer.cs](Hello/HelloSdlMixer.cs) | Playing a generated tone with Sdl.Mixer |
+| [HelloFmod.cs](Hello/HelloFmod.cs) | Playing a tone with FMOD. FMOD's native libraries aren't bundled, so you need your own licensed copy |
+
+## Physics
+
+| Sample | What it shows |
+| --- | --- |
+| [HelloBox2D.cs](Hello/HelloBox2D.cs) | Dropping a box onto the ground with Box2D and printing where it lands |
+| [HelloJolt.cs](Hello/HelloJolt.cs) | Dropping a box onto the ground with Jolt Physics and printing where it lands |
+
+## Networking
+
+| Sample | What it shows |
+| --- | --- |
+| [HelloRakNet.cs](Hello/HelloRakNet.cs) | A RakNet server and client connecting over localhost and sending a message |
+
+## Diagnostics
+
+| Sample | What it shows |
+| --- | --- |
+| [HelloMonitorHost.cs](Hello/HelloMonitorHost.cs) | Starting the Monitor watchdog and writing logs to a file |
+| [HelloRenderDoc.cs](Hello/HelloRenderDoc.cs) | Checking whether RenderDoc's in-application API is loaded (Windows and Linux) |
+| [HelloRenderDocImGui.cs](Hello/HelloRenderDocImGui.cs) | Drawing the RenderDoc control panel with Dear ImGui, headless |
+
+## Demos
+
+| Sample | What it shows |
+| --- | --- |
+| [DemoVulkan.cs](Demo/DemoVulkan.cs) | A coloured triangle with Vulkan, the Vulkan.Abstractions helpers, a VMA-allocated vertex buffer and shaders compiled with ShaderC |
+| [DemoGltfViewer.cs](Demo/DemoGltfViewer.cs) | Loading a glTF scene with its node transforms, optimising it with meshoptimizer and drawing it lit with OpenGL. Pass your own `.gltf` or `.glb`, or it builds a torus knot |
+| [DemoTexturedQuad.cs](Demo/DemoTexturedQuad.cs) | Writing a mipmapped texture as KTX2, loading it back and drawing it on a floor with OpenGL, with each mip level tinted |
+| [DemoImGui.cs](Demo/DemoImGui.cs) | Dear ImGui with FreeType fonts and an ImPlot plot, on GLFW and OpenGL |
+| [DemoSdl.cs](Demo/DemoSdl.cs) | An SDL window using Sdl.Image (PNG save and load), Sdl.Mixer (a beep on Space) and Sdl.Ttf (text, if you pass a font) |
+| [DemoRenderDoc.cs](Demo/DemoRenderDoc.cs) | An OpenGL triangle that captures a frame with RenderDoc when you press F12 (Windows and Linux) |
+| [DemoBox2D.cs](Demo/DemoBox2D.cs) | Boxes falling onto the ground with Box2D, drawn with OpenGL |
+| [DemoJolt.cs](Demo/DemoJolt.cs) | Boxes falling onto the ground with Jolt Physics, drawn in 3D with OpenGL |