#import "ViewController.h"
/
// This data type is used to store information for each vertex
typedef struct {
GLKVector3 positionCoords;
}SceneVertex;
/
// Define vertex data for a triangle to use in example, relative screen center
static const SceneVertex vertices[] = {
{{-0.5f, -0.5f, 0.0}}, // lower left corner
{{ 0.5f, -0.5f, 0.0}}, // lower right corner
{{-0.5f, 0.5f, 0.0}} // upper left corner
};
@interface ViewController ()
{
GLuint _vertexBufferID;
}
@property(nonatomic, strong) GLKBaseEffect *baseEffect;
@end
@implementation ViewController
- (void)dealloc
{
// Make the view's context current
GLKView *view = (GLKView *)self.view;
[EAGLContext setCurrentContext:view.context];
// Delete buffers that aren't needed when view is unloaded
if (0 != _vertexBufferID) {
// Setp 7
glDeleteBuffers(1, &_vertexBufferID);
_vertexBufferID = 0;
}
[((GLKView *)self.view) setContext:nil];
[EAGLContext setCurrentContext:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
GLKView *view = (GLKView *)self.view;
NSAssert([view isKindOfClass:[GLKView class]], @"View controller's view is not a GLKView");
view.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
[EAGLContext setCurrentContext:view.context];
self.baseEffect = [[GLKBaseEffect alloc] init];
self.baseEffect.useConstantColor = GL_TRUE;
self.baseEffect.constantColor = GLKVector4Make(1.0, //red
0.5, //green
1.0, //blue
1.0 //alpha
);
glClearColor(1.0, 1.0, 1.0, 1.0); //set self.view background color
//Setp 1 为缓存生成一个唯一的标识符
glGenBuffers(1, &(_vertexBufferID));
//Setp 2 把指定缓存的标识符绑定到当前缓存
glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID);
//Setp 3 复制数据到缓存中
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
// Sync all effect changes for consistent state when drawing
[self.baseEffect prepareToDraw];
//使 glClearColor 函数生效
glClear(GL_COLOR_BUFFER_BIT);
//Setp 4.启动
glEnableVertexAttribArray(GLKVertexAttribPosition);
//Step 5.设置指针
glVertexAttribPointer(GLKVertexAttribPosition,
3, //three components per vertex
GL_FLOAT, // data is floating point
GL_FALSE, // no fixed point scaling
sizeof(SceneVertex), //stride
NULL //tells GPU to start at beginning of bound buffer
);
//Step 6.绘图
glDrawArrays(GL_TRIANGLES,
0, // Start with first vertex in currently bound buffer
3 // Use three vertices from currently bound buffer
);
}
@end