用GLUT画一条线

时间:2015-10-12 04:32:26

标签: c opengl

我有下一个使用OPENGL GLUT的代码,此代码在光标位置绘制一条线。单击鼠标右键后,它会捕获线条的坐标x0y0,然后当鼠标移动到另一个像素,同时按下按钮coordinates(x1,y1)更改,最后释放按钮时,绘制线条。

#include<windows.h>
#include <gl/glut.h>

float a[90000];
int x0=0,y0=0,xf=0,yf=0;
int print=0;

void init(void)
{
   glClearColor(1.0, 1.0, 1.0, 0.0);
   glMatrixMode(GL_PROJECTION);
   gluOrtho2D(0.0, 300.0, 0.0,300.0);
}

void putpixel(int x,int y)
{
    glColor3f(0.0, 0.9,0.7);
    glBegin(GL_POINTS);
    glVertex2i(x,y);
    glEnd();
}
void Bresenham(int x0, int y0, int x1, int y1)
{
    int dx,dy,p,x,y,px = 1,py = 1,twoDy_Dx,twoDy,i;
    glColor3f(0.0,0.0,1.0);
    dx = x1-x0;
    dy = y1-y0;

    if(dx < 0)
       dx = dx*-1;
    if(dy < 0)
       dy = dy*-1;
    if(x1 < x0)
       px = -1;
    if(y1 < y0)
       py = -1;

    x = x0;
    y = y0;
    if( dx > dy )
    {
        putpixel(x,y);
        p = 2 * dy - dx;
        twoDy_Dx = 2 * ( dy - dx );
        twoDy = 2 * dy;
        for( i = 0; i < dx; i++ )
        {
             if( p >= 0 )
             {
                  y += py;
                  p += twoDy_Dx;
             }
             else
                p += twoDy;

             x += px;
             putpixel(x,y);
        }
   }
   else
   {
       putpixel(x,y);
       p = 2*dx - dy;
       twoDy_Dx = 2 * ( dx - dy );
       twoDy = 2*dx;

       for( i = 0; i < dy; i++ )
       {
           if( p >= 0 )
           {
               x += px;
               p += twoDy_Dx;
           }
           else
            p += twoDy;

           y += py;
           putpixel(x,y);
       }
   }
   glFlush();
}

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    if(print==1)
       glDrawPixels(300,300,GL_RGB,GL_UNSIGNED_BYTE,a);
    Bresenham(x0,y0,xf,yf);
    glutSwapBuffers();
    glFlush();
}

void onMotion(int x,int y)
{
    xf=x;
    yf=300-y;
    glutPostRedisplay();
}

void onMouse(int button, int e, int x, int y)
{
    if((button == GLUT_LEFT_BUTTON) && (e == GLUT_DOWN))
    {
        x0 = x;
        y0 = abs(300-y);
        print = 1;
    }
    if( (button == GLUT_RIGHT_BUTTON) && (e==GLUT_DOWN))
    {
        print=0;
    }
    if ( (button == GLUT_LEFT_BUTTON || button == GLUT_RIGHT_BUTTON) && (e == GLUT_UP) )
    {
        print=0;
    }
}

void onPassive(int x,int y)
{
    x0=-1;y0=-1;xf=-1;yf=-1;
    glReadPixels( 0.0, 0.0,300.0,300.0,GL_RGB,GL_UNSIGNED_BYTE,a);
}

int main(int argc, char** argv)
{
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(300, 300);
    glutCreateWindow("Line");
    init();
    glutDisplayFunc(display);
    glutMotionFunc(onMotion);
    glutMouseFunc(onMouse);
    glutPassiveMotionFunc(onPassive);
    glutMainLoop();
}

我遇到的问题是,当按下按钮并且最终坐标发生变化时,该线应绘制为尖线:---------  但是当它到达最终坐标时,该线应该如下绘制:_________。我怎么能这样做?

0 个答案:

没有答案