这个问题的两个原始答案都令人满意,但解决方案的方式略有不同。我选择了我发现更易于实现的那个
我正在尝试翻译一些 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/