Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git

window_mac.mm (8993B) · raw


      1 /// @file platform/window_mac.mm
      2 /// @brief macOS (Cocoa, Metal) implementation of platform/window.h.
      3 
      4 #include "platform/window.h"
      5 
      6 #import <Cocoa/Cocoa.h>
      7 #import <Metal/Metal.h>
      8 #import <QuartzCore/CAMetalLayer.h>
      9 
     10 #include <ptn/patternia.hpp>
     11 
     12 #include "platform/keyboard.h"
     13 #include "render/frame_buffer.h"
     14 
     15 /// @brief Handles close requests and keyboard focus changes.
     16 @interface KumoWindowDelegate : NSObject <NSWindowDelegate> {
     17  @public
     18   kumo::Keyboard keyboard;
     19 }
     20 @property(nonatomic) BOOL should_close;
     21 @end
     22 
     23 @implementation KumoWindowDelegate
     24 /// Called when the close button is pressed. Returning NO keeps the window
     25 /// open; the main loop sees the flag and shuts down on its own terms.
     26 - (BOOL)windowShouldClose:(NSWindow*)sender {
     27   self.should_close = YES;
     28   return NO;
     29 }
     30 
     31 - (void)windowDidResignKey:(NSNotification*)notification {
     32   (void)notification;
     33   keyboard.release_all();
     34 }
     35 @end
     36 
     37 /// @brief A view whose backing layer is a CAMetalLayer, so that Metal can draw
     38 ///        into it and AppKit still sizes the layer to the view.
     39 @interface KumoView : NSView
     40 @end
     41 
     42 @implementation KumoView
     43 - (CALayer*)makeBackingLayer {
     44   return [CAMetalLayer layer];
     45 }
     46 @end
     47 
     48 namespace kumo {
     49 
     50 /// @brief Cocoa and Metal state behind the opaque Window handle.
     51 struct Window {
     52   NSWindow* ns_window;
     53   KumoWindowDelegate* delegate;
     54   CAMetalLayer* layer;
     55   id<MTLCommandQueue> queue;
     56   id<MTLTexture> texture;  ///< Holds the last frame; made again on a new size.
     57 };
     58 
     59 /// @brief Creates the application object and a minimal menu with Cmd+Q.
     60 ///
     61 /// A bare executable (not an .app bundle) has no menu and is not a regular
     62 /// foreground application by default; without this it could neither receive
     63 /// keyboard focus nor be quit from the keyboard.
     64 static void init_application() {
     65   [NSApplication sharedApplication];
     66   [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
     67 
     68   NSMenu* menu_bar = [[NSMenu alloc] init];
     69   NSMenuItem* app_item = [[NSMenuItem alloc] init];
     70   [menu_bar addItem:app_item];
     71   NSMenu* app_menu = [[NSMenu alloc] init];
     72   [app_menu addItemWithTitle:@"Quit Kumo" action:@selector(terminate:) keyEquivalent:@"q"];
     73   [app_item setSubmenu:app_menu];
     74   [NSApp setMainMenu:menu_bar];
     75 
     76   // Finish launching by hand: events are pumped by window_poll_events()
     77   // instead of [NSApp run], which would take over the main loop.
     78   [NSApp finishLaunching];
     79 }
     80 
     81 Window* window_create(const WindowDesc& desc) {
     82   static bool application_ready = false;
     83   if (!application_ready) {
     84     init_application();
     85     application_ready = true;
     86   }
     87 
     88   id<MTLDevice> device = MTLCreateSystemDefaultDevice();
     89   if (device == nil) return nullptr;
     90 
     91   NSWindowStyleMask style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
     92                             NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable;
     93   NSRect frame = NSMakeRect(0, 0, desc.width, desc.height);
     94   NSWindow* ns_window = [[NSWindow alloc] initWithContentRect:frame
     95                                                     styleMask:style
     96                                                       backing:NSBackingStoreBuffered
     97                                                         defer:NO];
     98   if (ns_window == nil) return nullptr;
     99 
    100   KumoView* view = [[KumoView alloc] initWithFrame:frame];
    101   [view setWantsLayer:YES];
    102   CAMetalLayer* layer = (CAMetalLayer*)view.layer;
    103   layer.device = device;
    104   // Color is 0xAARRGGBB in a 32-bit integer, which is the bytes B, G, R, A on
    105   // a little-endian machine: exactly this format, so no conversion is needed.
    106   layer.pixelFormat = MTLPixelFormatBGRA8Unorm;
    107   // The frame is copied into the drawable, which a framebuffer-only texture
    108   // does not allow.
    109   layer.framebufferOnly = NO;
    110   // The drawable has the size of the frame, not of the window; the window
    111   // system stretches it. Nearest keeps the pixels square and sharp.
    112   layer.magnificationFilter = kCAFilterNearest;
    113   [ns_window setContentView:view];
    114 
    115   KumoWindowDelegate* delegate = [[KumoWindowDelegate alloc] init];
    116   // We own the reference through Window; AppKit must not release it on close.
    117   [ns_window setReleasedWhenClosed:NO];
    118   [ns_window setDelegate:delegate];
    119   [ns_window setTitle:[NSString stringWithUTF8String:desc.title]];
    120   [ns_window center];
    121   [ns_window makeKeyAndOrderFront:nil];
    122   [NSApp activate];
    123 
    124   return new Window{ns_window, delegate, layer, [device newCommandQueue], nil};
    125 }
    126 
    127 void window_destroy(Window* window) {
    128   if (window == nullptr) return;
    129   [window->ns_window setDelegate:nil];
    130   [window->ns_window close];
    131   delete window;
    132 }
    133 
    134 static Key key_from_event(NSEvent* event) {
    135   NSString* characters = event.charactersIgnoringModifiers;
    136   if (characters.length != 1) return Key::Count;
    137 
    138   using namespace ptn;
    139   return match([characters characterAtIndex:0]) | on(
    140       val<NSLeftArrowFunctionKey> >> Key::Left,
    141       val<NSRightArrowFunctionKey> >> Key::Right,
    142       val<NSUpArrowFunctionKey> >> Key::Up,
    143       val<NSDownArrowFunctionKey> >> Key::Down,
    144       val<' '> >> Key::Space,
    145       _ >> Key::Count);
    146 }
    147 
    148 static bool handle_key_event(Window* window, NSEvent* event, bool down) {
    149   if (event.window != window->ns_window || ![window->ns_window isKeyWindow]) {
    150     return false;
    151   }
    152   if (down && (event.modifierFlags & NSEventModifierFlagCommand) != 0) {
    153     return false;
    154   }
    155 
    156   constexpr unsigned short kEscapeKeyCode = 53;
    157   if (down && event.keyCode == kEscapeKeyCode) {
    158     window->delegate.should_close = YES;
    159     return true;
    160   }
    161 
    162   const Key key = key_from_event(event);
    163   if (key == Key::Count) return false;
    164   if (!down || ![event isARepeat]) {
    165     window->delegate->keyboard.set_key(key, down);
    166   }
    167   return true;
    168 }
    169 
    170 static bool handle_event(Window* window, NSEvent* event) {
    171   using namespace ptn;
    172   return match(event.type) |
    173          on(val<NSEventTypeKeyDown> >>
    174                 [&] { return handle_key_event(window, event, true); },
    175             val<NSEventTypeKeyUp> >>
    176                 [&] { return handle_key_event(window, event, false); },
    177             _ >> false);
    178 }
    179 
    180 void window_poll_events(Window* window) {
    181   // Keeps the autoreleased event objects from piling up across frames.
    182   @autoreleasepool {
    183     for (;;) {
    184       // distantPast: return at once if no event is queued.
    185       NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny
    186                                           untilDate:[NSDate distantPast]
    187                                              inMode:NSDefaultRunLoopMode
    188                                             dequeue:YES];
    189       if (event == nil) break;
    190 
    191       if (!handle_event(window, event)) {
    192         [NSApp sendEvent:event];
    193       }
    194     }
    195   }
    196 }
    197 
    198 Keyboard& window_keyboard(Window* window) {
    199   return window->delegate->keyboard;
    200 }
    201 
    202 bool window_should_close(const Window* window) { return window->delegate.should_close; }
    203 
    204 void window_present(Window* window, const FrameBuffer& framebuffer) {
    205   @autoreleasepool {
    206     const NSUInteger width = static_cast<NSUInteger>(framebuffer.width);
    207     const NSUInteger height = static_cast<NSUInteger>(framebuffer.height);
    208 
    209     if (window->texture == nil || window->texture.width != width ||
    210         window->texture.height != height) {
    211       MTLTextureDescriptor* texture_desc =
    212           [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
    213                                                              width:width
    214                                                             height:height
    215                                                          mipmapped:NO];
    216       window->texture = [window->layer.device newTextureWithDescriptor:texture_desc];
    217       window->layer.drawableSize = CGSizeMake(width, height);
    218     }
    219 
    220     // Blocks until the display can take another frame: this is the vsync wait.
    221     id<CAMetalDrawable> drawable = [window->layer nextDrawable];
    222     if (drawable == nil) return;
    223 
    224     [window->texture replaceRegion:MTLRegionMake2D(0, 0, width, height)
    225                        mipmapLevel:0
    226                          withBytes:framebuffer.pixels.data()
    227                        bytesPerRow:width * sizeof(Color)];
    228 
    229     id<MTLCommandBuffer> commands = [window->queue commandBuffer];
    230     id<MTLBlitCommandEncoder> blit = [commands blitCommandEncoder];
    231     [blit copyFromTexture:window->texture
    232               sourceSlice:0
    233               sourceLevel:0
    234              sourceOrigin:MTLOriginMake(0, 0, 0)
    235                sourceSize:MTLSizeMake(width, height, 1)
    236                 toTexture:drawable.texture
    237          destinationSlice:0
    238          destinationLevel:0
    239         destinationOrigin:MTLOriginMake(0, 0, 0)];
    240     [blit endEncoding];
    241     [commands presentDrawable:drawable];
    242     [commands commit];
    243     // The texture is written again by the next call, so the copy must be done
    244     // by then. Waiting is cheap next to drawing the frame on the CPU.
    245     [commands waitUntilCompleted];
    246   }
    247 }
    248 
    249 void window_set_title(Window* window, const char* title) {
    250   [window->ns_window setTitle:[NSString stringWithUTF8String:title]];
    251 }
    252 
    253 }  // namespace kumo