// 范例P185.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <gl/glut.h>
#include <math.h>
#include <conio.h>
#include <stdlib.h>
#define M_PI 3.1415926
GLuint theTorus;
/*绘制一个圆环*/
static void torus(int numc,int numt)
{
int i,j,k;
double s,t,x,y,z,twopi;
twopi=2*(double)M_PI;
for(i=0;i<numc;i++)
{
glBegin(GL_QUAD_STRIP);
for(j=0;j<=numt;j++)
{
for(k=1;k>=0;k--)
{
s=(i+k)%numc+0.5;
t=j%numt;
x=(1+0.1*cos(s*twopi/numc))*cos(t*twopi/numt);
y=(1+0.1*cos(s*twopi/numc))*sin(t*twopi/numt);
z=0.1*sin(s*twopi/numc);
glVertex3f(x,y,z);
}
}
glEnd();
}
}
/*创建1个存储圆环的显示列表并初始化状态*/
static void init(void)
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0,0.0,0.0,0.0);
GLfloat light_diffuse[]={1.0,0.0,0.0,1.0};
GLfloat light_ambient[]={1.0,1.0,1.0,1.0};
GLfloat mat_specular[]={1.0,1.0,1.0,1.0};
GLfloat mat_shininess=100;
GLfloat mat_diffuse[]={1.0,1.0,1.0,1.0};
glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,mat_shininess);
glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,mat_specular);
glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse);
glLightfv(GL_LIGHT0,GL_AMBIENT,light_ambient);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glPopMatrix();
theTorus=glGenLists(1);
glNewList(theTorus,GL_COMPILE);
torus(8,25);
glEndList();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT); //清除所有像素
glColor3f(1.0,1.0,1.0); //设置画笔白色
/*在缓存中绘制4对顶点坐标的矩形*/
glCallList(theTorus);
glFlush(); //立即显示出来
}
void reshape(int w,int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(15,(GLfloat)w/(GLfloat)h,1.0,100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,10,0,0,0,0,1,0);
}
/*x---绕x轴旋转,y---绕y轴旋转,i---回到观察角*/
void keyboard(unsigned char key,int x,int y)
{
GLfloat light_position[]={1.0,1.0,1.0,0.0};
switch(key){
case 'x':
case 'X':
glRotatef(30.0,1.0,0.0,0.0);
glLightfv(GL_LIGHT0,GL_POSITION,light_position);
glutPostRedisplay();
break;
case 'y':
case 'Y':
glRotatef(30.0,0.0,1.0,0.0);
glutPostRedisplay();
break;
case 'i':
case 'I':
glLoadIdentity();
gluLookAt(0,0,10,0,0,0,0,1,0);
glutPostRedisplay();
break;
case 27:
exit(0);
break;
}
}
int main(int argc,char ** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(250,250); //初始化窗口大小
glutInitWindowPosition(0,0); //初始化窗口位置
glutCreateWindow("hello"); //创建标题为“hello”的窗口
init(); //调用初始化函数
glutDisplayFunc(display); //注册回调函数
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop(); //进入主循环处理事件
return 0;
}
评论