基于Opengl的实时动画,为可视化科学计算过程提供了有利的工具。
然而,对于初学者来说,相关知识的学习仍需经历一个过程。
将Opengl的初始化等进行适当封装,建立了Opengl的动画框架,用户可以直接应用C语言的知识或Matlab知识,定义框架中相应的函数,即可实现实时动画程序开发,为科学计算和可视化计算提供了便利。
下面给出了Ubuntu14.04下,基于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);
glShadeModel (GL_FLAT);
}
void reshapeWindow(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//设置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);
glLoadIdentity();
}
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;
}
效果图如下: