【问题标题】:Swift - How to draw line in OpenGL ES?Swift - 如何在 OpenGL ES 中画线?
【发布时间】:2019-02-18 18:53:03
【问题描述】:

我正在尝试使用SwiftGLKitView 上画一条黑色单线,但它不起作用。 我可以清除屏幕,我可以用任何颜色填充它,但我不能在上面画任何东西。 我知道,这个问题被问了很多次,但我在 Swift 上找不到任何答案。 此外,没有任何关于在 Swift 中使用 OpenGL ES 的信息,所以我来到了这里。

这是我的代码:

import GLKit

class MyGLKit: GLKView {
    override func drawRect(rect: CGRect) {
        glClearColor(0.8, 0.8, 0.8, 1.0)
        glClear(GLbitfield(GL_COLOR_BUFFER_BIT))

        glColor4f(0, 0, 0, 1)

        var line: [GLfloat] = [-1, 0, 1, 0]
        var len = line.count * sizeof(GLfloat)

        // Create an handle for a buffer object array
        var bufferObjectNameArray: GLuint = 0

        // Have OpenGL generate a buffer name and store it in the buffer object array
        glGenBuffers(1, &bufferObjectNameArray);

        // Bind the buffer object array to the GL_ARRAY_BUFFER target buffer
        glBindBuffer(GLbitfield(GL_ARRAY_BUFFER), bufferObjectNameArray);

        // Send the line data over to the target buffer in GPU RAM
        glBufferData(
        GLbitfield(GL_ARRAY_BUFFER),    // the target buffer
        len,                            // the number of bytes to put into the buffer
        line,                           // a pointer to the data being copied
        GLbitfield(GL_STATIC_DRAW));    // the usage pattern of the data

        glVertexPointer(2, GLbitfield(GL_FLOAT), 0, line);
        var programHandle: GLuint = glCreateProgram()
        glLinkProgram(programHandle)

        glDrawArrays(GLbitfield(GL_LINES), 0, 2);
    }
}

我不确定这段代码在做什么,因为在通常的 OpenGL 之后,OpenGL ES 看起来很疯狂。我的意思是,你需要写很多代码来画一条线。为什么会这样?

【问题讨论】:

  • 您需要注释掉的glVertexPointer() 调用。但是使用0 作为最后一个参数,因为如果绑定了缓冲区,这是缓冲区的偏移量。
  • @RetoKoradi 我不能使用0 作为最后一个参数,因为XCode 说Cannot invoke 'init' with an argument list of type '(IntegerLiteralConvertible, $T3, IntegerLiteralConvertible, IntegerLiteralConvertible)'。最后一个参数是指定指向数组中第一个顶点的第一个坐标的指针。所以它必须是指向数组第一个元素的指针。但是如何制作呢?
  • 我同意 OP,带有 swift 的 OpenGL-ES 是 insane。我只想从A点到B点画一条该死的线。为什么这需要20多行gl代码?为什么这不是原始的? +1 insane

标签: ios swift opengl-es


【解决方案1】:

我没有使用过 Swift,但根据 OpenGL EXC_BAD_ACCESS when calling glDrawElements in Swift but not in Objective-C 中的代码,您的 glVertexPointer() 调用应该如下所示:

let bufferOffset: CConstVoidPointer = COpaquePointer(UnsafePointer<Int>(0))
glVertexPointer(2, GLbitfield(GL_FLOAT), 0, bufferOffset);

看起来您并没有真正构建着色器程序:

var programHandle: GLuint = glCreateProgram()
glLinkProgram(programHandle)

如果您使用的是普通的 OpenGL,这里需要处理很多事情。您需要创建着色器对象,为它们提供用 GLSL 编写的代码,调用编译着色器等。我相信 GLKit 具有使用预烘焙着色器的功能。

至于为什么 OpenGL 如此“疯狂”,这超出了本网站的范围。而且很主观。恕我直言,要记住的主要一点是,OpenGL 的设计目的不是为程序员提供方便的 API。它旨在为访问图形硬件提供相对较薄的通用抽象。类似 API 的趋势实际上是使抽象层更薄以减少开销(例如,参见 DirectX 12)。

没有什么能阻止任何人在 OpenGL 之上实现更方便的高级 API。这些接口存在,人们使用它们。

【讨论】:

  • 我收到了这个Use of undeclared type 'CConstVoidPointer' 错误。当我将类型更改为 UnsafePointer 时,它起作用了,但仍然没有绘制任何内容。
  • 我会邀请您编辑答案,但您的编辑很有可能会被拒绝,因为它必须经过编辑审核队列。除此之外,您似乎缺少构建着色器程序。我添加了一段关于此的内容。对不起,如果我的回答不是很有帮助。不确定我是否应该删除它。我通常不会回答关于我不理解的主题的问题,包括 Swift。
  • 我认为你是对的。让它发挥作用太难了!也没有意义,因为我不需要 3D 图形。我想要的 - 绘制原始线条和圆圈。或许,您可能会列举一些“在 OpenGL 之上更方便的高级 API”?
  • @Yuri,你可以使用 CGContext。
【解决方案2】:

看起来你需要添加 GLKBaseEffect

无论如何,这是我的工作解决方案: 要进行测试,请创建一个 MyGLKit.swift 文件

import Foundation
import GLKit
import OpenGLES

struct OpenGLColor {
    var r: GLubyte = 0
    var g: GLubyte = 0
    var b: GLubyte = 0
    var a: GLubyte = 0
}

class MyGLKit: GLKView {

    var lineData: [GLfloat] = []
    var colorData: [GLubyte] = []
    var linesCount:Int = 0

    func setup(){
        self.context = EAGLContext(api: .openGLES2)!
        EAGLContext.setCurrent(self.context)

        //effect
        let effect: GLKBaseEffect = GLKBaseEffect()
        let projectionMatrix: GLKMatrix4 = GLKMatrix4MakeOrtho(-1.0, 1.0, -1.0, 1.0, 1.0, -1.0)
        effect.transform.projectionMatrix = projectionMatrix
        effect.prepareToDraw()


        //OPTIONAL > disable slow GL extensions
        glDisable(GLenum(GL_DEPTH_TEST))
        glDisable(GLenum(GL_BLEND))
        glDisable(GLenum(GL_DITHER))
        glDisable(GLenum(GL_STENCIL_TEST))
        glDisable(GLenum(GL_TEXTURE_2D))
        //

        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_NEAREST)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_NEAREST)
        glEnableVertexAttribArray(GLuint(GLKVertexAttrib.position.rawValue))
        glEnableVertexAttribArray(GLuint(GLKVertexAttrib.color.rawValue))

    }

    func drawLine(x:GLfloat, y:GLfloat, x2:GLfloat, y2:GLfloat, color: OpenGLColor){

        //suppport for retina
        var x = x
        var y = y
        var x2 = x2
        var y2 = y2
        x *= 2
        x2 *= 2
        y *= 2
        y2 *= 2

        //calculate position for opengl
        let w: GLfloat = GLfloat(self.bounds.size.width)
        let h: GLfloat = GLfloat(self.bounds.size.height)

        //coordinates x/y
        lineData.append(((1.0/w)*x)-1)
        lineData.append(1-((1.0/h)*y))
        lineData.append(0)
        lineData.append(((1.0/w)*x2)-1)
        lineData.append(1-((1.0/h)*y2))
        lineData.append(0)

        //color
        colorData.append(color.r)
        colorData.append(color.g)
        colorData.append(color.b)
        colorData.append(color.a)
        colorData.append(color.r)
        colorData.append(color.g)
        colorData.append(color.b)
        colorData.append(color.a)

        linesCount += 1

    }

    override func draw(_ rect: CGRect) {

        glLineWidth(1.0)
        glClearColor(0.8, 0.8, 0.8, 1.0)
        glClear(GLbitfield(GL_COLOR_BUFFER_BIT))

        //draw layer
        if (lineData.count > 0){
            glVertexAttribPointer(GLuint(GLKVertexAttrib.position.rawValue), 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 0, lineData)
            glVertexAttribPointer(GLuint(GLKVertexAttrib.color.rawValue), 4, GLenum(GL_UNSIGNED_BYTE), GLboolean(GL_TRUE), 0, colorData)
            glDrawArrays(GLenum(GL_LINES), 0, GLsizei(linesCount*2))
        }
    }

}

然后在你的 UIViewController 中使用它:

let g = MyGLKit()
        g.setup()
        g.frame = self.view.bounds
        self.view.addSubview(g)
        var color = OpenGLColor()
        color.r = 20
        color.b = 30
        color.g = 40
        color.a = 255
        g.drawLine(x: 10, y: 10, x2: GLfloat(g.frame.size.width), y2: 10, color: color)
        g.drawLine(x: 10, y: 50, x2: GLfloat(g.frame.size.width), y2: 50, color: color)
        g.setNeedsDisplay()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多