OpenGL - 如何使用弹出菜单绘制多个不同的二维形状?

OpenGL - How to draw multiple different 2D shapes using pop-up menu?

我正在尝试制作一个简单的 openGL 应用程序,它使用鼠标点击创建形状。所需的形状是 select 使用鼠标右键打开的弹出菜单编辑的。目前我有矩形工作,还有一个简单的使用点的类似绘画的功能。一旦重绘它们就会消失,但这是我以后会担心的问题。

目前我也在尝试将 Line 功能实现为菜单选项。我有下面的代码,但是当我 select 弹出菜单中的线选项并单击两个点时,它似乎没有按预期绘制线。谁能指出我哪里出错了?

GLfloat x1, x2, y1, y2;
GLfloat x_Src, y_Src, x_Dest, y_Dest;

//used to change colour (To be implemented)
static int colour;

void menu(int);

void display(void)
{
glClearColor(0.0, 2.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);

glPointSize(3.0);
glColor3f(1.0, 0.0, 0.0);

//Rectangle vertices
glBegin(GL_POLYGON);
glVertex2f(x1, y1);
glVertex2f(x1, y2);
glVertex2f(x2, y2);
glVertex2f(x2, y1);
glEnd();

//Line vertices
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINE);
glVertex2f(x_Src, y_Src);
glVertex2f(x_Dest, y_Dest);
glEnd();

glFlush();
return;
}

void MyRect(GLint button, GLint state, GLint x, GLint y)
{
static int first = 1;

if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
{
    if (first)
    {
        //first point in terms of window size
        x1 = (x - 250.0) / 250.0;
        y1 = -(y - 250) / 250.0;;
    }
    else
    {
        //second point in terms of window size
        x2 = (x - 250.0) / 250.0;
        y2 = -(y - 250) / 250.0;
        glutPostRedisplay();
    }
    first = !first;
}

return;
}


void MyLine(GLint button, GLint state, GLint x, GLint y)
{
static int first = 1;

if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
{
    if (first)
    {
        x_Src = (x - 250.0) / 250.0;
        y_Src = -(y - 250) / 250.0;

    }
    else
    {
        x_Dest = (x - 250.0) / 250.0;
        y_Dest = -(y - 250) / 250.0;
        glutPostRedisplay();
    }
    first = !first;
}
return;
}

//allows drawing of un-fixed line using mouse
void MyPaint(GLint x, GLint y)
{
    glColor3f(0.0, 0.0, 0.0);
    glPointSize(3.0);
    glBegin(GL_POINTS);
    glVertex2f((x - 250.0) / 250.0, -(y - 250.0) / 250.0);
    glEnd();

    glFlush();
    return;
}

void MainMenu(int item)
{
//Remove motion function if exists and go to rectangle function
//prevents two functions running at once
if (item == 1)
{
    glutMotionFunc(NULL);
    glutMouseFunc(MyRect);
}
else if (item == 2)
{
    glutMotionFunc(NULL);
    glutMouseFunc(MyLine);
}
else if (item == 5)
{
    glutMouseFunc(NULL);
    glutMotionFunc(MyPaint);
}
glutPostRedisplay();
return;
}


int main(int argc, char **argv)
{

glutInit(&argc, argv);
glutInitWindowSize(500, 500);
glutInitWindowPosition(500, 200);
glutCreateWindow("Draw Shapes");
glutDisplayFunc(display);

glutCreateMenu(MainMenu);
glutAddMenuEntry("Rectangle", 1);
glutAddMenuEntry("Line", 2);
glutAddMenuEntry("Circle", 3);
glutAddMenuEntry("Triangle", 4);
glutAddMenuEntry("Paintbrush", 5);
glutAddMenuEntry("Background colour", 6);
glutAddMenuEntry("Clear screen", 7);
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutMainLoop();
}

您需要使用 glBegin(GL_LINES) 而不是 glBegin(GL_LINE)。

GL_LINE 是无关函数 glPolygonMode 的参数。