c++glfwmetalmetalkit

How to use metal-cpp with GLFW?


I'm trying to use the official metal-cpp headers to make an entirely C++ metal app using GLFW. I don't want to write any objective-c if possible.

#define GLFW_EXPOSE_NATIVE_COCOA
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>

#include <Metal/Metal.hpp>
#include <MetalKit/MetalKit.hpp>
#include <QuartzCore/QuartzCore.hpp>

int main() {
    glfwInit();
    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);

    GLFWwindow* window = glfwCreateWindow( 1280, 720, "Hello World", nullptr, nullptr);

    auto nswindow = glfwGetCocoaWindow(window);

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window)) {
        /* Render here */

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

I don't know if this is even possible, but my specific hurdle right now is converting the objective-c NSWindow returned from glfwGetCocoaWindow to an NS::Window C++ object.


Solution

  • Yes it's certainly possible. Here's an example I just put together.

    It uses Apple's unsupported metal-cpp-extensions code in order to set-up the CAMetalLayer in the NSWindow's view, and I had to modify that code in order to add the selectors required. After that I ported an Objective-C example to C++.