How do I convert this OpenGL pointer math to Swift?

这一生的挚爱 提交于 2019-12-03 16:08:50

In Swift, you can use the generic struct UnsafePointer to perform pointer arithmetic and casting. Swift doesn't have offsetof, but you can work around that cleanly by taking UnsafePointers of the geometryVertex and textureVertex elements directly.

The following code compiles in an iOS playground. I haven't tested it beyond that but I think it'll work:

import OpenGLES
import GLKit

struct TexturedVertex {
    var geometryVertex = GLKVector2()
    var textureVertex = GLKVector2()
}

struct TexturedQuad {
    var bl = TexturedVertex()
    var br = TexturedVertex()
    var tl = TexturedVertex()
    var tr = TexturedVertex()
    init() { }
}

var _quad = TexturedQuad()
withUnsafePointer(&_quad.bl.geometryVertex) { (pointer) -> Void in
    glVertexAttribPointer(GLuint(GLKVertexAttrib.Position.rawValue),
        2, GLenum(GL_FLOAT), GLboolean(GL_FALSE),
        GLsizei(sizeof(TexturedVertex)), pointer)
}
withUnsafePointer(&_quad.bl.textureVertex) { (pointer) -> Void in
    glVertexAttribPointer(GLuint(GLKVertexAttrib.TexCoord0.rawValue),
        2, GLenum(GL_FLOAT), GLboolean(GL_FALSE),
        GLsizei(sizeof(TexturedVertex)), pointer)
}

By the way, using CGPoint the way you did in your question is dangerous, because CGFloat changes size depending on your target (32-bit or 64-bit), but GL_FLOAT always means 32-bit. The tutorial you're following was written before 64-bit iOS came out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!