我正在编写一个使用 Metal 的程序。我正在使用结构定义统一缓冲区布局。当我在 swift 中声明结构时,它无法绘制。但是当我在 Objective-C 中声明结构并使用桥接头导入它时,它工作正常。计算的实际逻辑完全相同。唯一的变化是声明。以下是声明:
Objective-C 声明(这个有效):
struct Uniforms {
struct Matrix4x4 modelViewMatrix;
struct Matrix4x4 projectionMatrix;
struct Matrix3x3 normalMatrix;
struct Vector3 lightPosition;
};
以及 Swift 声明:
struct Uniforms {
var modelViewMatrix: Matrix4x4!
var projectionMatrix: Matrix4x4!
var normalMatrix: Matrix3x3!
var lightPosition: Vector3!
}
请注意,数学类型是在 Objective-C 中定义的结构,并充当 Swift 的包装器。
有关更多信息,这里是计算值并将它们发送到 Metal 的 Swift 代码:
// Declaration:
var uniforms: Uniforms!
...
// Part where I compute the values:
self.uniforms = Uniforms()
let eye = vector3Create(0.0, 5.0, 7.0)
let center = vector3Create(0.0, 0.0, 0.0)
let up = vector3Create(0.0, 1.0, 0.0)
self.uniforms.modelViewMatrix = MathOperations.lookAt(eye, center: center, up: up)
let aspect = Float(self.view.bounds.size.width / self.view.bounds.size.height)
self.uniforms.projectionMatrix = MathOperations.perspective(45.0, aspect: aspect, near: 0.01, far: 100.0)
self.uniforms.normalMatrix = getMatrix3x3FromMatrix4x4(self.uniforms.modelViewMatrix)
self.uniforms.lightPosition = vector3Create(0.0, 5.0, 7.0)
self.vertexBuffer = device.newBufferWithBytes(self.vertexArray, length: self.vertexArray.count * sizeof(Float), options: .CPUCacheModeDefaultCache)
self.uniformBuffer = device.newBufferWithBytes(&self.uniforms, length: sizeof(Uniforms), options: .CPUCacheModeDefaultCache)
对不起所有的代码,但请帮忙。谢谢。