2015-11-06 125 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(); 
}