前言
在上一篇OpenGL 環境搭建基礎上修改main.cpp
檔案,完成使用OpenGL
圖片繪製和移動效果。
程式碼
詳細程式碼已做註釋:
#include "GLShaderManager.h"
#include "GLTools.h"
#include <GLUT/GLUT.h>
//著色管理器
GLShaderManager shaderManager;
//批次容器
GLBatch quadsBatch;
//矩形座標長度
GLfloat blockSize = 0.1f;
//頂點座標
GLfloat vVerts[] = {
-blockSize,-blockSize,0.0f,
blockSize,-blockSize,0.0f,
blockSize,blockSize,0.0f,
-blockSize,blockSize,0.0f
};
//視窗大小修改回撥
void changeSize(int w, int h) {
glViewport(0, 0, w, h);
}
//區域渲染
void renderScene(void) {
//清除一個快取區
glClear(GL_COLOR_BUFFER_BIT);
GLfloat vBlue[] = {0.0,0.0,1.0,1.0f};
//使用著色器渲染
shaderManager.UseStockShader(GLT_SHADER_IDENTITY,vBlue);
quadsBatch.Draw();
//後臺緩衝區渲染完畢後交給前臺顯示
glutSwapBuffers();
}
//初始化
void setupRC() {
glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
shaderManager.InitializeStockShaders();
quadsBatch.Begin(GL_QUADS, 4);
quadsBatch.CopyVertexData3f(vVerts);
quadsBatch.End();
}
//處理鍵盤控制圖形移動
void specialKeys(int key, int x, int y) {
GLfloat stepSize = 0.01f;
GLfloat blockX = vVerts[0];
GLfloat blockY = vVerts[10];
if (key == GLUT_KEY_UP) {
blockY += stepSize;
}
if (key == GLUT_KEY_DOWN) {
blockY -= stepSize;
}
if (key == GLUT_KEY_LEFT) {
blockX -= stepSize;
}
if (key == GLUT_KEY_RIGHT) {
blockX += stepSize;
}
if (blockX < -1.0f) {
blockX = -1.0f;
}
if (blockX > (1.0 - blockSize * 2)) {
blockX = 1.0f - blockSize * 2;
}
if (blockY < -1.0f + blockSize * 2 ) {
blockY = -1.0f + blockSize * 2;
}
if (blockY > 1.0f) {
blockY = 1.0f;
}
//處理頂點
vVerts[0] = blockX;
vVerts[1] = blockY - blockSize*2;
vVerts[3] = blockX + blockSize*2;
vVerts[4] = blockY - blockSize*2;
vVerts[6] = blockX + blockSize*2;
vVerts[7] = blockY;
vVerts[9] = blockX;
vVerts[10] = blockY;
quadsBatch.CopyVertexData3f(vVerts);
glutPostRedisplay();
}
int main(int argc, char *argv[]) {
//設定工作目錄
gltSetWorkingDirectory(argv[0]);
//初始化glut庫
glutInit(&argc, argv);
//初始化一個雙緩衝區,離屏區渲染,視窗區顯示
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(600, 600);
glutCreateWindow("dowZhange");
//註冊重塑函式
glutReshapeFunc(changeSize);
//註冊顯示函式
glutDisplayFunc(renderScene);
glutSpecialFunc(specialKeys);
//用於檢查OpenGL API對程式可用
GLenum status = glewInit();
if (GLEW_OK != status) {
return 1;
}
setupRC();
glutMainLoop();
return 0;
}
複製程式碼