Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

Swift – first OpenGL rectangle

2019-11-20 17:52:28

核心代码:

import UIKit
import GLKit



extension Array {
    func s_size() -> Int {
        return self.count * MemoryLayout<Point>.size(ofValue: self[0] as! Point)
    }
}

struct Point {
    var x: Float
    var y: Float
    var z: Float
}

var vertix = [
    Point(x: 0.5, y: -0.5, z: 0),
    Point(x: 0.5, y: 0.5, z: 0),
    Point(x: -0.5, y: 0.5, z: 0),
    Point(x: -0.5, y: -0.5, z: 0)
]

class RectangleViewController: GLKViewController {

    var vertexBuffer: GLuint = 0
    var baseEffect = GLKBaseEffect()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1
        let view = self.view as! GLKView
        view.context = EAGLContext(api: EAGLRenderingAPI.openGLES3)!
        EAGLContext.setCurrent(view.context)
        
        // 2
        baseEffect.constantColor = GLKVector4Make(1, 0, 0, 0)
        baseEffect.useConstantColor = GLboolean(GL_TRUE)
        
        // 3
        glGenBuffers(1, &vertexBuffer)
        glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBuffer)
        glBufferData(GLenum(GL_ARRAY_BUFFER), vertix.s_size(), vertix, GLenum(GL_STATIC_DRAW))
        
        
    
    }

    override func glkView(_ view: GLKView, drawIn rect: CGRect) {
        baseEffect.prepareToDraw()
        
        glClear(GLenum(GL_COLOR_BUFFER_BIT))

        glVertexAttribPointer(0, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<Point>.size), nil)
        glEnableVertexAttribArray(0)
        
        glDrawArrays(GLenum(GL_TRIANGLE_FAN), 0, GLsizei(vertix.count))
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    


}

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *