用OpenGL绘制Sierpinski的麻烦

Trouble drawing Sierpinski with OpenGL

本文关键字:麻烦 Sierpinski 绘制 OpenGL      更新时间:2023-10-16

我正在尝试使用绘制点模式并生成垫圈的函数来生成sierpinski垫圈。

但是,当我编译并运行程序时,它除了黑屏外什么都没有显示。是什么原因引起了问题?

这是我的代码:

#include <Windows.h>
#include <gl/GL.h>
#include <glut.h>
void myInit(void) {
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glColor3f(0.0f, 0.0f, 0.0f);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
class GLintPoint {
    public:
        GLint x, y;
    };
    int random(int m) {
        return rand() % m;
    }
    void drawDot(GLint x, GLint y)
    {
        glBegin(GL_POINTS);
        glVertex2i(x, y);
        glEnd();
    }
    void Sierpinski(void) {
    GLintPoint T[3] = {{ 10, 10 }, {300, 30}, {200, 300}};
    int index = random(3);
    GLintPoint point = T[index];
    for (int i = 0; i < 1000; i++)
    {
        index = random(3);
        point.x = (point.x + T[index].x) / 2;
        point.y = (point.y + T[index].y) / 2;
        drawDot(point.x, point.y);
    }
    glFlush();
}
void main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(640, 480);
    glutInitWindowPosition(100, 150);
    glutCreateWindow("Sierpinski Gasket");
    glutDisplayFunc(drawDot);
    myInit();
    glutMainLoop();
}

如果要在白色背景上绘制黑点,则必须清除glClear背景:

glClear( GL_COLOR_BUFFER_BIT );

注意,glClearColor设置用于清除视图端口的颜色,但没有清除任何内容。

您的代码应该以某种方式看起来:

void drawDot(GLint x, GLint y)
{
    glVertex2i(x, y);
}
void Sierpinski(void) {
    GLintPoint T[3] = {{ 10, 10 }, {300, 30}, {200, 300}};
    int index = random(3);
    GLintPoint point = T[index];
    glClearColor(1.0, 1.0, 1.0, 1.0); // set up white clear color
    glClear( GL_COLOR_BUFFER_BIT );   // clear the back ground (white)
    glMatrixMode( GL_MODELVIEW );
    glPushMatrix();                   // setup model matrix
    glScalef( 1.5f, 1.5f, 1.0f );     // scale the point distribution
    glColor3f( 0.0f, 0.0f, 0.0f );    // set black draw color
    glPointSize( 5.0f );              // set the size of the points 
    glBegin(GL_POINTS);
    for (int i = 0; i < 1000; i++)
    {
        index = random(3);
        point.x = (point.x + T[index].x) / 2;
        point.y = (point.y + T[index].y) / 2;
        drawDot(point.x, point.y);
    }
    glEnd();
    glPopMatrix();                    // reset model matrix
    glFlush();
}