samples: add Hello/Demo samples for most BRUTAL packages (#19)

Add samples/, a collection of single-file .NET 10 apps run with
`dotnet run <file>.cs`. Hello/ has one minimal sample per package
that has a public API, many of them headless; Demo/ has fuller
programs that combine packages into a more interesting application.

samples/README.md indexes every sample and covers the layout, error
handling and per-OS requirements.
This commit is contained in:
Rian Drake 2026-10-27 09:10:25 +13:00 • committed by GitHub
commit 7a3b72d843
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
42 changed files with 4599 additions and 1 deletions

View file

@ -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.1
#:package Ahwoo.Brutal.Core@2026.10.1
#:package Ahwoo.Brutal.Numerics@2026.10.1
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()}"
);
}
}
}

View file

@ -0,0 +1,35 @@
/*
* HelloCollections
*
* Uses NativeList<T>, a growable list backed by unmanaged memory: add, insert,
* remove, iterate and edit it as a span.
*/
#:package Ahwoo.Brutal.Collections@2026.10.1
#:package Ahwoo.Brutal.Core@2026.10.1
// 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<T>-like collection backed by unmanaged memory, freed when Run returns.
using var list = new NativeList<int>();
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())}");
}

View file

@ -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.1
// 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}");
}

View file

@ -0,0 +1,29 @@
/*
* HelloCore
*
* Shows a few Brutal.Core basics: platform detection, ByteSize/ElementCount arithmetic and Ptr<T>.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Core@2026.10.1
// 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<float>();
var total = stride * new ElementCount(1024);
Console.WriteLine($"1024 floats = {total}");
var alternative = ByteSize.Of<float>(1024);
Console.WriteLine($"1024 floats = {alternative}");
unsafe
{
var raw = stackalloc int[4] { 10, 20, 30, 40 };
Ptr<int> p = raw;
Console.WriteLine($"p.Value = {p.Value}, p[2] = {p[2]}, p.Offset(1).Value = {p.Offset(1).Value}");
}

View file

@ -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.3
#:package Ahwoo.Brutal.Core@2026.10.1
// 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();
}

View file

@ -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.4
#:package Ahwoo.Brutal.Numerics@2026.10.1
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();
}

49
samples/Hello/HelloGli.cs Normal file
View file

@ -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.1
#:package Ahwoo.Brutal.Numerics@2026.10.1
// 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<byte4>(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"
);
}

View file

@ -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.2
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<byte, float>(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}");

115
samples/Hello/HelloImGui.cs Normal file
View file

@ -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.2
#:package Ahwoo.Brutal.ImGui.Backends@2026.10.2
#:package Ahwoo.Brutal.Core@2026.10.1
#:package Ahwoo.Brutal.Glfw@2026.10.4
#:package Ahwoo.Brutal.Numerics@2026.10.1
#:package Ahwoo.Brutal.OpenGl@2026.10.1
// 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();
}
}

View file

@ -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.2
#:package Ahwoo.Brutal.Core@2026.10.1
#:package Ahwoo.Brutal.ImGui@2026.10.2
#:package Ahwoo.Brutal.Numerics@2026.10.1
// 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}");
}

View file

@ -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.2
#:package Ahwoo.Brutal.Core@2026.10.1
#:package Ahwoo.Brutal.ImGui@2026.10.2
#:package Ahwoo.Brutal.Numerics@2026.10.1
// 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,
}

View file

@ -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.2
#:package Ahwoo.Brutal.ImGui.FreeType@2026.10.2
#:package Ahwoo.Brutal.Core@2026.10.1
#:package Ahwoo.Brutal.Numerics@2026.10.1
#:package Ahwoo.Brutal.Strings@2026.10.1
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}");
}

View file

@ -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.2
#:package Ahwoo.Brutal.ImPlot@2026.10.2
#:package Ahwoo.Brutal.Core@2026.10.1
#:package Ahwoo.Brutal.Numerics@2026.10.1
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"
);
}

View file

@ -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.2
#:package Ahwoo.Brutal.Numerics@2026.10.1
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);
}

57
samples/Hello/HelloKtx.cs Normal file
View file

@ -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.1
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"
);
}
}

View file

@ -0,0 +1,24 @@
/*
* HelloLocalization
*
* Formats localised strings with named variables, then swaps in a French translation.
*/
#:package Ahwoo.Brutal.Localization@2026.10.2
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<string, string> { ["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));

View file

@ -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.2
// 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");

View file

@ -0,0 +1,24 @@
/*
* HelloMaths
*
* Uses the Random extensions to generate numbers, points in shapes and random directions.
*/
#:package Ahwoo.Brutal.Maths@2026.10.1
#:package Ahwoo.Brutal.Numerics@2026.10.1
// 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()})");

View file

@ -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.1
#:package Ahwoo.Brutal.Core@2026.10.1
// 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<int>(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<double>(Math.PI);
Console.WriteLine($"PtrOwner holds {pi.Value}");
}

View file

@ -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.1
#:package Ahwoo.Brutal.Core@2026.10.1
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<int[]>();
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}");
}
}

Some files were not shown because too many files have changed in this diff Show more