ubuntu+opengl程序设计(3)
--lihn1987(转载请著名作者,谢谢)
先上图
再上代码
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
///
// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);
// Set current drawing color to red
// R G B
glColor3f(1.0f, 0.0f, 0.0f);
// Draw a filled rectangle with current color
glRectf(-25.0f, 25.0f, 25.0f, -25.0f);
// Flush drawing commands
glFlush();
}
///
// Set up the rendering state
void SetupRC(void)
{
// Set clear color to blue
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
}
///
// Called by GLUT library when the window has chanaged size
void ChangeSize(GLsizei w, GLsizei h)
{
GLfloat aspectRatio;
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Establish clipping volume (left, right, bottom, top, near, far)
aspectRatio = (GLfloat)w / (GLfloat)h;
if (w <= h)
glOrtho (-100.0, 100.0, -100 / aspectRatio, 100.0 / aspectRatio,1.0, -1.0);
else
glOrtho (-100.0 * aspectRatio, 100.0 * aspectRatio,-100.0, 100.0, 1.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
///
// Main program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutCreateWindow("GLRect");
glutDisplayFunc(RenderScene);
glutReshapeFunc(ChangeSize);
SetupRC();
glutMainLoop();
return 0;
}
以下是对新用到的函数的一些说明:
void glColor3f( GLfloat red, GLfloat green, GLfloat blue);
该函数是一个颜色选择函数,使用后,其后的绘制,包括画笔和画刷。
void glRectf( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
根据两个坐标点,绘制一个矩形
void glViewport( GLint x, GLint y, GLsizei width, GLsizei height);
设置视角,其实我的理解在 2D里就是设置一个坐标原点的样子
void glMatrixMode( GLenum mode);
设置矩阵操作其中我们用到的两个
GL_MODELVIEW,对模型视景矩阵堆栈应用随后的矩阵操作 .
GL_PROJECTION,对投影矩阵应用随后的矩阵操作
void glOrtho( GLdouble left, GLdouble right,GLdouble bottom, GLdouble top, GLdouble nearVal, GLdouble farVal);
该函数是为了在窗口大小变化时将我们的图形映射到变化后的窗口上的
其中我们做了这样的操作
if (w <= h)
glOrtho (-100.0, 100.0, -100 /
else
glOrtho (-100.0 * aspectRatio, 10
-100.0, 100.0, 1.0, -1.0)
主要是为了让窗口宽高比在变化的时候,我们绘制的图形依然保持其原有的宽搞比的,而当我们使用使用以下语句的 时候,窗口的宽搞比变化时,我们绘制图形的宽搞比也会发生相应的变化。
GlOrtho (-100.0 , 100.0 , -100.0, 100.0, 1.0, -1.0)