GLKitを使って三角を表示する方法のメモ。
Framework
・GLKit
・OpenGLES
※ Build Phases の Link Binary … に追加。
ポイント
・EAGLContext
・GLKBaseEffect
・GLKVector
・GLKView
・GLKViewController
注意
こんなログが出る場合、
reason: ‘-[GLKViewController loadView] loaded the “ViewController_iPhone” nib but didn’t get a GLKView
nibとかのviewのclassをGLKViewに変更する。
三角形を表示するサンプルコード
————————-
ViewController.h
————————-
#import <GLKit/GLKit.h>
@interface ViewController : GLKViewController{
GLuint vertexBufferID;
}
@property (strong, nonatomic) GLKBaseEffect *baseEffect;
@end
————————-
ViewController.m
————————-
#import “ViewController.h”
@implementation ViewController
@synthesize baseEffect;
typedef struct {
GLKVector3 position;
} Vertex;
// 三角の座標
static const Vertex vertices[] =
{
{{-0.5f, –0.5f, 0.0}},
{{ 0.5f, –0.5f, 0.0}},
{{-0.5f, 0.5f, 0.0}}
};
– (void)viewDidLoad
{
[super viewDidLoad];
GLKView *view = (GLKView*)self.view;
// OpenGL ES2を指定
view.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
// set context
[EAGLContext setCurrentContext:view.context];
// 三角形に白を設定
self.baseEffect = [[GLKBaseEffect alloc] init];
self.baseEffect.useConstantColor = GL_TRUE;
self.baseEffect.constantColor = GLKVector4Make(1.0f, 1.0f, 1.0f, 1.0f);
// 透明部分(背景)を黒に
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// GPUに点の情報を
glGenBuffers(1, &vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
}
#pragma mark – GLKView delegate
– (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
[self.baseEffect prepareToDraw];
glClear(GL_COLOR_BUFFER_BIT);
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), NULL);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
– (void)viewDidUnload
{
[super viewDidUnload];
// current contextのbufferを消す
GLKView *view = (GLKView *)self.view;
[EAGLContext setCurrentContext:view.context];
if (0 != vertexBufferID) {
glDeleteBuffers(1, &vertexBufferID);
}
// contextを消す
view.context = nil;
[EAGLContext setCurrentContext:nil];
}
@end