From 7a3b72d84368872b885094e34fe8cdf5f7989460 Mon Sep 17 00:00:00 2001 From: Rian Drake <129921000+werkz-by-drake@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:10:25 +1300 Subject: [PATCH] samples: add Hello/Demo samples for most BRUTAL packages (#19) Add samples/, a collection of single-file .NET 10 apps run with `dotnet run .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. --- README.md | 4 +- samples/Demo/DemoBox2D.cs | 197 +++++++++ samples/Demo/DemoGltfViewer.cs | 431 ++++++++++++++++++++ samples/Demo/DemoImGui.cs | 140 +++++++ samples/Demo/DemoJolt.cs | 256 ++++++++++++ samples/Demo/DemoRenderDoc.cs | 191 +++++++++ samples/Demo/DemoSdl.cs | 134 +++++++ samples/Demo/DemoTexturedQuad.cs | 241 +++++++++++ samples/Demo/DemoVulkan.cs | 485 +++++++++++++++++++++++ samples/Hello/HelloBox2D.cs | 45 +++ samples/Hello/HelloCollections.cs | 35 ++ samples/Hello/HelloConcurrency.cs | 27 ++ samples/Hello/HelloCore.cs | 29 ++ samples/Hello/HelloFmod.cs | 53 +++ samples/Hello/HelloGlfw.cs | 49 +++ samples/Hello/HelloGli.cs | 49 +++ samples/Hello/HelloGltf.cs | 50 +++ samples/Hello/HelloImGui.cs | 115 ++++++ samples/Hello/HelloImGuiAbstractions.cs | 85 ++++ samples/Hello/HelloImGuiExtensions.cs | 114 ++++++ samples/Hello/HelloImGuiFreeType.cs | 72 ++++ samples/Hello/HelloImPlot.cs | 77 ++++ samples/Hello/HelloJolt.cs | 98 +++++ samples/Hello/HelloKtx.cs | 57 +++ samples/Hello/HelloLocalization.cs | 24 ++ samples/Hello/HelloLogging.cs | 28 ++ samples/Hello/HelloMaths.cs | 24 ++ samples/Hello/HelloMemory.cs | 31 ++ samples/Hello/HelloMeshOptimizer.cs | 40 ++ samples/Hello/HelloMonitorHost.cs | 41 ++ samples/Hello/HelloNativeFileDialog.cs | 34 ++ samples/Hello/HelloNotCurses.cs | 29 ++ samples/Hello/HelloNumerics.cs | 28 ++ samples/Hello/HelloOpenAl.cs | 43 ++ samples/Hello/HelloOpenGl.cs | 145 +++++++ samples/Hello/HelloRakNet.cs | 85 ++++ samples/Hello/HelloRenderDoc.cs | 23 ++ samples/Hello/HelloRenderDocImGui.cs | 67 ++++ samples/Hello/HelloRenderMesh.cs | 29 ++ samples/Hello/HelloSdl.cs | 65 +++ samples/Hello/HelloSdlImage.cs | 45 +++ samples/Hello/HelloSdlMixer.cs | 52 +++ samples/Hello/HelloSdlTtf.cs | 77 ++++ samples/Hello/HelloShaderC.cs | 37 ++ samples/Hello/HelloSlang.cs | 48 +++ samples/Hello/HelloStb.cs | 40 ++ samples/Hello/HelloStrings.cs | 25 ++ samples/Hello/HelloTexture.cs | 54 +++ samples/Hello/HelloVulkan.cs | 105 +++++ samples/Hello/HelloVulkanAbstractions.cs | 113 ++++++ samples/Hello/HelloVulkanVma.cs | 99 +++++ samples/README.md | 135 +++++++ 52 files changed, 4599 insertions(+), 1 deletion(-) create mode 100644 samples/Demo/DemoBox2D.cs create mode 100644 samples/Demo/DemoGltfViewer.cs create mode 100644 samples/Demo/DemoImGui.cs create mode 100644 samples/Demo/DemoJolt.cs create mode 100644 samples/Demo/DemoRenderDoc.cs create mode 100644 samples/Demo/DemoSdl.cs create mode 100644 samples/Demo/DemoTexturedQuad.cs create mode 100644 samples/Demo/DemoVulkan.cs create mode 100644 samples/Hello/HelloBox2D.cs create mode 100644 samples/Hello/HelloCollections.cs create mode 100644 samples/Hello/HelloConcurrency.cs create mode 100644 samples/Hello/HelloCore.cs create mode 100644 samples/Hello/HelloFmod.cs create mode 100644 samples/Hello/HelloGlfw.cs create mode 100644 samples/Hello/HelloGli.cs create mode 100644 samples/Hello/HelloGltf.cs create mode 100644 samples/Hello/HelloImGui.cs create mode 100644 samples/Hello/HelloImGuiAbstractions.cs create mode 100644 samples/Hello/HelloImGuiExtensions.cs create mode 100644 samples/Hello/HelloImGuiFreeType.cs create mode 100644 samples/Hello/HelloImPlot.cs create mode 100644 samples/Hello/HelloJolt.cs create mode 100644 samples/Hello/HelloKtx.cs create mode 100644 samples/Hello/HelloLocalization.cs create mode 100644 samples/Hello/HelloLogging.cs create mode 100644 samples/Hello/HelloMaths.cs create mode 100644 samples/Hello/HelloMemory.cs create mode 100644 samples/Hello/HelloMeshOptimizer.cs create mode 100644 samples/Hello/HelloMonitorHost.cs create mode 100644 samples/Hello/HelloNativeFileDialog.cs create mode 100644 samples/Hello/HelloNotCurses.cs create mode 100644 samples/Hello/HelloNumerics.cs create mode 100644 samples/Hello/HelloOpenAl.cs create mode 100644 samples/Hello/HelloOpenGl.cs create mode 100644 samples/Hello/HelloRakNet.cs create mode 100644 samples/Hello/HelloRenderDoc.cs create mode 100644 samples/Hello/HelloRenderDocImGui.cs create mode 100644 samples/Hello/HelloRenderMesh.cs create mode 100644 samples/Hello/HelloSdl.cs create mode 100644 samples/Hello/HelloSdlImage.cs create mode 100644 samples/Hello/HelloSdlMixer.cs create mode 100644 samples/Hello/HelloSdlTtf.cs create mode 100644 samples/Hello/HelloShaderC.cs create mode 100644 samples/Hello/HelloSlang.cs create mode 100644 samples/Hello/HelloStb.cs create mode 100644 samples/Hello/HelloStrings.cs create mode 100644 samples/Hello/HelloTexture.cs create mode 100644 samples/Hello/HelloVulkan.cs create mode 100644 samples/Hello/HelloVulkanAbstractions.cs create mode 100644 samples/Hello/HelloVulkanVma.cs create mode 100644 samples/README.md diff --git a/README.md b/README.md index 9efcd51..1caaef8 100644 --- a/README.md +++ b/README.md @@ -125,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`. diff --git a/samples/Demo/DemoBox2D.cs b/samples/Demo/DemoBox2D.cs new file mode 100644 index 0000000..6cae88a --- /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.1 +#:package Ahwoo.Brutal.Glfw@2026.10.4 +#:package Ahwoo.Brutal.OpenGl@2026.10.1 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +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..f2cea74 --- /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.2 +#:package Ahwoo.Brutal.MeshOptimizer@2026.10.1 +#:package Ahwoo.Brutal.Glfw@2026.10.4 +#:package Ahwoo.Brutal.OpenGl@2026.10.1 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +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..83fe414 --- /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.2 +#:package Ahwoo.Brutal.ImGui.Backends@2026.10.2 +#:package Ahwoo.Brutal.ImGui.FreeType@2026.10.2 +#:package Ahwoo.Brutal.ImPlot@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 + +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..234eefd --- /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.2 +#:package Ahwoo.Brutal.Glfw@2026.10.4 +#:package Ahwoo.Brutal.OpenGl@2026.10.1 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +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..ca025a6 --- /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.4 +#:package Ahwoo.Brutal.OpenGl@2026.10.1 +#:package Ahwoo.Brutal.RenderDoc@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; +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..39d196f --- /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.2 +#:package Ahwoo.Brutal.Sdl.Image@2026.10.2 +#:package Ahwoo.Brutal.Sdl.Mixer@2026.10.2 +#:package Ahwoo.Brutal.Sdl.Ttf@2026.10.2 + +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..7b53e13 --- /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.4 +#:package Ahwoo.Brutal.Ktx@2026.10.1 +#:package Ahwoo.Brutal.OpenGl@2026.10.1 +#:package Ahwoo.Brutal.Texture@2026.10.2 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +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..428cc81 --- /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.2 +#:package Ahwoo.Brutal.Vulkan.Abstractions@2026.10.2 +#:package Ahwoo.Brutal.Vulkan.Vma@2026.10.2 +#:package Ahwoo.Brutal.Glfw@2026.10.4 +#:package Ahwoo.Brutal.ShaderC@2026.10.2 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Memory@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 +#:package Ahwoo.Brutal.Strings@2026.10.1 + +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..c5429a8 --- /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.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()}" + ); + } + } +} diff --git a/samples/Hello/HelloCollections.cs b/samples/Hello/HelloCollections.cs new file mode 100644 index 0000000..8761b49 --- /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.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-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..749b561 --- /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.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}"); +} diff --git a/samples/Hello/HelloCore.cs b/samples/Hello/HelloCore.cs new file mode 100644 index 0000000..2bccd5a --- /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.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(); +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..4908660 --- /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.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(); +} diff --git a/samples/Hello/HelloGlfw.cs b/samples/Hello/HelloGlfw.cs new file mode 100644 index 0000000..593a9fc --- /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.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(); +} diff --git a/samples/Hello/HelloGli.cs b/samples/Hello/HelloGli.cs new file mode 100644 index 0000000..3305bd9 --- /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.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(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..2d8d647 --- /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.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(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..152dfbf --- /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.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(); + } +} diff --git a/samples/Hello/HelloImGuiAbstractions.cs b/samples/Hello/HelloImGuiAbstractions.cs new file mode 100644 index 0000000..7f4d7e6 --- /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.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}"); +} diff --git a/samples/Hello/HelloImGuiExtensions.cs b/samples/Hello/HelloImGuiExtensions.cs new file mode 100644 index 0000000..665f0a9 --- /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.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, +} diff --git a/samples/Hello/HelloImGuiFreeType.cs b/samples/Hello/HelloImGuiFreeType.cs new file mode 100644 index 0000000..7409f8a --- /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.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}"); +} diff --git a/samples/Hello/HelloImPlot.cs b/samples/Hello/HelloImPlot.cs new file mode 100644 index 0000000..a76dc87 --- /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.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" + ); +} diff --git a/samples/Hello/HelloJolt.cs b/samples/Hello/HelloJolt.cs new file mode 100644 index 0000000..7da20c2 --- /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.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); +} diff --git a/samples/Hello/HelloKtx.cs b/samples/Hello/HelloKtx.cs new file mode 100644 index 0000000..1b4898c --- /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.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" + ); + } +} diff --git a/samples/Hello/HelloLocalization.cs b/samples/Hello/HelloLocalization.cs new file mode 100644 index 0000000..23f1bcf --- /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.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 { ["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..e05b905 --- /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.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"); diff --git a/samples/Hello/HelloMaths.cs b/samples/Hello/HelloMaths.cs new file mode 100644 index 0000000..9297fbb --- /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.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()})"); diff --git a/samples/Hello/HelloMemory.cs b/samples/Hello/HelloMemory.cs new file mode 100644 index 0000000..ca4f42b --- /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.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(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..2b1cda7 --- /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.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(); +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..73f3118 --- /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.2 +#:package Ahwoo.Brutal.Monitor.Common@2026.10.2 + +// 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..77b518c --- /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.2 + +// 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..91788d1 --- /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.0 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +// 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..a84b83b --- /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.1 + +// 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..7b686be --- /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.2 + +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..6f53d3f --- /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.4 +#:package Ahwoo.Brutal.OpenGl@2026.10.1 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +// 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..83e77ee --- /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.2 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Strings@2026.10.1 + +// 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..3b185de --- /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.2 + +// 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..0455d45 --- /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.2 +#:package Ahwoo.Brutal.RenderDoc@2026.10.2 +#:package Ahwoo.Brutal.RenderDoc.ImGui@2026.10.2 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +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..19d2fa9 --- /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.1 +#:package Ahwoo.Brutal.Collections@2026.10.1 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +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..87b8125 --- /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.2 + +// 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..a851e6a --- /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.2 +#:package Ahwoo.Brutal.Sdl.Image@2026.10.2 + +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..9638cf9 --- /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.2 +#:package Ahwoo.Brutal.Sdl.Mixer@2026.10.2 + +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..002e948 --- /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.2 +#:package Ahwoo.Brutal.Sdl.Ttf@2026.10.2 + +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..f53208f --- /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.2 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Strings@2026.10.1 + +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..3b9cce5 --- /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.1 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Strings@2026.10.1 + +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..092ce6b --- /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.2 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +// 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..57a66e8 --- /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.1 + +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..01b8e2a --- /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.2 +#:package Ahwoo.Brutal.Texture.Abstractions@2026.10.2 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +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..36998f0 --- /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.2 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Strings@2026.10.1 + +// 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..f025bfa --- /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.2 +#:package Ahwoo.Brutal.Vulkan.Abstractions@2026.10.2 +#:package Ahwoo.Brutal.Collections@2026.10.1 +#:package Ahwoo.Brutal.Core@2026.10.1 +#:package Ahwoo.Brutal.Numerics@2026.10.1 + +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..5437ed9 --- /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.2 +#:package Ahwoo.Brutal.Vulkan.Vma@2026.10.2 +#:package Ahwoo.Brutal.Core@2026.10.1 + +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 |