计算机图形学课程实验:代码实现一个基于简单光照模型的三维圆环体的真实感显示,用openGL实现,给出完整代码
时间: 2024-03-13 21:43:31 浏览: 19
很好,这是一个比较经典的计算机图形学实验,我可以给您提供一个基于OpenGL实现的简单光照模型的三维圆环体真实感显示的代码,希望对您有所帮助。
代码如下:
```c++
#include <GL/glut.h>
#include <math.h>
void init(void) {
// 设置光照模型
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 50.0 };
GLfloat light_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glEnable(GL_DEPTH_TEST);
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// 绘制圆环体
int i;
float x, y, z, theta;
float radius1 = 1.0;
float radius2 = 0.5;
float height = 2.0;
int num_slices = 30;
int num_stacks = 10;
for (i = 0; i < num_slices; i++) {
glBegin(GL_QUAD_STRIP);
for (int j = 0; j <= num_stacks; j++) {
theta = i * 2.0 * M_PI / num_slices;
x = (radius1 + radius2 * cos(theta)) * cos(j * M_PI / num_stacks);
y = (radius1 + radius2 * cos(theta)) * sin(j * M_PI / num_stacks);
z = radius2 * sin(theta) + height / 2.0;
glNormal3f(cos(theta) * cos(j * M_PI / num_stacks), cos(theta) * sin(j * M_PI / num_stacks), sin(theta));
glVertex3f(x, y, z);
x = (radius1 + radius2 * cos(theta + 2.0 * M_PI / num_slices)) * cos(j * M_PI / num_stacks);
y = (radius1 + radius2 * cos(theta + 2.0 * M_PI / num_slices)) * sin(j * M_PI / num_stacks);
z = radius2 * sin(theta + 2.0 * M_PI / num_slices) + height / 2.0;
glNormal3f(cos(theta + 2.0 * M_PI / num_slices) * cos(j * M_PI / num_stacks), cos(theta + 2.0 * M_PI / num_slices) * sin(j * M_PI / num_stacks), sin(theta + 2.0 * M_PI / num_slices));
glVertex3f(x, y, z);
}
glEnd();
}
glFlush();
}
void reshape(int w, int h) {
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat)w / (GLfloat)h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("OpenGL Sphere");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
```
希望这份代码对您有所帮助!