初识OpenGL ES之你好, 三角形

2017-06-28  本文已影响75人  小Ju
屏幕快照 2017-06-27 下午9.56.32.png
  1. 缓存(buffers):提供数据的最好方式;
    OpenGL ES为两个缓存区域之间的数据交换定义了缓存, CPU将数据复制到OpenGL ES的缓存中, GPU申请到权限之后, CPU就不会接触这个缓存, 这样GPU就会高效的读写数据.

2.为缓存提供数据7个步骤和对应的函数中对应的API(非常重要):
2.1)生成---glGenBuffers():请求生成一个独一无二的标识符
2.2)绑定---glGindBuffer():告诉OpenGL为接下来的运算使用一个缓存
2.3)缓存数据---glBufferData():初始化(分配内存),复制数据到缓存中
2.4)启用或者禁止---glEnableVertexAttribArray()和glDisableVertexAttribArray()
2.5)设置指针---glVertexAttribPointer()
2.6)绘图---glDrawArrays()渲染
2.7)删除---glDeleteBuffers()

  1. 帧缓存(frame buffer):接收渲染结果的缓冲区

4.上下文(context):(可以理解为画布)用于配置OpenGL ES的保存在特定平台的软件数据结构中

5.着色器(shaders):它们是一个个独立运行在GPU上的小程序, 这些小程序为图形渲染管线的某个特定部分而运行

6.GLKit(iOS 5)框架:在iOS中使用OpenGL ES需要使用的框架

  1. 首先用到的是GLKit框架, 控制器使用的是UIViewController的子类GLKViewController
  2. 定义一个C结构体scene,用来保存GLKVector3(表示,x,y,z坐标)类型的成员变量positionCoords,数组point表示三角形的三个顶点坐标
  typedef struct {
    GLKVector3 positionCoords;
}scene;
static const scene point[] = {
    {{0.5, -0.5, 0.0f}},  //右下
    {{0.5, 0.5, -0.0f}},    //右上
    {{-0.5, 0.5, 0.0f}}   //左上
};

3.着色器和上下文

  //顶点数据缓存的标识符
@property (nonatomic,assign)GLuint bufferID;
//着色器
@property (nonatomic,strong) GLKBaseEffect *baseEffect;
//上下文
@property (nonatomic,strong)EAGLContext *context;

4.初始化,配置上下文和着色器

GLKView *v = (GLKView *)self.view;
    //初始化上下文
    self.context = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2];
    v.context = self.context;
    //设置当前的上下文
    [EAGLContext setCurrentContext:self.context];

  //着色器
    self.baseEffect = [[GLKBaseEffect alloc]init];
    self.baseEffect.useConstantColor = GL_TRUE;
    self.baseEffect.constantColor = GLKVector4Make(1.0, 1.0, 1.0, 1.0);//红,绿,蓝,透明度

5.核心代码,创建缓存(7个步骤,前5个步骤)

  //创建缓存
    glGenBuffers(1, &_bufferID);//生成标识符
    glBindBuffer(GL_ARRAY_BUFFER, _bufferID);//绑定
    glBufferData(GL_ARRAY_BUFFER, sizeof(point), point, GL_STATIC_DRAW);//复制顶点数据到缓存中
    glEnableVertexAttribArray(GLKVertexAttribPosition);//允许
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(scene), NULL);//告诉OpenGL顶点数据在哪里

6.最后在glkView:(GLKView *)view drawInRect:(CGRect)rect的代理方法中实现实现绘制

  //背景颜色
    glClearColor(1.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    [self.baseEffect prepareToDraw];
    glDrawArrays(GL_TRIANGLES, 0, 3);//重绘

上一篇 下一篇

猜你喜欢

热点阅读