Kumo

A hand-rolled game engine.

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

window_win.cpp (7255B) · raw


      1 /// @file platform/window_win.cpp
      2 /// @brief Windows (Win32) implementation of platform/window.h.
      3 
      4 #define WIN32_LEAN_AND_MEAN
      5 #define NOMINMAX
      6 #include <dwmapi.h>
      7 #include <windows.h>
      8 
      9 #include <string>
     10 
     11 #include <ptn/patternia.hpp>
     12 
     13 #include "core/types.h"
     14 #include "platform/keyboard.h"
     15 #include "platform/window.h"
     16 #include "render/frame_buffer.h"
     17 
     18 namespace kumo {
     19 
     20 struct Window {
     21   HWND handle = nullptr;
     22   bool should_close = false;
     23   Keyboard keyboard;
     24 };
     25 
     26 static constexpr wchar_t kWindowClass[] = L"KumoWindow";
     27 
     28 // Public titles use UTF-8; Win32's W functions use UTF-16.
     29 static bool wide_title(const char* title, std::wstring& result) {
     30   if (title == nullptr) return false;
     31 
     32   const int count =
     33       MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, title, -1, nullptr, 0);
     34   if (count == 0) return false;
     35 
     36   result.resize(static_cast<size_t>(count));
     37   return MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, title, -1,
     38                              result.data(), count) != 0;
     39 }
     40 
     41 static Key key_from_virtual_key(WPARAM code) {
     42   using namespace ptn;
     43   return match(code) | on(val<VK_LEFT> >> Key::Left,
     44                           val<VK_RIGHT> >> Key::Right, val<VK_UP> >> Key::Up,
     45                           val<VK_DOWN> >> Key::Down,
     46                           val<VK_SPACE> >> Key::Space, _ >> Key::Count);
     47 }
     48 
     49 static LRESULT CALLBACK window_proc(HWND handle, UINT message, WPARAM wparam,
     50                                     LPARAM lparam) {
     51   auto* window =
     52       reinterpret_cast<Window*>(GetWindowLongPtrW(handle, GWLP_USERDATA));
     53 
     54   // CreateWindowExW sends this before the window becomes visible.
     55   if (message == WM_NCCREATE) {
     56     const auto* create = reinterpret_cast<const CREATESTRUCTW*>(lparam);
     57     window = static_cast<Window*>(create->lpCreateParams);
     58     window->handle = handle;
     59 
     60     SetWindowLongPtrW(handle, GWLP_USERDATA,
     61                       reinterpret_cast<LONG_PTR>(window));
     62   }
     63 
     64   const auto default_proc = [&] {
     65     return DefWindowProcW(handle, message, wparam, lparam);
     66   };
     67   if (window == nullptr) return default_proc();
     68 
     69   using namespace ptn;
     70   return match(message) | on(
     71       val<WM_CLOSE> >> [&]() -> LRESULT {
     72         // Keep the window alive until the main loop destroys it.
     73         window->should_close = true;
     74         return 0;
     75       },
     76       any(val<WM_KEYDOWN>, val<WM_KEYUP>, val<WM_SYSKEYUP>) >>
     77           [&]() -> LRESULT {
     78             const bool down = message == WM_KEYDOWN;
     79             if (down && wparam == VK_ESCAPE) {
     80               window->should_close = true;
     81               return 0;
     82             }
     83 
     84             const Key key = key_from_virtual_key(wparam);
     85             if (key == Key::Count) return default_proc();
     86 
     87             // Win32 sets bit 30 when the key was already held.
     88             constexpr LPARAM kWasDown = LPARAM{1} << 30;
     89             if (!down || (lparam & kWasDown) == 0) {
     90               window->keyboard.set_key(key, down);
     91             }
     92             // Forward system key messages after updating our state.
     93             return message == WM_SYSKEYUP ? default_proc() : 0;
     94           },
     95       val<WM_KILLFOCUS> >> [&]() -> LRESULT {
     96         window->keyboard.release_all();
     97         return 0;
     98       },
     99       val<WM_NCDESTROY> >> [&] {
    100         window->should_close = true;
    101         window->handle = nullptr;
    102         SetWindowLongPtrW(handle, GWLP_USERDATA, 0);
    103         return default_proc();
    104       },
    105       _ >> default_proc);
    106 }
    107 
    108 Window* window_create(const WindowDesc& desc) {
    109   if (desc.width <= 0 || desc.height <= 0) return nullptr;
    110 
    111   std::wstring title;
    112   if (!wide_title(desc.title, title)) return nullptr;
    113 
    114   const HINSTANCE instance = GetModuleHandleW(nullptr);
    115 
    116   // Register once; later windows reuse the same class.
    117   static ATOM window_class = 0;
    118   if (window_class == 0) {
    119     WNDCLASSEXW info{};
    120     info.cbSize = sizeof(info);
    121     info.lpfnWndProc = window_proc;
    122     info.hInstance = instance;
    123     info.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512));  // Arrow.
    124     info.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
    125     info.lpszClassName = kWindowClass;
    126 
    127     window_class = RegisterClassExW(&info);
    128     if (window_class == 0) return nullptr;
    129   }
    130 
    131   constexpr DWORD style = WS_OVERLAPPEDWINDOW;
    132 
    133   // Convert the requested client size to the outer window size.
    134   RECT bounds{0, 0, desc.width, desc.height};
    135   if (!AdjustWindowRectEx(&bounds, style, FALSE, 0)) return nullptr;
    136 
    137   auto* window = new Window;
    138 
    139   const HWND handle = CreateWindowExW(
    140       0, kWindowClass, title.c_str(), style, CW_USEDEFAULT, CW_USEDEFAULT,
    141       bounds.right - bounds.left, bounds.bottom - bounds.top, nullptr, nullptr,
    142       instance, window);
    143 
    144   if (handle == nullptr) {
    145     delete window;
    146     return nullptr;
    147   }
    148 
    149   ShowWindow(handle, SW_SHOW);
    150   UpdateWindow(handle);
    151   return window;
    152 }
    153 
    154 void window_destroy(Window* window) {
    155   if (window == nullptr) return;
    156 
    157   if (window->handle != nullptr) {
    158     DestroyWindow(window->handle);
    159   }
    160   delete window;
    161 }
    162 
    163 void window_poll_events(Window* window) {
    164   MSG message{};
    165 
    166   // Return immediately when no messages remain.
    167   while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
    168     if (message.message == WM_QUIT) {
    169       window->should_close = true;
    170       break;
    171     }
    172 
    173     TranslateMessage(&message);
    174     DispatchMessageW(&message);
    175   }
    176 }
    177 
    178 Keyboard& window_keyboard(Window* window) { return window->keyboard; }
    179 
    180 bool window_should_close(const Window* window) { return window->should_close; }
    181 
    182 void window_present(Window* window, const FrameBuffer& framebuffer) {
    183   if (window->handle == nullptr) return;
    184 
    185   RECT client{};
    186   if (!GetClientRect(window->handle, &client)) return;
    187 
    188   // Color is 0xAARRGGBB in a 32-bit integer, which is the bytes B, G, R, A on
    189   // a little-endian machine: exactly a 32-bit DIB, so no conversion is needed.
    190   // GDI ignores the fourth byte. A negative height says that the first row is
    191   // the top one.
    192   BITMAPINFO info{};
    193   info.bmiHeader.biSize = sizeof(info.bmiHeader);
    194   info.bmiHeader.biWidth = framebuffer.width;
    195   info.bmiHeader.biHeight = -framebuffer.height;
    196   info.bmiHeader.biPlanes = 1;
    197   info.bmiHeader.biBitCount = 32;
    198   info.bmiHeader.biCompression = BI_RGB;
    199 
    200   // A minimized window has an empty client area, and there is nothing to draw.
    201   if (client.right > 0 && client.bottom > 0) {
    202     const HDC context = GetDC(window->handle);
    203     if (context != nullptr) {
    204       // The frame is stretched to the client area. COLORONCOLOR drops or
    205       // repeats pixels, which is nearest-neighbor: the pixels stay sharp.
    206       SetStretchBltMode(context, COLORONCOLOR);
    207       StretchDIBits(context, 0, 0, client.right, client.bottom, 0, 0,
    208                     framebuffer.width, framebuffer.height,
    209                     framebuffer.pixels.data(), &info, DIB_RGB_COLORS, SRCCOPY);
    210       ReleaseDC(window->handle, context);
    211     }
    212   }
    213 
    214   // GDI does not wait for the display. DwmFlush() returns when the compositor
    215   // has shown its next frame, which is the vsync wait; if it cannot, sleep
    216   // briefly so that the loop does not spin a whole core.
    217   if (FAILED(DwmFlush())) Sleep(1);
    218 }
    219 
    220 void window_set_title(Window* window, const char* title) {
    221   std::wstring text;
    222   if (wide_title(title, text)) {
    223     SetWindowTextW(window->handle, text.c_str());
    224   }
    225 }
    226 
    227 }  // namespace kumo