openGL 大作业之n星变换
#include "stdafx.h" #include<stdio.h> #define GLUT_DISABLE_ATEXIT_HACK //不写这句话总运行出错,我也不知道为啥。。。 #include<gl/GLUT.h> #include<math.h> int change = 10; static GLfloat spin = 0.0;//static:静态全局变量,只要程序运行,内存中一直存在,文件内可见,文件外不可见 void init(void) { glClearColor(0.0, 0.0, 0.0, 0.0);//将清空颜色设置为黑 } int z = -1; void fillOption(GLint selectedOption) { z = -1; switch (selectedOption) { case 1:change-=2; break; case 2:z=-z; break; case 3:z =0; break; } glutPostRedisplay(); } void display(void) { glClear(GL_COLOR_BUFFER_BIT);//清除颜色缓存 glPushMatrix();//将当前矩阵压栈(保存现场) glRotatef(spin, 0.0, 0.0,z);//旋转方向,遵循右手原则 glColor3f(1.0, 1.0, 1.0); glEnable(GL_LINE_SMOOTH);//让线条更平滑 GLint x = 100; GLdouble a = 1.256637, c = 1; while (x--) { glShadeModel(GL_SMOOTH);//渐变色 glBegin(GL_LINE_STRIP); glVertex2f(50 * cos(a + c), 50 * sin(a + c)); glColor3f(1.0, 0.0, 0.0); glVertex2f(50 * cos(3 * a + c), 50 * sin(3 * a + c)); glColor3f(0.0, 1.0, 0.0); glVertex2f(50 * cos(5 * a + c), 50 * sin(5 * a + c)); glColor3f(0.0, 0.0, 1.0); glVertex2f(50 * cos(2 * a + c), 50 * sin(2 * a + c)); glColor3f(0.0, 1.0, 1.0); glVertex2f(50 * cos(4 * a + c), 50 * sin(4 * a + c)); glColor3f(1.0, 1.0, 1.0); glVertex2f(50 * cos(a + c), 50 * sin(a + c)); glEnd(); c+=0.0314159365*change; } glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINE_STRIP); glEnd(); glPopMatrix(); glutSwapBuffers();//双缓存技术的函数,作用为交换两个缓冲区的指针 } void spinDisplay(void) { spin = spin + 0.04; if (spin > 360.0) { spin = spin - 360.0; } glutPostRedisplay();//glutPostRedisplay 标记当前窗口需要重新绘制。通过glutMainLoop下一次循环时,窗口显示将被回调以重新显示窗口的正常面板 } void reshape(int w, int h) { glViewport(0, 0, (GLsizei)w, (GLsizei)h);//函数作用:用一个视景体截取图像 glMatrixMode(GL_PROJECTION);//mode 指定哪一个矩阵堆栈是下一个矩阵操作的目标,参数表示接下来要进行投影相关的操作 glLoadIdentity();//设置当前变化矩阵为单位矩阵;单位矩阵就是对角线上都是1,其余元素皆为0的矩阵。然后复位 glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW);//进行视景相关的操作 glLoadIdentity(); } void mouse(int button, int state, int x, int y) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) glutIdleFunc(spinDisplay);//glutIdleFunc函数如果启用,这个idle function会被不断调用,直到有窗口事件发生 break; case GLUT_RIGHT_BUTTON: if (state == GLUT_DOWN) glutIdleFunc(NULL); break; default: break; } } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(680, 680); glutInitWindowPosition(400, 0); glutCreateWindow("big homework"); init(); glutDisplayFunc(display);//每次重绘场景时调用 glutCreateMenu(fillOption); glutAddMenuEntry("amount", 1); glutAddMenuEntry("reverse", 2); glutAddMenuEntry("narrow", 3); glutAttachMenu(GLUT_RIGHT_BUTTON); glutReshapeFunc(reshape);//每次窗口改变时调用 glutMouseFunc(mouse);//每次使用鼠标时调用 glutMainLoop(); return 0; }
随便用