如何将metal-cpp与GLFW一起使用?

问题描述 投票:0回答:2

我正在尝试使用 official metal-cpp headers 使用 GLFW 制作一个完全 C++ 的金属应用程序。如果可能的话我不想写任何 Objective-C。

#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;
}

我不知道这是否可能,但我现在的具体障碍是将

NSWindow
返回的 Objective-c
glfwGetCocoaWindow
转换为
NS::Window
C++ 对象。

c++ glfw metal metalkit
2个回答
1
投票

使用 GLFW 时无法完全摆脱 Objective-C(++)。

您需要一个

*.h
/
*.m(m)
组合来向 NSWindow 添加金属层。

#ifndef COCOA_BRIDGE
#define COCOA_BRIDGE
#include <metal/metal.hpp>
struct GLFWwindow;

namespace CA {
    class MetalLayer;
}
namespace X {

    void add_layer_to_window(GLFWwindow* window, CA::MetalLayer* layer);
}
#endif
#import "cocoa_bridge.h"
#include <GLFW/glfw3.h>
#define GLFW_EXPOSE_NATIVE_COCOA
#include <GLFW/glfw3native.h>
#import <QuartzCore/CAMetalLayer.h>
namespace X{

    void add_layer_to_window(GLFWwindow* window, CA::MetalLayer* layer) {
        NSWindow* cocoa_window = glfwGetCocoaWindow(window);
        CAMetalLayer* native_layer = (__bridge CAMetalLayer*)layer;
        [[cocoa_window contentView] setLayer:native_layer];
        [native_layer setMaximumDrawableCount:2];
        [[cocoa_window contentView] setWantsLayer:YES];
        [[cocoa_window contentView] setNeedsLayout:YES];
    }
}
auto* window = (GLFWwindow*)get_window();
layer = NS::TransferPtr(CA::MetalLayer::layer());
layer->setDevice(device.get());
layer->setFramebufferOnly(true);
layer->setPixelFormat(MTL::PixelFormat::PixelFormatBGRA8Unorm_sRGB);
add_layer_to_window(window, layer.get());

整个渲染通过图层进行。


0
投票

是的,这当然是可能的。 这是一个例子我刚刚放在一起。

它使用 Apple 不受支持的

metal-cpp-extensions
代码来在
CAMetalLayer
视图中设置
NSWindow
,我必须修改该代码才能添加所需的选择器。 之后,我将 Objective-C 示例 移植到 C++。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.