CGLFW3

GLFW 构建为一个库,以便添加到您的 Swift Package 中。 截至撰写本文时,它已更新到 GLFW 3.4 的 最新提交

这个包可以独立工作,但它是作为 SwiftGLFW 的基础而创建的。

入门

SwiftPM 不支持带有语义版本控制包的不安全标志,因此请将其添加到 Package.swift 中的依赖项中

.package(url: "https://github.com/thepotatoking55/CGLFW3.git", branch: "main")

从那里,您可以直接使用 import CGLFW3 导入它,并像平常一样使用它。

跨平台支持

要公开平台原生函数,例如 glfwGetCocoaWindow,请将以下 C 设置添加到您的目标

.target(
    name: "ExampleTarget",
    dependencies: ["CGLFW3"],
    cSettings: [
        .define("GLFW_EXPOSE_NATIVE_WIN32", .when(platforms: [.windows])),
        .define("GLFW_EXPOSE_NATIVE_WGL", .when(platforms: [.windows])),
        .define("GLFW_EXPOSE_NATIVE_COCOA", .when(platforms: [.macOS])),
        .define("GLFW_EXPOSE_NATIVE_NSGL", .when(platforms: [.macOS])),
        .define("GLFW_EXPOSE_NATIVE_X11", .when(platforms: [.linux]))
    ]
)

我没有运行 Linux 的计算机,而且 SwiftPM 对 Windows 的支持还很初级,因此将其移植到非 Mac 平台可能还需要一些工作。

Hello World

GLFW 文档中 “hello world” 程序的 Swift 翻译

import CGLFW3

func main() {
    glfwInit()
    
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4)
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1)
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE)
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
    
    guard let window = glfwCreateWindow(800, 600, "Hello World", nil, nil) else {
        let error = glfwGetError(nil)
        print(error)
        return
    }

    glfwMakeContextCurrent(window)
    while glfwWindowShouldClose(window) == GLFW_FALSE {
        glfwSwapBuffers(window)
        glfwPollEvents()
    }
    
    glfwTerminate()
}