c++ - 无法使用 OpenGL 绘制 Sierpinski

标签 c++ opengl glut

我正在尝试使用绘制点图案并将生成垫圈的函数生成 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设置用于清除视口(viewport)的颜色,但本身不清除任何内容。

您的代码应该看起来像这样:

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();
}

关于c++ - 无法使用 OpenGL 绘制 Sierpinski,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47833397/

相关文章:

c++ - 为什么 C++ 函数的命名标准不存在?

c++ - 使用 this = new Foo()? 从内部将一个对象的实例设置为另一个对象的实例?

c++ - 创建巨大矩阵时的问题

c++ - 为什么我不能插入指向多重集的 const 指针?

c++ - glutBitmapCharacter() 文本没有出现在屏幕上?

c++ - 带键盘监听器的游戏循环

c++ - GL_QUADS 绘制凹五边形而不是矩形

c++ - Opengl sws_scale 不工作(段错误)

c++ - 将 1 个参数(指针)传递给 glutDisplayFunc?

c - Monodevelop 和过剩问题