OpenGL代码学习(2)
#include "GLShaderManager.h"//着色管理器类 #include "GLTools.h"//包含了大部分GLTool中类似C语言的独立函数 #include <GLUT/GLUT.h>//在Mac系统下使用GLUT,在Window或Linux上使用的是freeglut的静态库 GLShaderManager shaderManager;//定义一个着色管理器 GLBatch triangleBatch;//简单的批次容器,是GLTools的一个简单的容器类 GLfloat blockSize = 0.2f;//边长 GLfloat vVerts[] = { -blockSize/2, -blockSize/2, 0.f, blockSize/2, -blockSize/2, 0.f, blockSize/2, blockSize/2, 0.f, -blockSize/2, blockSize/2, 0.f };//正方形的4个点坐标 void changeSize(int w, int h) { glViewport(0, 0, w, h); printf("w:%d h:%d\n", w, h); // glMatrixMode (GL_PROJECTION); // glLoadIdentity ( ); // gluOrtho2D (0.0, (GLdouble) w, 0.0, (GLdouble) h); // glClear (GL_COLOR_BUFFER_BIT); }; void RenderScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); GLfloat vRed[] = {1.f, 0.f, 0.f, 1.f}; shaderManager.UseStockShader(GLT_SHADER_IDENTITY, vRed); triangleBatch.Draw(); glutSwapBuffers(); }; void setupRC(void) { glClearColor(0.98f, 0.40f, 0.70f, 1); shaderManager.InitializeStockShaders(); triangleBatch.Begin(GL_TRIANGLE_FAN, 4); triangleBatch.CopyVertexData3f(vVerts); triangleBatch.End(); } void SpecialKeys(int key, int x, int y) { GLfloat stepSize = 0.025f; GLfloat blockX = vVerts[0]; GLfloat blockY = vVerts[10]; printf("v[0] = %f\n", vVerts[0]); printf("v[10] = %f\n", 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.f) { blockX = -1.f; } if (blockX > (1.f - blockSize)) { blockX = 1.f - blockSize; } if (blockY < (-1.f + blockSize)) { blockY = -1.f + blockSize; } if (blockY > 1.f) { blockY = 1.f; } vVerts[0] = blockX; vVerts[1] = blockY - blockSize; vVerts[3] = blockX + blockSize; vVerts[4] = blockY - blockSize; vVerts[6] = blockX + blockSize; vVerts[7] = blockY; vVerts[9] = blockX; vVerts[10] = blockY; triangleBatch.CopyVertexData3f(vVerts); glutPostRedisplay(); } int main(int argc, char * argv[]) { gltSetWorkingDirectory(argv[0]); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL); glutInitWindowSize(800, 700); //glutInitWindowSize(800, 720); glutCreateWindow("OpenGL测试"); glutReshapeFunc(changeSize); glutDisplayFunc(RenderScene); glutSpecialFunc(SpecialKeys); GLenum status = glewInit(); if (GLEW_OK != status) { printf("GLEW Error:%s\n", glewGetErrorString(status)); return 1; } // 设置渲染环境 setupRC(); glutMainLoop(); return 0; }