SCNProgram - 如何传递类型的制服" mat4"到自定义着色器?

时间:2014-08-25 19:32:30

标签: ios opengl-es swift scenekit

我试图在iOS(Xcode 6 beta 6)的SceneKit中设置我想要在自定义着色器程序中使用的统一mat4。而且我试图在Swift中这样做。

let myMatrix: Array<GLfloat> = [1, 0, 0 , 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]

var material = SCNMaterial()
var program = SCNProgram()

// setup of vertex/fragment shader goes here
program.vertexShader = //...
program.fragmentShader = //...

material.program = program

// I want to initialize the variable declared as "uniform mat4 u_matrix" in the vertex shader with "myMatrix"

material.handleBindingOfSymbol("u_matrix") {
    programID, location, renderedNode, renderer in            
    let numberOfMatrices = 1
    let needToBeTransposed = false
    glUniformMatrix4fv(GLint(location), GLsizei(numberOfMatrices), GLboolean(needToBeTransposed), myMatrix)
}

使用此代码,我有以下编译错误:Cannot invoke 'init' with an argument list of type (GLint, GLsizei, GLboolean, Array<GLfloat>)。但是,从这里的文档(section "Constant pointers")我的理解是,我们可以将一个数组传递给一个以UnsafePointer为参数的函数。

然后我尝试通过执行以下操作直接传递UnsafePointer:

let testPtr: UnsafePointer<GLfloat> = nil
glUniformMatrix4fv(GLint(location), GLsizei(numberOfMatrices), GLboolean(needToBeTransposed), testPtr)

我收到错误Cannot invoke 'init' with an argument list of type '(GLint, GLsizei, GLboolean, UnsafePointer<GLfloat>)'

然而,glUniformMatrix4fv的原型恰恰是:

func glUniformMatrix4fv(location: GLint, count: GLsizei, transpose: GLboolean, value: UnsafePointer<GLfloat>)

知道我做错了什么吗?如果我们使用自定义着色器,我们如何将mat4作为制服传递?

Note1 :我首先尝试将SCNMatrix4用于myMatrix但我收到错误&#34; SCNMatrix4无法转换为UnsafePointer&#34;。

Note2 :我想过使用GLKMatrix4但是在Swift中无法识别此类型。

1 个答案:

答案 0 :(得分:1)

我发现在确定如何调用C API时,编译器的错误消息可能提供更多误导而不是帮助。我的故障排除技术是将每个参数声明为局部变量,并查看哪个获取红色标志。在这种情况下,它不是导致问题的最后一个参数,它是GLboolean

let aTranspose = GLboolean(needToBeTransposed)
// Cannot invoke 'init' with an argument of type 'Bool'

结果GLboolean以这种方式定义:

typealias GLboolean = UInt8

所以这是我们需要的代码:

material.handleBindingOfSymbol("u_matrix") {
    programID, location, renderedNode, renderer in

    let numberOfMatrices = 1
    let needToBeTransposed = false

    let aLoc = GLint(location)
    let aCount = GLsizei(numberOfMatrices)
    let aTranspose = GLboolean(needToBeTransposed ? 1 : 0)
    glUniformMatrix4fv(aLoc, aCount, aTranspose, myMatrix)
}