2015-11-06 28 views
0

我想在我的OpenGL和C++程序中用我的鼠标绘制多个线段。现在我可以绘制一个,一旦我开始绘制另一个,前一个消失。在OpenGL中绘制多行与鼠标

下面是我的与鼠标绘图相关的代码。有关如何绘制多条线的任何建议?

LineSegment seg; 

void mouse(int button, int state, int x, int y) { 

    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {     // if left button is clicked, that is the start point 
     seg.x1 = seg.x2 = x; 
     seg.y1 = seg.y2 = y; 
    } 

    if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {     // once they lift the mouse, thats the finish point 
     seg.x2 = x; 
     seg.y2 = y; 
    } 

} 

void motion(int x, int y) { 
    seg.x2 = x; 
    seg.y2 = y; 

    glutPostRedisplay();             // refresh the screen showing the motion of the line 
} 

void display(void) { 
    glClear(GL_COLOR_BUFFER_BIT);           // clear the screen 

    glBegin(GL_LINES);               // draw lines 
    glVertex2f(seg.x1, seg.y1); 
    glVertex2f(seg.x2, seg.y2); 

    glEnd(); 

    glutSwapBuffers(); 
} 

回答

2
void display(void) { 
    glClear(GL_COLOR_BUFFER_BIT);           // clear the screen 

    glBegin(GL_LINES);               // draw lines 
    glVertex2f(seg.x1, seg.y1); 
    glVertex2f(seg.x2, seg.y2); 

    glEnd(); 

    glutSwapBuffers(); 
} 

你需要一个数据结构来保存先前的线段,并添加到它,只要你用鼠标点击。然后drawloop需要遍历该数据结构并绘制每个保存的线段。

std::vector<LineSegment> segmentvector; 
//Each time you release the mouse button, add the current line segment to this vector 
/*...*/ 

glClear(GL_COLOR_BUFFER_BIT); 
glBegin(GL_LINES); 
for(const LineSegment & seg : segmentvector) { 
    glVertex2f(seg.x1, seg.y1); 
    glVertex2f(seg.x2, seg.y2); 
} 

glVertex2f(currseg.x1, currseg.y1); 
glVertex2f(currseg.x2, currseg.y2); 
glEnd(); 

我也强烈建议,你不学习的OpenGL时使用固定功能,管道功能。 There are lots of tutorials online for learning modern OpenGL.

+1

我第二是**强烈劝喻**;那个OpenGL石器时代的军团显然被弃用了。 –

+1

是的。我习惯于每个从Java循环,所以这样的怪癖对我来说还不是很明显。 – Xirema

+0

当你开始学习现代版本时,学习旧的openGL可以派上用场。 – OpenGLmaster1992

1

您需要设置一些逻辑来保存已绘制线条的状态。目前,您从未开始绘制另一个行,您只需重置当前行的开始位置。

这里是你要寻找一个可能的解决方案:

std::vector<LineSegment> segs; 
LineSegment currentSeg; 

void mouse(int button, int state, int x, int y) { 

    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {     
     LineSegment newSeg; // Make a new segment 
     newSeg.x1 = newSeg.x2 = x; 
     newSeg.y1 = newSeg.y2 = y; 
     segs.insert(newSeg); // Insert segment into segment vector 
     currentSeg = newSeg; 
    } 

    if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) { 
     currentSeg.x2 = x; 
     currentSeg.y2 = y; 
    } 
} 

void motion(int x, int y) { 
    currentSeg.x2 = x; 
    currentSeg.y2 = y; 

    glutPostRedisplay();       
} 

void display(void) { 
    glClear(GL_COLOR_BUFFER_BIT); 

    glBegin(GL_LINES);               

    // Iterate through segments in your vector and draw each 
    for(const auto& seg : segs) { 
     glVertex2f(seg.x1, seg.y1); 
     glVertex2f(seg.x2, seg.y2); 
    } 

    glEnd(); 

    glutSwapBuffers(); 
}