2012-02-13 20 views
-1

我正在尝试以左右点击的形式将用户输入绘制到屏幕的多边形。每一次左键单击都会捕获为(x,y)坐标并保存到数组中。用户按下右键后,鼠标功能应完成多边形(将最后一个点连接到原始点)并将其显示在屏幕上。我已经在显示函数中使用我的代码验证了使用顶点数组的硬编码值,所以我认为问题在于如何处理终止条件(即“GLUT_RIGHT_CLICK”)
您能在此处看到错误吗?当我测试功能时,它右键点击崩溃。OpenGL顶点数组,从用户输入绘图

void mouseMove(int click, int state, int x, int y) 
{ 
    clearFramebuffer(); 
    static int i = 0; 
    drawit(); 
    glEnableClientState(GL_VERTEX_ARRAY); 
    while(click!=GLUT_RIGHT_BUTTON){ 
     if(click==GLUT_LEFT_BUTTON && state == GLUT_DOWN){ 

      vertices[i]=x; 
      vertices[i+1]=y; 
      //{10, 10, 10, 50, 50, 50, 50, 10}; 
      //printf("Coords: (%d,%d)\n",vertices[i],vertices[i+1]); 
      i++;i++; 
     } 
    } 
    //drawit(); 
    glVertexPointer(2, GL_INT, 0, vertices); 
    glDrawArrays(GL_POLYGON, 0, 10); 
    glDisableClientState(GL_VERTEX_ARRAY); 
    glutPostRedisplay(); 
} 

的mouseMove被称为主像这样:

glutMouseFunc(mouseMove); 

这太不涉及顶点数组任何其他解决方案是不允许我的功课的一部分。

回答

1

每次按下鼠标时都会调用此函数,因此不需要在那里存在循环。这里有一个建议是你如何解决你的问题。这不是最好的,但会起作用。请注意,您可以借鉴,只有凸多边形这样,否则你需要例如镶嵌:

std::vector<std::pair<int,int> > points; 
void UnprojectPoint(std::pair<int,int> point, 
    std::pair<double,double>& unprojected) { 
    double modelview[16], projection[16]; 
    int viewport[4]; 
    double objz; 

    //get the modelview matrix   
    glGetDoublev(GL_MODELVIEW_MATRIX, modelview); 
    //get the projection matrix 
    glGetDoublev(GL_PROJECTION_MATRIX, projection); 
    //get the viewport   
    glGetIntegerv(GL_VIEWPORT, viewport); 

    //Unproject the window co-ordinates to 
    //find the world co-ordinates. 
    gluUnProject(x, y, 0, modelview, projection, viewport, 
     &unprojected.first, &&unprojected.second, &objz); 
} 

void MousePressFunc(int button, int state, int x, int y) { 
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { 
    points.push_back(std::make_pair(x, y)); 
    } else if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) { 
    glBegin(GL_POLYGON); 
     for (unsigned index = 0; index < points.size(); ++index) { 
     std::pair<double, double> unprojected; 
     UnprojectPoint(points[index], unporjected); 
     glVertex2f(unprojected.first, unprojected.second); 
     } 
    glEnd(); // GL_POLYGON 
    points.clear(); // Clear the polygon. 
    } 
} 

请注意,你需要unproject点把它从窗口坐标转换为世界坐标。 希望这有助于。