# 基于OpenGL的随机图动画演示框架与代码

//第三方库： sudo apt-get install freeglut3-dev
//		   其中，用到了glut.h文件
//编译命令：g++ test.cpp -lglut -lGL -lGLU
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <math.h>
#include <GL/glut.h>

using namespace std;

#define Width 600
#define Height 600

typedef struct Point {
GLfloat x, y;
Point() : x(0), y(0) {};
Point(GLfloat x, GLfloat y) : x(x), y(y) {
}
} Point;

typedef struct Line {
Point lbegin, lend;
Line(Point& pa, Point& pb) {
lbegin.x = pa.x;
lbegin.y = pa.y;
lend.x = pb.x;
lend.y = pb.y;
}
} Line;

typedef vector<Point> Points;
typedef vector<Line> Lines;

Points points;
//Lines lines;

//用户自定义初始化函数---用于初始化点的坐标
void myinit() {
srand(time(NULL));
//随机产生50个点的坐标
points.resize(50);
for(int i = 1; i < 50; i++) {
points[i].x = (rand() * 1.0 / RAND_MAX) * Width - Width / 2;
points[i].y = (rand() * 1.0 / RAND_MAX) * Height - Height/2;
}
}

//用户自定义屏幕绘制和计算函数
void myDraw() {
//绘制点的集合
glColor3f(0.0, 1.0, 0);
glPointSize(5.0);
glBegin(GL_POINTS);
for(int i = 0; i < points.size(); i++)
glVertex3f(points[i].x, points[i].y, 0);
glEnd();

//绘制随机线---模拟可能的计算过程
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINES);
for(int i = 0; i < points.size(); i++)
{
int id1 = (rand() % 1024) / 1024.0 * points.size();
int id2 = (rand() % 1024) / 1024.0 * points.size();
glVertex3f(points[id1].x, points[id1].y, 0);
glVertex3f(points[id2].x, points[id2].y, 0);
}
glEnd();
}

//==========以下代码无需变动======================
void display(void)
{
//清除屏幕内容
glClear(GL_COLOR_BUFFER_BIT);
myDraw();
//刷新结果
glFlush() ;
glutSwapBuffers();
}

void idleDisplay(void)
{
glutPostRedisplay();
}

void initOpenGL(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
}

void reshapeWindow(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
//设置xmin-xmax, ymin-ymax, zmin-zmax
glOrtho(-w/2, w/2, -h/2, h/2, -1.0, 1.0); //-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv)
{
myinit();	//调用用户初始化数据函数
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (Width, Height);
glutInitWindowPosition (0, 0);
glutCreateWindow (argv[0]);
initOpenGL();
//设置显示函数
glutDisplayFunc(display);
//设置窗口大小调整时的函数
glutReshapeFunc(reshapeWindow);
//闲暇时的后台处理程序---可用于修改数据
glutIdleFunc(idleDisplay);

//主循环
glutMainLoop();
return 0;
}