Swift:将 int 元组转换为包含 float 向量的自定义类型

标签 swift metal

这个问题的两个原始答案都令人满意,但解决方案的方式略有不同。我选择了我发现更易于实现的那个

我正在尝试翻译一些 ObjectiveC,from this apple metal doc/example , 和 metal code into swift 但在这方面遇到了一些麻烦:

这是我正在使用的 typedef,它是 Metal 着色器可以计算我的顶点数据所必需的(来自 simd.h 的浮点向量很重要):

#include <simd/simd.h>

typedef struct
{
  vector_float2 position;
  vector_float4 color;
} AAPLVertex;

在 objective-c 中,您可以这样做以将一些数据转换为这种类型:

static const AAPLVertex triangleVertices[] =
{
    // 2D positions,    RGBA colors
    { {  250,  -250 }, { 1, 1, 1, 1 } },
    { { -250,  -250 }, { 1, 1, 0, 1 } },
    { {    0,   250 }, { 0, 1, 1, 1 } },
};

但是你如何在 Swift 中做到这一点?我试过这个:

  private let triangleVertices = [
    ( (250,  -250), (1, 0, 1, 1) ),
    ( (-250,  -250), (1, 1, 0, 1) ),
    ( (0,  250), (0, 1, 1, 1) )
  ] as? [AAPLVertex]

但是 xcode 告诉我:

从'[((Int, Int), (Int, Int, Int, Int))]'到不相关的类型'[AAPLVertex]'总是失败

我的应用程序在加载时崩溃。

最佳答案

这就是我的实现方式:

import simd

struct Vertex {
    var position: SIMD2<Float>
    var color: SIMD4<Float>
}

extension Vertex {
    init(x: Float, y: Float, r: Float, g: Float, b: Float, a: Float = 1.0) {
        self.init(position: SIMD2(x, y), color: SIMD4(r, g, b, a))
    }
}

let triangleVertices = [
    Vertex(x: +250, y: -250, r: 1, g: 0, b: 1),
    Vertex(x: -250, y: -250, r: 1, g: 1, b: 0),
    Vertex(x:    0, y: -250, r: 0, g: 1, b: 1),
]

但是,与 Objective C ones 相比,我不确定 Swift 原生 SIMD 类型在多大程度上与 Metal 兼容。 ,尽管我怀疑它们是可互操作的。

关于Swift:将 int 元组转换为包含 float 向量的自定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56781233/

相关文章:

swift - 错误 : Multiple commands produce . .. x86_64.swiftmodule

ios - 解析 XLSX 期间找不到 Xcode 文件错误

swift - 无法将 UIBarButtonItem 添加到 UINavigationController 中的工具栏

ios - 如何快速获取 wkwebView 内容大小

ios - 如何在iPhone真机上打开数据库sqlite文件?

swift - 如何将纹理存储模式设置为 `private` 到从 `CVMetalTextureCacheCreateTextureFromImage` 创建的纹理?

ios - 在 iOS 13 模拟器上从源代码编译 Metal 着色器会出现 PCH 错误

ios - 为什么重写 UIView.drawRect 会出现 "calling -display has no effect"消息?

ios - 如何使用 MetalPetal 遮盖图像并以透明方式输出

用于在运行时识别 Metal 支持的 iOS 代码?