opengl 太阳系模拟
程序员文章站
2022-07-13 11:11:45
...
#include <GL/glut.h>
#include <stdlib.h>
static int year = 0, day = 0;//公转和自转分别转动角度,静态变量,所有函数都可以用
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);//清屏
glShadeModel (GL_FLAT);//设置的着色模式
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);//清颜色缓存
//太阳
glColor3f(1.0f, 0.0f, 0.0f);//红色
glPushMatrix();//压栈
glutWireSphere(1.0,20,16); /* draw sun */// 线框体 半径 1.0 20,16是经度纬度线框的个数
//行星
glColor3f(1.0f, 0.0f, 1.0f);//平红色
glPushMatrix();//压栈
glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (-2.0, 0.0, 0.0);//xyz,在x方向平移2.0
glRotatef ((GLfloat) day, 1.0, 1.0, 1.0);
glutWireSphere(0.2, 10, 8); //1
glPopMatrix();//弹出
glColor3f(0.0f, 1.0f, 1.0f);//情色
glPushMatrix();//压栈
glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (2.0, 0.0, 0.0);
glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.5, 10, 8); //2
glPopMatrix();//弹出
glColor3f(0.0f, 0.0f, 1.0f);//蓝色
glPushMatrix();//压栈
glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (3.5, 0.0, 0.0);
glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.3, 10, 8); //3
glPopMatrix();//弹出
glColor3f(1.0f, 1.0f, 0.0f);//黄色
glPushMatrix();//压栈
glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (-3.5, 0.0, 0.0);
glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.3, 10, 8); //4
glPopMatrix();//弹出
glColor3f(0.0f, 1.0f, 0.0f);//绿色
glPushMatrix();//压栈
glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (5.0, 0.0, 0.0);
glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.3, 10, 8); //5
glColor3f(1.0f, 1.0f, 0.0f);//黄色
glPushMatrix();//压栈
glRotatef ((GLfloat) year, 1.0, 1.0, 0.0);
glTranslatef (0.0, 2.0, 0.0);
glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.3, 10, 8); //5.1
glPopMatrix();//弹出
glutSwapBuffers();
}
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);//设定视点(观测点)
}
void keyboard (unsigned char key, int x, int y)//按到键盘的key值,
{
switch (key) {
case 'd':
day = (day + 10) % 360;//逆时针转10度
glutPostRedisplay();
break;
case 'D':
day = (day - 10) % 360; //顺时针转10度
glutPostRedisplay();
break;
case 'y':
year = (year + 5) % 360;
glutPostRedisplay();
break;
case 'Y':
year = (year - 5) % 360;
glutPostRedisplay();
break;
case 27:
exit(0);
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);//初始化窗口
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);//两个模式
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();//清屏之类的
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);//事件处理函数,键盘按下去,执行的一个函数
glutMainLoop();
return 0;
}
上一篇: 浅谈redis数据结构
下一篇: 用 Python 动态模拟太阳系运转