【问题标题】:OpenGL: Bresenham's Line Drawing Algorithm ImplementationOpenGL:Bresenham 的画线算法实现
【发布时间】:2018-03-14 05:26:39
【问题描述】:

我一直在尝试使用以下代码使用 Bresenham 算法生成一条线(是的,我知道存在内置函数,但这是我被要求实现的)。 但由于某种原因,我无法看到窗口上的线条。我只是得到一个空窗口。

我最初尝试使用 SetPixel() 绘制点,但除了 X 和 Y 坐标之外,我还缺少 2 个参数(HDC 和 COLORREF)。我不知道其他 2 个参数是做什么的,所以我不得不尝试其他方法。

所以我使用了在 StackOverflow 上找到的解决方案来生成该点。虽然我没有收到任何编译错误或警告,但代码似乎不起作用。你试试看问题如何:

#include<iostream>
#include<GL/glut.h>
#include<stdlib.h>
#include<math.h>
using namespace std;

int x00; 
int y00;
int xEnd;
int yEnd;

void init(){
    glClearColor(1,0,0,0);
    glMatrixMode( GL_PROJECTION );
    gluOrtho2D(0,500,0,500);
}

void bres()
{     
    int dx = fabs(xEnd - x00), dy = fabs(yEnd - y00);
    int p = 2*dy-dx;
    int x, y;

    if(x00>xEnd){
        x=xEnd;
        y=yEnd;
        xEnd=x00;
    }
    else{
        x=x00;
        y=y00;
    }
    //Stack Overflow Solution to generate a point:
    glBegin(GL_POINTS);
        glColor3f(0,0,0);
        glVertex2i(x,y);
    glEnd();

    while(x<xEnd){
        x++;
        if(p<0){
            p = p + 2*dy;
        }
        else{
            y++;
            p= p + 2*dy - 2*dx;
       }
        glBegin(GL_POINTS);
            glColor3f(0,0,0);
            glVertex2i(x,y);
        glEnd();

    }

}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    bres();
    glFlush();

}

int main(int argc, char* argv[])
{
    cout<<"Enter the co ordinates for 2 points: ";
    cin>>x00>>y00>>xEnd>>yEnd;

    glutInit(&argc, argv);
    glutInitWindowSize(600,600);
    glutInitWindowPosition(10,10);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Bresenham's Algo");

    init();
    glutDisplayFunc(display);
    glutMainLoop();

    return 0;
}

【问题讨论】:

    标签: c++ opengl glut


    【解决方案1】:

    由于您使用的是双缓冲窗口

    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    

    您必须拨打glutSwapBuffers 而不是glFlush

    如果您使用单个缓冲窗口

    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
    

    那么glFlush 就可以了。

    以某种方式更改您的代码:

    void display()
    {
        glClear(GL_COLOR_BUFFER_BIT);
        bres();
        //glFlush();
        glutSwapBuffers();
    } 
    

    【讨论】:

    • Further I recommend to redisplayed the window continuously glutPostRedisplay – 如果内容没有改变,为什么?除非播放动画,否则只会浪费 GPU 周期和功耗。
    猜你喜欢
    • 2015-06-10
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2011-05-15
    相关资源
    最近更新 更多