Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git
commit 242ce4fb8488980e61f0c038cebc56ae78f47958
parent cb41c818d211675d2c46257ced7a2216d556df9f
Author: sentomk <sentomk@proton.me>
Date:   Fri, 16 Oct 2026 16:01:34 +0800

feat: present the software framebuffer through Metal

Add window_present(): the frame is uploaded to a texture, copied into the drawable of a CAMetalLayer and shown. The drawable has the size of the frame and the window system scales it with nearest-neighbor filtering. Waiting for the next drawable paces the loop at the refresh rate of the display. The main loop now presents a test picture drawn by the software rasterizer.

Diffstat:
Msrc/main.cpp | 29+++++++++++++++++++++++++----
Msrc/platform/window.h | 12++++++++++++
Msrc/platform/window_mac.mm | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
3 files changed, 122 insertions(+), 8 deletions(-)

diff --git a/src/main.cpp b/src/main.cpp @@ -1,11 +1,29 @@ -#include <chrono> #include <cstdio> #include <cstdlib> -#include <thread> #include "core/clock.h" #include "core/fixed_step.h" #include "platform/window.h" +#include "render/frame_buffer.h" +#include "render/raster.h" + +/// @brief Draws a test picture: a gradient, a triangle and a frame around it. +static void draw_scene(kumo::FrameBuffer& frame) { + for (int y = 0; y < frame.height; ++y) { + for (int x = 0; x < frame.width; ++x) { + frame.at(x, y) = kumo::make_color( + static_cast<uint8_t>(x * 255 / (frame.width - 1)), + static_cast<uint8_t>(y * 255 / (frame.height - 1)), 96); + } + } + kumo::fill_triangle(frame, kumo::pixel_point(160, 30), + kumo::pixel_point(240, 150), kumo::pixel_point(80, 150), + kumo::make_color(250, 220, 60)); + kumo::draw_line(frame, 0, 0, frame.width - 1, frame.height - 1, + kumo::make_color(255, 255, 255)); + kumo::draw_line(frame, 0, frame.height - 1, frame.width - 1, 0, + kumo::make_color(0, 0, 0)); +} int main() { kumo::Window* window = kumo::window_create({"Kumo", 1280, 720}); @@ -14,6 +32,9 @@ int main() { return EXIT_FAILURE; } + kumo::FrameBuffer frame(320, 180); + draw_scene(frame); + kumo::SystemClock clock; kumo::FrameTimer timer(clock); kumo::FixedStep step(kumo::step_from_hz(60), kumo::milliseconds(250)); @@ -34,8 +55,8 @@ int main() { kumo::window_set_title(window, title); } - // Until presenting a frame paces the loop, do not spin a whole core. - std::this_thread::sleep_for(std::chrono::milliseconds(1)); + // Waits for the display, which paces the loop. + kumo::window_present(window, frame); } kumo::window_destroy(window); diff --git a/src/platform/window.h b/src/platform/window.h @@ -10,6 +10,8 @@ namespace kumo { +struct FrameBuffer; + /// @brief Opaque window handle; the definition lives in the platform file. struct Window; @@ -43,6 +45,16 @@ void window_poll_events(Window* window); /// open until window_destroy(), so the caller decides when to shut down. bool window_should_close(const Window* window); +/// @brief Shows a frame in the window. +/// +/// The frame is scaled to fill the content of the window; the window system +/// does the scaling, with nearest-neighbor filtering so that pixels stay sharp. +/// The call waits for the display to be ready for the next frame, so a loop +/// that presents once per iteration runs at the refresh rate of the display. +/// +/// @param framebuffer The pixels to show. Its size may change between calls. +void window_present(Window* window, const FrameBuffer& framebuffer); + /// @brief Changes the title of the window. /// /// @param title UTF-8 text. diff --git a/src/platform/window_mac.mm b/src/platform/window_mac.mm @@ -1,9 +1,13 @@ /// @file platform/window_mac.mm -/// @brief macOS (Cocoa) implementation of platform/window.h +/// @brief macOS (Cocoa, Metal) implementation of platform/window.h. #include "platform/window.h" #import <Cocoa/Cocoa.h> +#import <Metal/Metal.h> +#import <QuartzCore/CAMetalLayer.h> + +#include "render/frame_buffer.h" /// @brief Window delegate that records close requests instead of closing. @interface KumoWindowDelegate : NSObject <NSWindowDelegate> @@ -19,12 +23,26 @@ } @end +/// @brief A view whose backing layer is a CAMetalLayer, so that Metal can draw +/// into it and AppKit still sizes the layer to the view. +@interface KumoView : NSView +@end + +@implementation KumoView +- (CALayer*)makeBackingLayer { + return [CAMetalLayer layer]; +} +@end + namespace kumo { -/// @brief Cocoa state behind the opaque Window handle. +/// @brief Cocoa and Metal state behind the opaque Window handle. struct Window { NSWindow* ns_window; KumoWindowDelegate* delegate; + CAMetalLayer* layer; + id<MTLCommandQueue> queue; + id<MTLTexture> texture; ///< Holds the last frame; made again on a new size. }; /// @brief Creates the application object and a minimal menu with Cmd+Q. @@ -56,6 +74,9 @@ Window* window_create(const WindowDesc& desc) { application_ready = true; } + id<MTLDevice> device = MTLCreateSystemDefaultDevice(); + if (device == nil) return nullptr; + NSWindowStyleMask style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable; NSRect frame = NSMakeRect(0, 0, desc.width, desc.height); @@ -65,6 +86,21 @@ Window* window_create(const WindowDesc& desc) { defer:NO]; if (ns_window == nil) return nullptr; + KumoView* view = [[KumoView alloc] initWithFrame:frame]; + [view setWantsLayer:YES]; + CAMetalLayer* layer = (CAMetalLayer*)view.layer; + layer.device = device; + // Color is 0xAARRGGBB in a 32-bit integer, which is the bytes B, G, R, A on + // a little-endian machine: exactly this format, so no conversion is needed. + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + // The frame is copied into the drawable, which a framebuffer-only texture + // does not allow. + layer.framebufferOnly = NO; + // The drawable has the size of the frame, not of the window; the window + // system stretches it. Nearest keeps the pixels square and sharp. + layer.magnificationFilter = kCAFilterNearest; + [ns_window setContentView:view]; + KumoWindowDelegate* delegate = [[KumoWindowDelegate alloc] init]; // We own the reference through Window; AppKit must not release it on close. [ns_window setReleasedWhenClosed:NO]; @@ -74,7 +110,7 @@ Window* window_create(const WindowDesc& desc) { [ns_window makeKeyAndOrderFront:nil]; [NSApp activate]; - return new Window{ns_window, delegate}; + return new Window{ns_window, delegate, layer, [device newCommandQueue], nil}; } void window_destroy(Window* window) { @@ -85,7 +121,7 @@ void window_destroy(Window* window) { } void window_poll_events(Window* window) { - // Keeps the autoreleased event objects from pilling up cross frames. + // Keeps the autoreleased event objects from piling up across frames. @autoreleasepool { for (;;) { // distantPast: return at once if no event is queued. @@ -106,6 +142,51 @@ void window_poll_events(Window* window) { bool window_should_close(const Window* window) { return window->delegate.should_close; } +void window_present(Window* window, const FrameBuffer& framebuffer) { + @autoreleasepool { + const NSUInteger width = static_cast<NSUInteger>(framebuffer.width); + const NSUInteger height = static_cast<NSUInteger>(framebuffer.height); + + if (window->texture == nil || window->texture.width != width || + window->texture.height != height) { + MTLTextureDescriptor* texture_desc = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:width + height:height + mipmapped:NO]; + window->texture = [window->layer.device newTextureWithDescriptor:texture_desc]; + window->layer.drawableSize = CGSizeMake(width, height); + } + + // Blocks until the display can take another frame: this is the vsync wait. + id<CAMetalDrawable> drawable = [window->layer nextDrawable]; + if (drawable == nil) return; + + [window->texture replaceRegion:MTLRegionMake2D(0, 0, width, height) + mipmapLevel:0 + withBytes:framebuffer.pixels.data() + bytesPerRow:width * sizeof(Color)]; + + id<MTLCommandBuffer> commands = [window->queue commandBuffer]; + id<MTLBlitCommandEncoder> blit = [commands blitCommandEncoder]; + [blit copyFromTexture:window->texture + sourceSlice:0 + sourceLevel:0 + sourceOrigin:MTLOriginMake(0, 0, 0) + sourceSize:MTLSizeMake(width, height, 1) + toTexture:drawable.texture + destinationSlice:0 + destinationLevel:0 + destinationOrigin:MTLOriginMake(0, 0, 0)]; + [blit endEncoding]; + [commands presentDrawable:drawable]; + [commands commit]; + // The texture is written again by the next call, so the copy must be done + // by then. Waiting is cheap next to drawing the frame on the CPU. + [commands waitUntilCompleted]; + } +} + void window_set_title(Window* window, const char* title) { [window->ns_window setTitle:[NSString stringWithUTF8String:title]]; }