以下是完整的例子。在第四版 《计算机图形学 with openGL》第四章的例子中,竟然只调用了circleMidpoint(scrPt &c, GLint r) ,没有实现,我认为是系统方法,怎么找都找不到。openGL 官方文档也没找到,这不会是自定义的吧。我在同类文章中发现 有人写了 circleMidpoint(scrPt &c, GLint r) 和里面嵌套的void putpixel(GLint x0, GLint y0, GLint x, GLint y),竟然跑起来了。
为啥没有人提到这个事情,是本道长太菜了?还是这事太简单了,不值一提?
#include "stdafx.h"
#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
const GLdouble twoPi = 6.283185;
class scrPt {
public:
GLint x, y;
};
GLsizei winWidth = 400, winHeight = 300; // Initial display window size.
void init(void)
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, 200.0, 0.0, 150.0);
}
//书上的代码里没有,自己后补的。2-1
void putpixel(GLint x0, GLint y0, GLint x, GLint y)
{
glBegin(GL_POINTS);
glVertex2f(x0 + x, y0 + y);
glVertex2f(x0 + x, y0 - y);
glVertex2f(x0 - x, y0 + y);
glVertex2f(x0 - x, y0 - y);
glVertex2f(x0 + y, y0 + x);
glVertex2f(x0 + y, y0 - x);
glVertex2f(x0 - y, y0 + x);
glVertex2f(x0 - y, y0 - x);
glEnd();
}
// Midpoint routines for displaying a circle.
//书上的代码里没有,自己后补的。2-2
void circleMidpoint(scrPt &c, GLint r) //中点画圆函数
{
int x, y, p;
x = 0; y = r; p = 1 - r;
while (x <= y) {
putpixel(c.x, c.y, x, y);
if (p < 0) {
p += 2 * x + 1;
}
else {
p += 2 * (x - y) + 1;
y--;
}
x++;
}
}
void pieChart(void)
{
scrPt circCtr, piePt;
GLint radius = winWidth / 4; // Circle radius.
GLdouble sliceAngle, previousSliceAngle = 0.0;
GLint k, nSlices = 12; // Number of slices.
GLfloat dataValues[12] = { 10.0, 7.0, 13.0, 5.0, 13.0, 14.0, 3.0, 16.0, 5.0, 3.0, 17.0, 8.0 };
GLfloat dataSum = 0.0;
circCtr.x = winWidth / 2; // Circle center position.
circCtr.y = winHeight / 2;
circleMidpoint(circCtr, radius); // Call a midpoint circle-plot routine.
for (k = 0; k < nSlices; k++)
dataSum += dataValues[k];
for (k = 0; k < nSlices; k++) {
sliceAngle = twoPi * dataValues[k] / dataSum + previousSliceAngle;
piePt.x = circCtr.x + radius * cos(sliceAngle);
piePt.y = circCtr.y + radius * sin(sliceAngle);
glBegin(GL_LINES);
glVertex2i(circCtr.x, circCtr.y);
glVertex2i(piePt.x, piePt.y);
glEnd();
previousSliceAngle = sliceAngle;
}
}
void displayFcn(void)
{
glClear(GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f(0.0, 0.0, 1.0); // Set circle color to blue.
pieChart();
glFlush();
}
void winReshpeFcn(GLint newWidth, GLint newHeight)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, GLdouble(newWidth), 0.0, GLdouble(newHeight));
glClear(GL_COLOR_BUFFER_BIT);
/* Reset display-window size parameters. */
winWidth = newWidth;
winHeight = newHeight;
}
void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(winWidth,winHeight);
glutCreateWindow("Pie Chart");
init();
glutDisplayFunc(displayFcn);
glutReshapeFunc(winReshpeFcn);
glutMainLoop();
}