c++ - 通过鼠标点击绘制多边形

标签 c++ opengl

我试图在屏幕上绘制一个多边形,其顶点由鼠标点击确定。 左键单击向多边形添加一个顶点,右键单击将最后一个顶点添加到多边形,将它连接到第一个并创建形状。

我目前有两个 vector ,一个用于 x 坐标,一个用于 y 坐标,我正在遍历 vector 创建一个线循环。 vector 中的 -1 确定多边形的终点和新多边形的起点。这是一个随后在显示函数中调用的函数。

最终我必须扫描转换这些多边形,然后使用 Sutherland Hodgman 算法将它们裁剪到用户定义的窗口中,但我什至无法显示多边形。

glBegin(GL_LINE_LOOP);
for (int i = 0; i < xCo.size(); i++)
{
    if (xCo[i + 1] != -1)
    {
        glVertex2f(xCo[i], yCo[i]);
        glVertex2f(xCo[i + 1], yCo[i + 1]);
    }
    else
    {
        glVertex2f(xCo[i + 1], yCo[i + 1]);
        glVertex2f(xCo[0], yCo[0]);
    }
}
glEnd();
glFlush();
xCo.clear();
yCo.clear();

最佳答案

使用structs而不是单独的数组和 float 比较:

#include <glm/glm.hpp>

typedef vector< glm::vec2 > Poly;
void drawPoly( const Poly& poly )
{
    if( poly.size() == 1 )
        glBegin( GL_POINTS );
    else
        glBegin( GL_LINE_STRIP );

    for( const auto& pt : poly )
    {
        glVertex2f( pt.x, pt.y );
    }

    glEnd();
}

在上下文中:

#include <GL/glut.h>
#include <glm/glm.hpp>
#include <vector>

typedef std::vector< glm::vec2 > Poly;
void drawPoly( const Poly& poly )
{
    if( poly.size() == 1 )
        glBegin( GL_POINTS );
    else
        glBegin( GL_LINE_STRIP );

    for( const auto& pt : poly )
    {
        glVertex2f( pt.x, pt.y );
    }

    glEnd();
}

typedef std::vector< Poly > Polys;
Polys polys( 1 );
void mouse( int button, int state, int x, int y )
{
    if( GLUT_UP == state && GLUT_LEFT_BUTTON == button )
    {
        polys.back().push_back( glm::vec2( x, y ) );
        glutPostRedisplay();
    }
    if( GLUT_UP == state && GLUT_RIGHT_BUTTON == button )
    {
        polys.back().push_back( polys.back().front() );
        polys.push_back( Poly() );
        glutPostRedisplay();
    }
}

void display()
{
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );
    glOrtho( 0, w, h, 0, -1, 1 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glColor3ub( 255, 255, 255 );
    for( const auto& poly : polys )
    {
        drawPoly( poly );
    }

    glutSwapBuffers();
}

int main( int argc, char **argv )
{
    glutInitWindowSize( 640, 480 );
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
    glutCreateWindow( "GLUT" );
    glutDisplayFunc( display );
    glutMouseFunc( mouse );
    glutMainLoop();
    return 0;
}

关于c++ - 通过鼠标点击绘制多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21787600/

相关文章:

c++ - 我不明白为什么我的 .find 函数不起作用

c++ - OpenCV OpenGLDrawCallback 没有被调用

c++ - OpenGL Vertex Array Sphere C 的问题

c++ - 如何在 win32 可执行文件中嵌入任何 *.jpg 图像并在运行时使用它

c++ - 构建 Windows dll 的建议

c++ - gcc的模棱两可的模板实例化错误

c++ - 有没有一种方法可以强制gradle一次只为一个项目编译c++代码(并且只有它)?

c++ - 计算点云部分体积的算法

c - 带时序的流动动画 (OpenGL)

opengl - 从右前方确定俯仰、偏航和滚转