OpenGL绘制添加光照的材质效果的球体,并且能用键盘实现缩放,平移
时间: 2024-05-01 09:19:08 浏览: 8
下面是一个使用OpenGL绘制球体并添加光照和材质效果的示例代码。你可以通过键盘实现缩放和平移。
```c++
#include <GL/glut.h>
#include <cmath>
// 球体半径
const float sphereRadius = 1.0f;
// 光源位置
const GLfloat lightPosition[] = { 0.0f, 0.0f, 10.0f, 1.0f };
// 球体材质
const GLfloat sphereAmbient[] = { 0.5f, 0.5f, 0.5f, 1.0f };
const GLfloat sphereDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat sphereSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat sphereShininess[] = { 100.0f };
// 窗口大小
int windowWidth = 640;
int windowHeight = 480;
// 球体位置
float sphereX = 0.0f;
float sphereY = 0.0f;
float sphereZ = 0.0f;
// 缩放比例
float scale = 1.0f;
// 窗口大小变化回调函数
void reshape(int width, int height)
{
windowWidth = width;
windowHeight = height;
glViewport(0, 0, windowWidth, windowHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (float)windowWidth / (float)windowHeight, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0f, 0.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
}
// 绘制回调函数
void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(sphereX, sphereY, sphereZ);
glScalef(scale, scale, scale);
// 设置光源位置
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
// 设置球体材质
glMaterialfv(GL_FRONT, GL_AMBIENT, sphereAmbient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, sphereDiffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, sphereSpecular);
glMaterialfv(GL_FRONT, GL_SHININESS, sphereShininess);
// 绘制球体
glutSolidSphere(sphereRadius, 50, 50);
glutSwapBuffers();
}
// 键盘回调函数
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case '+':
scale += 0.1f;
break;
case '-':
scale -= 0.1f;
break;
case 'w':
sphereY += 0.1f;
break;
case 's':
sphereY -= 0.1f;
break;
case 'a':
sphereX -= 0.1f;
break;
case 'd':
sphereX += 0.1f;
break;
case 'q':
sphereZ += 0.1f;
break;
case 'e':
sphereZ -= 0.1f;
break;
default:
break;
}
glutPostRedisplay();
}
// 初始化函数
void init()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glShadeModel(GL_SMOOTH);
}
// 程序入口
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("OpenGL Sphere");
glutReshapeFunc(reshape);
glutDisplayFunc(render);
glutKeyboardFunc(keyboard);
init();
glutMainLoop();
return 0;
}
```