使用鼠标在OpenGL GLUT中绘制多边形

时间:2017-11-05 15:26:24

标签: c++ opengl graphics glut

我想在openGL Glut中使用鼠标交互绘制多边形,每个要做的左键将是一个顶点,并且将在每个顶点之间绘制一条线。当单击鼠标右键时,多边形将关闭从最后一个顶点到第一个顶点绘制一条线。我想出了这个,但它似乎没有用。

        Scanner scanner = new Scanner(fin);

我也试图找出如何添加一个功能,当我从菜单中选择时,我可以从创建这个多边形到以一种我可以选择顶点的方式进行编辑,将其移动到周围,并且形状发生变化相应

1 个答案:

答案 0 :(得分:4)

您必须将鼠标事件和绘图功能分开。

在鼠标事件中,您应该只收集输入。我建议使用std::vector。如果按下鼠标左键,以下函数会向3 // there are 3 snakes 1 2 1 N // head of a snake (1, 2)/its encoding (1)/its move direction (N) 5 7 2 E // second snake 3 4 3 S // third snake 9 9 // dimensions of the map 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 3 3 3 3 0 0 1 1 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 2 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 // the map with the 3 snakes The purpose is to move the snakes in the indicated direction as long as they do not collide. As you can see, if snake 1 goes up and 2 goes to right, they will collide in 5 steps I used #pragma omp parallel for to count from 0 to the maximum number of movements, which was 20 000. If I decide to not paralelise the counting, but to paralelise the iteration through the snakes (i have an array of them), the problem does not appear. 添加一个点。如果按下右按钮,则多边形标记为关闭。如果再次按下左按钮,则清除多边形并重新开始该过程。

std::vector

在鼠标移动事件功能中,您可以跟踪当前鼠标位置:

#include <vector>
#include <array>

int vp_width = 640;
int vp_height = 480;

std::array<int, 2> currentPt;
std::vector<std::array<int, 2>> pts;
bool closed = false;

void draw_polygon(int button, int state, int x, int y)
{
    currentPt = std::array<int, 2>{x, vp_height-y}; 

    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        if ( closed )
            pts.clear(); // restart if last action was close
        closed = false;
        pts.push_back( currentPt );
    }
    if ( button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN )
        closed = true;
}

在主循环中,您可以连续绘制当前点之间的线条。 fllowing功能在点列表之间绘制线条。如果设置了“cloesd”标志,则关闭多边形。否则,将绘制从列表中最后一个点到当前鼠标位置的一条线。

void mouse_move(int x, int y)
{
    currentPt = std::array<int, 2>{x, vp_height-y};
    glutPostRedisplay();
}

void display(void)
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

    if ( !pts.empty() )
    {
        glBegin(GL_LINE_STRIP);
        for ( auto &pt : pts )
            glVertex2f( (float)pt[0], (float)pt[1] );
        auto &endPt = closed ? pts.front() : currentPt;
        glVertex2f( (float)endPt[0], (float)endPt[1] );
        glEnd();
    }

    //glFlush();
    glutSwapBuffers();
}


预览:

preview