Close M1: real triangle, engine.input, screenshot-to-file capture
All three plugins M1 called for now exist over Silk.NET, and the milestone's actual claim is proven against a live GL context, not just argued: edit a plugin's code, rebuild just it, reload it while a real window stays open, see the change with no app restart. Verified directly this time — two PNGs of the same running window, before and after a live reload (orange triangle -> green, same process, same window, same GL context throughout) — not by analogy to the earlier clear-color version. engine.render, upgraded from clear-color to real geometry: - Vertex/fragment shaders compiled and linked at Configure() time, with real error checking (GetShader/GetProgram *Status + InfoLog on failure) rather than trusting hand-typed GLSL to just work. - VAO/VBO for a hardcoded triangle; Shutdown() deletes all three GL objects rather than leaking them across reloads. - unsafe confined to Configure() (VertexAttribPointer takes a raw offset pointer) via a narrow, documented override of Directory.Build.props' default — native graphics interop, not the kernel data structures docs/kernel-contract.md §7 was written against. engine.input: publishes IEngineInput (keyboard state) via Silk.NET.Input. Reuses Silk.NET's own Key enum rather than inventing one, same call as IEngineWindow.Native. Loads and constructs cleanly against a real window; nothing reacts to it yet since there's no gameplay code to. IScreenCapture (new, engine.render): reads the frame back via ReadPixels and writes a PNG. No SixLabors.ImageSharp — checked its license first and it isn't MIT/Apache (revenue-gated), which would have been a real surprise for downstream users of an MIT engine. PngWriter is a from-scratch encoder instead: ZLibStream (BCL, .NET 6+) for the one genuinely hard part, a correctly zlib-wrapped DEFLATE stream; chunk framing and CRC32 are small enough to get right and to verify by actually decoding files this wrote (done repeatedly, by hand, across this session). Engine.Host: "screenshot <path>" joins "r <plugin-id>" as a live stdin command, plus a non-interactive --screenshot/--screenshot-after- frames pair that captures once and exits — for scripts and agents that can't easily hold a pipe open into a long-running process. Real bug found and fixed in PluginHost, not specific to any one environment: loading a Contracts assembly into the Default ALC never set up resolution for ITS OWN dependencies. engine.windowing's and engine.render's Contracts both need Silk.NET packages and loaded fine anyway, by accident — Engine.Host references those two Contracts projects directly (to drive the windowed loop and screenshot capture), so their dependencies were already sitting in Engine.Host's own output directory. engine.input's Contracts has no such lucky coincidence and failed with a real FileNotFoundException. Fixed by hooking AssemblyLoadContext.Default.Resolving with an AssemblyDependencyResolver per loaded Contracts path — mirroring what PluginLoadContext already does for collectible ALCs, applied to the one path that never had it. Hooked once per process via a static list/flag, not per PluginHost instance, specifically to avoid a PluginHost instance becoming unreclaimable through its own event subscription. Not covered by automated tests, deliberately, same reasoning as the windowing/render pass: opening a real window and reading back a real framebuffer both need a real display. Verified by hand instead, documented above and in commit history rather than asserted. README status: M1 done, not "in progress." Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01N1qPfzq8TDCUMFMV3UwV5N
This commit is contained in:
@@ -2,6 +2,14 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<EnableDynamicLoading>true</EnableDynamicLoading>
|
||||
|
||||
<!-- Narrow, deliberate exception to Directory.Build.props' default:
|
||||
Silk.NET.OpenGL's VertexAttribPointer takes a raw offset pointer,
|
||||
and that's native graphics interop, not the kind of kernel data
|
||||
structure docs/kernel-contract.md §7 was written to keep unsafe
|
||||
out of. Confined to Configure() — see the `unsafe` on that one
|
||||
method, not this whole file. -->
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -11,6 +19,7 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Engine.Kernel\Engine.Kernel.csproj" />
|
||||
<ProjectReference Include="..\..\engine.windowing\Engine.Windowing.Contracts\Engine.Windowing.Contracts.csproj" />
|
||||
<ProjectReference Include="..\Engine.Render.Contracts\Engine.Render.Contracts.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using Engine.Render.Contracts;
|
||||
using Engine.Windowing.Contracts;
|
||||
using Silk.NET.OpenGL;
|
||||
|
||||
namespace Engine.Render;
|
||||
|
||||
internal sealed class GlScreenCapture(GL gl, IEngineWindow window) : IScreenCapture
|
||||
{
|
||||
public void CaptureToFile(string path)
|
||||
{
|
||||
var size = window.Native.FramebufferSize;
|
||||
var width = size.X;
|
||||
var height = size.Y;
|
||||
var stride = width * 4;
|
||||
|
||||
var bottomUp = new byte[stride * height];
|
||||
gl.ReadPixels(0, 0, (uint)width, (uint)height, PixelFormat.Rgba, PixelType.UnsignedByte, bottomUp.AsSpan());
|
||||
|
||||
// OpenGL's row 0 is the bottom of the image; PngWriter wants row 0
|
||||
// to be the top.
|
||||
var topDown = new byte[bottomUp.Length];
|
||||
for (var y = 0; y < height; y++)
|
||||
Array.Copy(bottomUp, (height - 1 - y) * stride, topDown, y * stride, stride);
|
||||
|
||||
PngWriter.Write(path, width, height, topDown);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
|
||||
namespace Engine.Render;
|
||||
|
||||
/// <summary>
|
||||
/// Minimal PNG encoder: 8-bit RGBA, uncompressed-filter scanlines (filter
|
||||
/// type 0, "None"), one IDAT chunk. No external dependency —
|
||||
/// SixLabors.ImageSharp was considered and rejected: its license isn't
|
||||
/// MIT or Apache (it's revenue-gated), and pulling that into an MIT
|
||||
/// engine's own screenshot tooling would be exactly the kind of surprise
|
||||
/// a downstream user shouldn't have to discover later. <see
|
||||
/// cref="ZLibStream"/> (BCL, since .NET 6) does the one genuinely hard
|
||||
/// part — a correctly zlib-wrapped DEFLATE stream — so what's left here
|
||||
/// (chunk framing, CRC32) is small enough to get right and to verify by
|
||||
/// actually opening a file this writes.
|
||||
/// </summary>
|
||||
internal static class PngWriter
|
||||
{
|
||||
private static readonly byte[] Signature = [137, 80, 78, 71, 13, 10, 26, 10];
|
||||
private static readonly uint[] Crc32Table = BuildCrc32Table();
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="topDownRgba"/> is <paramref name="width"/> *
|
||||
/// <paramref name="height"/> * 4 bytes, row 0 first (top of the
|
||||
/// image). OpenGL's ReadPixels returns rows bottom-first — flip
|
||||
/// before calling this, not after; this writer has no opinion about
|
||||
/// where the bytes came from.
|
||||
/// </summary>
|
||||
public static void Write(string path, int width, int height, ReadOnlySpan<byte> topDownRgba)
|
||||
{
|
||||
using var file = File.Create(path);
|
||||
file.Write(Signature);
|
||||
WriteChunk(file, "IHDR", BuildIhdr(width, height));
|
||||
WriteChunk(file, "IDAT", BuildIdat(width, height, topDownRgba));
|
||||
WriteChunk(file, "IEND", []);
|
||||
}
|
||||
|
||||
private static byte[] BuildIhdr(int width, int height)
|
||||
{
|
||||
var ihdr = new byte[13];
|
||||
WriteUInt32BE(ihdr, 0, (uint)width);
|
||||
WriteUInt32BE(ihdr, 4, (uint)height);
|
||||
ihdr[8] = 8; // bit depth
|
||||
ihdr[9] = 6; // color type: RGBA
|
||||
ihdr[10] = 0; // compression method: deflate (the only one PNG defines)
|
||||
ihdr[11] = 0; // filter method: adaptive (per-scanline filter byte)
|
||||
ihdr[12] = 0; // interlace method: none
|
||||
return ihdr;
|
||||
}
|
||||
|
||||
private static byte[] BuildIdat(int width, int height, ReadOnlySpan<byte> rgba)
|
||||
{
|
||||
var stride = width * 4;
|
||||
using var compressed = new MemoryStream();
|
||||
|
||||
using (var zlib = new ZLibStream(compressed, CompressionLevel.Optimal, leaveOpen: true))
|
||||
{
|
||||
var filterByte = new byte[1]; // 0 = "None" — every scanline, unfiltered
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
zlib.Write(filterByte);
|
||||
zlib.Write(rgba.Slice(y * stride, stride));
|
||||
}
|
||||
}
|
||||
|
||||
return compressed.ToArray();
|
||||
}
|
||||
|
||||
private static void WriteChunk(Stream stream, string type, byte[] data)
|
||||
{
|
||||
var typeBytes = Encoding.ASCII.GetBytes(type);
|
||||
|
||||
Span<byte> length = stackalloc byte[4];
|
||||
WriteUInt32BE(length, 0, (uint)data.Length);
|
||||
stream.Write(length);
|
||||
|
||||
stream.Write(typeBytes);
|
||||
stream.Write(data);
|
||||
|
||||
Span<byte> crc = stackalloc byte[4];
|
||||
WriteUInt32BE(crc, 0, Crc32(typeBytes, data));
|
||||
stream.Write(crc);
|
||||
}
|
||||
|
||||
private static void WriteUInt32BE(Span<byte> buffer, int offset, uint value)
|
||||
{
|
||||
buffer[offset] = (byte)(value >> 24);
|
||||
buffer[offset + 1] = (byte)(value >> 16);
|
||||
buffer[offset + 2] = (byte)(value >> 8);
|
||||
buffer[offset + 3] = (byte)value;
|
||||
}
|
||||
|
||||
private static uint[] BuildCrc32Table()
|
||||
{
|
||||
var table = new uint[256];
|
||||
for (uint n = 0; n < 256; n++)
|
||||
{
|
||||
var c = n;
|
||||
for (var k = 0; k < 8; k++)
|
||||
c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1;
|
||||
table[n] = c;
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private static uint Crc32(byte[] type, byte[] data)
|
||||
{
|
||||
var crc = 0xFFFFFFFFu;
|
||||
|
||||
foreach (var b in type)
|
||||
crc = Crc32Table[(crc ^ b) & 0xFF] ^ (crc >> 8);
|
||||
foreach (var b in data)
|
||||
crc = Crc32Table[(crc ^ b) & 0xFF] ^ (crc >> 8);
|
||||
|
||||
return crc ^ 0xFFFFFFFFu;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
using Engine.Kernel.Plugins;
|
||||
using Engine.Kernel.Scheduling;
|
||||
using Engine.Kernel.World;
|
||||
using Engine.Render.Contracts;
|
||||
using Engine.Windowing.Contracts;
|
||||
using Silk.NET.OpenGL;
|
||||
|
||||
namespace Engine.Render;
|
||||
|
||||
/// <summary>
|
||||
/// M1's minimal render pipeline: clears the window to a color and swaps
|
||||
/// buffers, once per Render stage. No Contracts assembly — nothing here is
|
||||
/// a type another plugin needs to reference yet (see the null-Contracts
|
||||
/// note on PluginManifest). See M1 in docs/kernel-contract.md §8.
|
||||
/// M1's render pipeline: one hardcoded triangle, drawn every Render stage.
|
||||
/// See M1 in docs/kernel-contract.md §8.
|
||||
///
|
||||
/// This is the whole point of M1's "done when": change ClearColor, rebuild
|
||||
/// just this plugin, and reload it while the window from engine.windowing
|
||||
/// stays open — the color changes with no app restart. Verified by hand,
|
||||
/// not by an automated test — opening a real window needs a real display,
|
||||
/// which isn't something to assume of every environment this runs in.
|
||||
/// This is the whole point of M1's "done when": change TriangleColor,
|
||||
/// rebuild just this plugin, and reload it while the window from
|
||||
/// engine.windowing stays open — the color changes with no app restart.
|
||||
/// Verified by hand against a real window and a live GL context, and via
|
||||
/// IScreenCapture — no external image library; see the note on PngWriter
|
||||
/// for why.
|
||||
///
|
||||
/// engine.windowing alone produces a window that never becomes visible on
|
||||
/// Wayland — unlike X11, a Wayland surface with no committed buffer simply
|
||||
@@ -26,33 +26,130 @@ namespace Engine.Render;
|
||||
/// </summary>
|
||||
public sealed class RenderPlugin : IPlugin
|
||||
{
|
||||
private static readonly float[] ClearColor = [0.25f, 0.55f, 0.85f, 1f];
|
||||
private const string VertexShaderSource = """
|
||||
#version 330 core
|
||||
layout (location = 0) in vec2 aPosition;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = vec4(aPosition, 0.0, 1.0);
|
||||
}
|
||||
""";
|
||||
|
||||
private const string FragmentShaderSource = """
|
||||
#version 330 core
|
||||
out vec4 FragColor;
|
||||
uniform vec4 uColor;
|
||||
|
||||
void main()
|
||||
{
|
||||
FragColor = uColor;
|
||||
}
|
||||
""";
|
||||
|
||||
private static readonly float[] TriangleColor = [0.2f, 0.8f, 0.4f, 1f];
|
||||
|
||||
private static readonly float[] Vertices =
|
||||
[
|
||||
0.0f, 0.6f,
|
||||
-0.6f, -0.6f,
|
||||
0.6f, -0.6f,
|
||||
];
|
||||
|
||||
private GL? _gl;
|
||||
private IEngineWindow? _window;
|
||||
private uint _vao;
|
||||
private uint _vbo;
|
||||
private uint _program;
|
||||
private int _colorLocation;
|
||||
|
||||
public void Configure(IPluginContext ctx)
|
||||
public unsafe void Configure(IPluginContext ctx)
|
||||
{
|
||||
_window = ctx.Services.Require<IEngineWindow>();
|
||||
_window.Native.GLContext!.MakeCurrent();
|
||||
_gl = _window.Native.CreateOpenGL();
|
||||
|
||||
_program = LinkProgram(_gl, VertexShaderSource, FragmentShaderSource);
|
||||
_colorLocation = _gl.GetUniformLocation(_program, "uColor");
|
||||
|
||||
_vao = _gl.GenVertexArray();
|
||||
_gl.BindVertexArray(_vao);
|
||||
|
||||
_vbo = _gl.GenBuffer();
|
||||
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, _vbo);
|
||||
_gl.BufferData<float>(BufferTargetARB.ArrayBuffer, Vertices, BufferUsageARB.StaticDraw);
|
||||
|
||||
_gl.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, 2 * sizeof(float), (void*)0);
|
||||
_gl.EnableVertexAttribArray(0);
|
||||
_gl.BindVertexArray(0);
|
||||
|
||||
ctx.Services.Provide<IScreenCapture>(new GlScreenCapture(_gl, _window));
|
||||
ctx.Schedule.Add(Stage.Render, Draw);
|
||||
ctx.Log.Info("GL context created");
|
||||
ctx.Log.Info("GL context created, triangle ready");
|
||||
}
|
||||
|
||||
public void Shutdown(IPluginContext ctx)
|
||||
{
|
||||
ctx.Schedule.RemoveAllFrom("engine.render");
|
||||
_gl?.Dispose();
|
||||
ctx.Services.Revoke<IScreenCapture>();
|
||||
|
||||
if (_gl is not null)
|
||||
{
|
||||
_gl.DeleteVertexArray(_vao);
|
||||
_gl.DeleteBuffer(_vbo);
|
||||
_gl.DeleteProgram(_program);
|
||||
_gl.Dispose();
|
||||
}
|
||||
|
||||
_gl = null;
|
||||
_window = null;
|
||||
}
|
||||
|
||||
private void Draw(IWorld world)
|
||||
{
|
||||
_gl!.ClearColor(ClearColor[0], ClearColor[1], ClearColor[2], ClearColor[3]);
|
||||
_gl!.ClearColor(0.05f, 0.05f, 0.08f, 1f);
|
||||
_gl.Clear(ClearBufferMask.ColorBufferBit);
|
||||
|
||||
_gl.UseProgram(_program);
|
||||
_gl.Uniform4(_colorLocation, TriangleColor[0], TriangleColor[1], TriangleColor[2], TriangleColor[3]);
|
||||
_gl.BindVertexArray(_vao);
|
||||
_gl.DrawArrays(PrimitiveType.Triangles, 0, 3);
|
||||
|
||||
_window!.Native.GLContext!.SwapBuffers();
|
||||
}
|
||||
|
||||
private static uint LinkProgram(GL gl, string vertexSource, string fragmentSource)
|
||||
{
|
||||
var vertex = CompileShader(gl, ShaderType.VertexShader, vertexSource);
|
||||
var fragment = CompileShader(gl, ShaderType.FragmentShader, fragmentSource);
|
||||
|
||||
var program = gl.CreateProgram();
|
||||
gl.AttachShader(program, vertex);
|
||||
gl.AttachShader(program, fragment);
|
||||
gl.LinkProgram(program);
|
||||
|
||||
gl.GetProgram(program, GLEnum.LinkStatus, out var linked);
|
||||
if (linked == 0)
|
||||
throw new InvalidOperationException($"Shader program failed to link: {gl.GetProgramInfoLog(program)}");
|
||||
|
||||
gl.DetachShader(program, vertex);
|
||||
gl.DetachShader(program, fragment);
|
||||
gl.DeleteShader(vertex);
|
||||
gl.DeleteShader(fragment);
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
private static uint CompileShader(GL gl, ShaderType type, string source)
|
||||
{
|
||||
var shader = gl.CreateShader(type);
|
||||
gl.ShaderSource(shader, source);
|
||||
gl.CompileShader(shader);
|
||||
|
||||
gl.GetShader(shader, GLEnum.CompileStatus, out var compiled);
|
||||
if (compiled == 0)
|
||||
throw new InvalidOperationException($"{type} failed to compile: {gl.GetShaderInfoLog(shader)}");
|
||||
|
||||
return shader;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user