通过指定图元GL_LINES可以再空间中画一条直线。下面的代码段将画一条直线:
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(30.0f, 30.0f, 30.0f);
glEnd();
这里有一点需要注意,空间中每两个顶点确定一条直线。如果有奇数个点,最后一个点将被忽略。
下面的一个示例程序将展示如何画线:
#include
#include
#define GL_PI 3.14
void RenderScene(void)
{
float x,y,z,angle;
glClear(GL_COLOR_BUFFER_BIT); //清除颜色缓存
glColor3f(1.0f, 1.0f, 0.0f);
glBegin(GL_LINES);
x = 0.0f;
y = 0.0f;
z = 0.0f;
for(angle=0.0f; angle <= GL_PI; angle += (GL_PI/20.0f))
{
y = 50.0f * sin(angle);
x = 50.0f * cos(angle);
glVertex3f(x,y,z);
y = 50.0f * sin(GL_PI + angle);
x = 50.0f * cos(GL_PI + angle);
glVertex3f(x,y,z);
}
glEnd();
glFlush(); //刷新
}
//当窗口大小变化时调用
void ChangeSize(GLsizei w,GLsizei h)
{
GLfloat aspectRatio;
if(0 == h)
h = 1;
//设置视口大小
glViewport(0,0,w,h);
//重置坐标系
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//建立裁剪区
aspectRatio = (GLfloat)w / (GLfloat)h;
if(w <= h)
glOrtho(-100.0,100.0,-100.0/aspectRatio,100/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();
}
//设置渲染
void SetupRC(void)
{
glClearColor(0.0f,0.0f,1.0f,1.0f);
}
int main(int argc,char* argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutCreateWindow("OpenGL Sample");
glutDisplayFunc(RenderScene);
glutReshapeFunc(ChangeSize);
SetupRC();
glutMainLoop();
return 0;
}
程序截图如下:
......