11-2.GLSL-索引绘图案例
2020-10-29 本文已影响0人
Pufus
效果
操作图
准备工作
创建顶点着色器shaderv.vsh
和片元着色器shaderf.fsh
- 顶点着色器(shaderv.vsh)
attribute vec4 position;
attribute vec4 positionColor;
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
varying lowp vec4 varyColor;
void main()
{
varyColor = positionColor;
vec4 vPos;
//4*4 * 4*4 * 4*1
vPos = projectionMatrix * modelViewMatrix * position;
//ERROR
//vPos = position * modelViewMatrix * projectionMatrix ;
gl_Position = vPos;
}
- 片元着色器(shaderf.fsh)
varying lowp vec4 varyColor;
void main()
{
gl_FragColor = varyColor;
}
思路:
-
setupLayer
: 创建图层 -
setupContext
: 创建上下文 -
deleteRenderAndFrameBuffer
: 清空缓存区 -
setupRenderBuffer
: 设置RenderBuffer -
setupFrameBuffer
: 设置FrameBuffer
//前面5个步骤跟上一章的案例是一样的 -
renderLayer
:开始绘制
创建CCView,继承自UIView
#import <UIKit/UIKit.h>
@interface CCView : UIView
@end
在CCView中导入文件
注意:本案例使用了第三方的工具
#import "CCView.h"
#import "GLESMath.h" //第三方的工具
#import "GLESUtils.h" //第三方的工具
#import <OpenGLES/ES2/gl.h>
定义属性
@interface CCView()
//在iOS和tvOS上绘制OpenGL ES内容的图层,继承与CALayer
@property(nonatomic,strong)CAEAGLLayer *myEagLayer;
//上下文
@property(nonatomic,strong)EAGLContext *myContext;
//RenderBuffer缓存区
@property(nonatomic,assign)GLuint myColorRenderBuffer;
//FrameBuffer缓存区
@property(nonatomic,assign)GLuint myColorFrameBuffer;
//program
@property(nonatomic,assign)GLuint myPrograme;
//顶点数组
@property (nonatomic , assign) GLuint myVertices;
@end
@implementation CCView
{
float xDegree;
float yDegree;
float zDegree;
BOOL bX;
BOOL bY;
BOOL bZ;
NSTimer* myTimer;
}
@end
ViewController
1.view的class类型指定为CCView
1.ViewController中添加x,y,z三个按钮,并且添加绑定事件(绑定事件写在CCView上面)
操作图
#import "ViewController.h"
#import "CCView.h"
@interface CCViewController ()
@property(nonatomic,strong)CCView *cView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.cView = (CCView *)self.view;
}
@end
1.设置图层
//1.设置图层
-(void)setupLayer
{
self.myEagLayer = (CAEAGLLayer *)self.layer;
[self setContentScaleFactor:[[UIScreen mainScreen]scale]];
self.myEagLayer.opaque = YES;
self.myEagLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking,kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
}
+ (Class)layerClass {
return [CAEAGLLayer class];
}
2.设置上下文
//2.设置上下文
-(void)setupContext
{
EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
EAGLContext *context = [[EAGLContext alloc]initWithAPI:api];
if (!context) {
NSLog(@"Create Context Failed");
return;
}
if (![EAGLContext setCurrentContext:context]) {
NSLog(@"Set Current Context Failed");
return;
}
self.myContext = context;
}
3.清空缓存区
//3.清空缓存区
-(void)deletBuffer
{
glDeleteBuffers(1, &_myColorRenderBuffer);
_myColorRenderBuffer = 0;
glDeleteBuffers(1, &_myColorFrameBuffer);
_myColorFrameBuffer = 0;
}
4.设置renderBuffer
//4.设置renderBuffer
-(void)setupRenderBuffer
{
//1.定义一个缓存区
GLuint buffer;
//2.申请一个缓存区标志
glGenRenderbuffers(1, &buffer);
//3.
self.myColorRenderBuffer = buffer;
//4.将标识符绑定到GL_RENDERBUFFER
glBindRenderbuffer(GL_RENDERBUFFER, self.myColorRenderBuffer);
[self.myContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:self.myEagLayer];
}
5.设置frameBuffer
//5.设置frameBuffer
-(void)setupFrameBuffer
{
//1.定义一个缓存区
GLuint buffer;
//2.申请一个缓存区标志
glGenFramebuffers(1, &buffer);
//3.
self.myColorFrameBuffer = buffer;
//4.设置当前的framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, self.myColorFrameBuffer);
//5.将_myColorRenderBuffer 装配到GL_COLOR_ATTACHMENT0 附着点上
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, self.myColorRenderBuffer);
}
6.绘制(重点!!!)
//6.绘制
-(void)render
{
//1.清屏颜色
glClearColor(0, 0.0, 0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
CGFloat scale = [[UIScreen mainScreen] scale];
//2.设置视口
glViewport(self.frame.origin.x * scale, self.frame.origin.y * scale, self.frame.size.width * scale, self.frame.size.height * scale);
//3.获取顶点着色程序、片元着色器程序文件位置
NSString* vertFile = [[NSBundle mainBundle] pathForResource:@"shaderv" ofType:@"vsh"];
NSString* fragFile = [[NSBundle mainBundle] pathForResource:@"shaderf" ofType:@"fsh"];
//4.判断self.myProgram是否存在,存在则清空其文件
if (self.myProgram) {
glDeleteProgram(self.myProgram);
self.myProgram = 0;
}
//5.加载程序到myProgram中来。
self.myProgram = [self loadShader:vertFile frag:fragFile];
//6.链接
glLinkProgram(self.myProgram);
GLint linkSuccess;
//7.获取链接状态
glGetProgramiv(self.myProgram, GL_LINK_STATUS, &linkSuccess);
if (linkSuccess == GL_FALSE) {
GLchar messages[256];
glGetProgramInfoLog(self.myProgram, sizeof(messages), 0, &messages[0]);
NSString *messageString = [NSString stringWithUTF8String:messages];
NSLog(@"error%@", messageString);
return ;
}else {
glUseProgram(self.myProgram);
}
//8.创建顶点数组 & 索引数组
//(1)顶点数组 前3顶点值(x,y,z),后3位颜色值(RGB)
GLfloat attrArr[] =
{
-0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, //左上0
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, //右上1
-0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, //左下2
0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, //右下3
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, //顶点4
};
//(2).索引数组
GLuint indices[] =
{
0, 3, 2,
0, 1, 3,
0, 2, 4,
0, 4, 1,
2, 3, 4,
1, 4, 3,
};
//(3).判断顶点缓存区是否为空,如果为空则申请一个缓存区标识符
if (self.myVertices == 0) {
glGenBuffers(1, &_myVertices);
}
//9.-----处理顶点数据-------
//(1).将_myVertices绑定到GL_ARRAY_BUFFER标识符上
glBindBuffer(GL_ARRAY_BUFFER, _myVertices);
//(2).把顶点数据从CPU内存复制到GPU上
glBufferData(GL_ARRAY_BUFFER, sizeof(attrArr), attrArr, GL_DYNAMIC_DRAW);
//(3).将顶点数据通过myPrograme中的传递到顶点着色程序的position
//1.glGetAttribLocation,用来获取vertex attribute的入口的.
//2.告诉OpenGL ES,通过glEnableVertexAttribArray,
//3.最后数据是通过glVertexAttribPointer传递过去的。
//注意:第二参数字符串必须和shaderv.vsh中的输入变量:position保持一致
GLuint position = glGetAttribLocation(self.myProgram, "position");
//(4).打开position
glEnableVertexAttribArray(position);
//(5).设置读取方式
//参数1:index,顶点数据的索引
//参数2:size,每个顶点属性的组件数量,1,2,3,或者4.默认初始值是4.
//参数3:type,数据中的每个组件的类型,常用的有GL_FLOAT,GL_BYTE,GL_SHORT。默认初始值为GL_FLOAT
//参数4:normalized,固定点数据值是否应该归一化,或者直接转换为固定值。(GL_FALSE)
//参数5:stride,连续顶点属性之间的偏移量,默认为0;
//参数6:指定一个指针,指向数组中的第一个顶点属性的第一个组件。默认为0
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, NULL);
//10.--------处理顶点颜色值-------
//(1).glGetAttribLocation,用来获取vertex attribute的入口的.
//注意:第二参数字符串必须和shaderv.glsl中的输入变量:positionColor保持一致
GLuint positionColor = glGetAttribLocation(self.myProgram, "positionColor");
//(2).设置合适的格式从buffer里面读取数据
glEnableVertexAttribArray(positionColor);
//(3).设置读取方式
//参数1:index,顶点数据的索引
//参数2:size,每个顶点属性的组件数量,1,2,3,或者4.默认初始值是4.
//参数3:type,数据中的每个组件的类型,常用的有GL_FLOAT,GL_BYTE,GL_SHORT。默认初始值为GL_FLOAT
//参数4:normalized,固定点数据值是否应该归一化,或者直接转换为固定值。(GL_FALSE)
//参数5:stride,连续顶点属性之间的偏移量,默认为0;
//参数6:指定一个指针,指向数组中的第一个顶点属性的第一个组件。默认为0
glVertexAttribPointer(positionColor, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, (float *)NULL + 3);
//11.找到myProgram中的projectionMatrix、modelViewMatrix 2个矩阵的地址。如果找到则返回地址,否则返回-1,表示没有找到2个对象。
GLuint projectionMatrixSlot = glGetUniformLocation(self.myProgram, "projectionMatrix");
GLuint modelViewMatrixSlot = glGetUniformLocation(self.myProgram, "modelViewMatrix");
float width = self.frame.size.width;
float height = self.frame.size.height;
//12.创建4 * 4投影矩阵
KSMatrix4 _projectionMatrix;
//(1)获取单元矩阵
ksMatrixLoadIdentity(&_projectionMatrix);
//(2)计算纵横比例 = 长/宽
float aspect = width / height; //长宽比
//(3)获取透视矩阵
/*
参数1:矩阵
参数2:视角,度数为单位
参数3:纵横比
参数4:近平面距离
参数5:远平面距离
参考PPT
*/
ksPerspective(&_projectionMatrix, 30.0, aspect, 5.0f, 20.0f); //透视变换,视角30°
//(4)将投影矩阵传递到顶点着色器
/*
void glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
参数列表:
location:指要更改的uniform变量的位置
count:更改矩阵的个数
transpose:是否要转置矩阵,并将它作为uniform变量的值。必须为GL_FALSE
value:执行count个元素的指针,用来更新指定uniform变量
*/
glUniformMatrix4fv(projectionMatrixSlot, 1, GL_FALSE, (GLfloat*)&_projectionMatrix.m[0][0]);
//13.创建一个4 * 4 矩阵,模型视图矩阵
KSMatrix4 _modelViewMatrix;
//(1)获取单元矩阵
ksMatrixLoadIdentity(&_modelViewMatrix);
//(2)平移,z轴平移-10
ksTranslate(&_modelViewMatrix, 0.0, 0.0, -10.0);
//(3)创建一个4 * 4 矩阵,旋转矩阵
KSMatrix4 _rotationMatrix;
//(4)初始化为单元矩阵
ksMatrixLoadIdentity(&_rotationMatrix);
//(5)旋转
ksRotate(&_rotationMatrix, xDegree, 1.0, 0.0, 0.0); //绕X轴
ksRotate(&_rotationMatrix, yDegree, 0.0, 1.0, 0.0); //绕Y轴
ksRotate(&_rotationMatrix, zDegree, 0.0, 0.0, 1.0); //绕Z轴
//(6)把变换矩阵相乘.将_modelViewMatrix矩阵与_rotationMatrix矩阵相乘,结合到模型视图
ksMatrixMultiply(&_modelViewMatrix, &_rotationMatrix, &_modelViewMatrix);
//(7)将模型视图矩阵传递到顶点着色器
/*
void glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
参数列表:
location:指要更改的uniform变量的位置
count:更改矩阵的个数
transpose:是否要转置矩阵,并将它作为uniform变量的值。必须为GL_FALSE
value:执行count个元素的指针,用来更新指定uniform变量
*/
glUniformMatrix4fv(modelViewMatrixSlot, 1, GL_FALSE, (GLfloat*)&_modelViewMatrix.m[0][0]);
//14.开启剔除操作效果
glEnable(GL_CULL_FACE);
//15.使用索引绘图
/*
void glDrawElements(GLenum mode,GLsizei count,GLenum type,const GLvoid * indices);
参数列表:
mode:要呈现的画图的模型
GL_POINTS
GL_LINES
GL_LINE_LOOP
GL_LINE_STRIP
GL_TRIANGLES
GL_TRIANGLE_STRIP
GL_TRIANGLE_FAN
count:绘图个数
type:类型
GL_BYTE
GL_UNSIGNED_BYTE
GL_SHORT
GL_UNSIGNED_SHORT
GL_INT
GL_UNSIGNED_INT
indices:绘制索引数组
*/
glDrawElements(GL_TRIANGLES, sizeof(indices) / sizeof(indices[0]), GL_UNSIGNED_INT, indices);
//16.要求本地窗口系统显示OpenGL ES渲染<目标>
[self.myContext presentRenderbuffer:GL_RENDERBUFFER];
}
7.添加点击事件和设置定时器
- (IBAction)XClick:(id)sender {
//开启定时器
if (!myTimer) {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(reDegree) userInfo:nil repeats:YES];
}
//更新的是X还是Y
bX = !bX;
}
- (IBAction)YClick:(id)sender {
//开启定时器
if (!myTimer) {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(reDegree) userInfo:nil repeats:YES];
}
//更新的是X还是Y
bY = !bY;
}
- (IBAction)ZClick:(id)sender {
//开启定时器
if (!myTimer) {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(reDegree) userInfo:nil repeats:YES];
}
//更新的是X还是Y
bZ = !bZ;
}
-(void)reDegree
{
//如果停止X轴旋转,X = 0则度数就停留在暂停前的度数.
//更新度数
xDegree += bX * 5;
yDegree += bY * 5;
zDegree += bZ * 5;
//重新渲染
[self render];
}
8.调用方法
-(void)layoutSubviews
{
//1.设置图层
[self setupLayer];
//2.设置上下文
[self setupContext];
//3.清空缓存区
[self deletBuffer];
//4.设置renderBuffer;
[self setupRenderBuffer];
//5.设置frameBuffer
[self setupFrameBuffer];
//6.绘制
[self render];
}