#include "stdafx.h"
#include
#include"gl.h"
#include"glut.h"
//旋转参数
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;
//深度测试技术
BOOL bDepth = FALSE;
//剔除开关
BOOL bCull = FALSE;
//渲染场景
void SetupRC()
{
//设置窗口背景颜色为黑色
glClearColor(0.0f, 0.0f, 0.0f,1.0f);
//指定多边形的阴影模式为平面阴暗模式
glShadeModel(GL_FLAT);
}
//改变大小
void ChangeSize(int w, int h)
{
if (h == 0) h = 1;
glViewport(0, 0, w, h);//图形显示位置
glMatrixMode(GL_PROJECTION);//切换到投影矩阵
glLoadIdentity();//将当前的用户的坐标系统的原点移到屏幕中心
if (w <= h)
glOrtho(-100.0f, 100.0f, -100.0f*h / w, 100.0*h / w, -100.0f, 100.0f);
else
glOrtho(-100.0f*w/h, 100.0f*w/h, -100.0f , 100.0f, -100.0f, 100.0f);
glMatrixMode(GL_MODELVIEW);//对模型视景矩阵操作
glLoadIdentity();
}
//在窗口中绘制棱锥
void RenderScene(void)
{
//清除颜色及深度缓冲区
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//是否开启深度测试技术
if (bDepth)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
//是否打开剔除
if (bCull)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);
//旋转图形
glPushMatrix();
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);
// 指定顺时针绕法的多边形为多边形正面
glFrontFace(GL_CW);
//绘制三棱锥
glBegin(GL_TRIANGLE_FAN);
glVertex3f(0.0, 0.0, 100.0);
glVertex3f(0.0, 60.0, 0.0);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(60.0, -60.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(-60.0, -60.0, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 60.0, 0.0);
glEnd();
//绘制三棱锥底面
glBegin(GL_TRIANGLE_FAN);
glVertex3f(0.0, 60.0, 0.0);
glVertex3f(60.0, -60.0, 0.0);
glColor3f(1.0, 1.0, 0.0);
glVertex3f(-60.0, -60.0, 0.0);
glEnd();
glPopMatrix();
//刷新命令缓冲区
glutSwapBuffers();
}
//控制上下左右方向键
void ControlKeys(int key, int x, int y)
{
if (key == GLUT_KEY_UP)
xRot -= 5.0f;
if (key == GLUT_KEY_DOWN)
xRot += 5.0f;
if (key == GLUT_KEY_LEFT)
yRot -= 5.0f;
if (key == GLUT_KEY_RIGHT)
yRot += 5.0f;
if (xRot > 356.0f) xRot = 0.0f;
if (xRot <-1.0f) xRot = 355.0f;
if (yRot > 356.0f) yRot = 0.0f;
if (yRot <-1.0f) yRot = 355.0f;
//刷新窗口
glutPostRedisplay();
}
//创建菜单
void CreateMenu(int value)
{
switch (value)
{
case 1:
bDepth = !bDepth;
break;
case 2:
bCull = !bCull;
break;
default:
break;
}
glutPostRedisplay();//标记当前窗口需要重新绘制
}
int _tmain(int argc, _TCHAR* argv[])
{
glutInit(&argc, (char**)argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutCreateWindow("绘制三棱锥");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutSpecialFunc(ControlKeys);
//创建菜单
glutCreateMenu(CreateMenu);
//添加菜单
glutAddMenuEntry("深度测试技术", 1);
glutAddMenuEntry("剔除背面测试", 2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
SetupRC();
glutMainLoop();//进入GLUT事件处理循环
return 0;
}