我对使用GLUT还比较新,一直在尝试编译一个程序(我在这里找到的第一个回答),该程序使用鼠标记录点击和拖动的起始和结束点来绘制矩形。
原样复制粘贴后,它可以编译但不会绘制任何东西。即使在设置()函数中更改背景颜色为黑色,它仍然只显示白色屏幕。我阅读了几个来源以验证此程序在其绘制和重塑函数中没有遗漏任何内容,并且所有内容都在那里。
我创建一个窗口,将视口设置为窗口尺寸,然后使用gluOrtho2D函数设置映射(因为窗口和视口是相同的尺寸,所以我将映射设置为窗口尺寸)。鼠标回调记录我的左键单击和释放左键的位置,然后调用glutPostRedisplay()函数以使用新坐标重新绘制窗口。经过一些调试,我发现坐标已适当地记录并保存,并且以像素为单位测量(x和y是介于0和窗口尺寸之间的整数),因此我应该能够使用这些坐标从一个顶点绘制矩形到另一个顶点。但是,就像我说的那样,它只显示白色屏幕。
那么,我绘制矩形的方式有问题吗?我是否错误地映射了窗口?我真的很迷茫,任何反馈都将不胜感激。
编辑2: 我将glutInitDisplayMode从GLUT_SINGLE更改为GLUT_DOUBLE,这解决了整个非交互式白屏问题。现在它可以用鼠标绘制具有翻转y坐标的矩形(我已修复),现在它运行得非常好。非常感谢您的建议。
以下是我的程序(编辑1: 添加注释):
#include <cstdlib>
#include <GL/glut.h>
using namespace std;
GLsizei width, height;
struct Position
{
Position() : x(0), y(0) {}
float x;
float y;
};
Position start; // Records left-click location
Position finish; // Records left-click release location
void display()
{
glClear(GL_COLOR_BUFFER_BIT); // clear window
glColor3ub(rand()%256, rand()%256, rand()%256); // generates random color
glBegin(GL_QUADS);
glVertex2f(start.x,start.y);
glVertex2f(finish.x,start.y);
glVertex2f(finish.x,finish.y);
glVertex2f(start.x,finish.y);
glEnd();
glutSwapBuffers(); // display newly drawn image in window
}
void reshape( int w, int h )
{
glViewport( 0, 0, (GLsizei)w, (GLsizei)h ); // set to size of window
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, (float)w, 0.0, (float)h );
width = w; // records width globally
height = h; // records height globally
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void mouse(int button, int state, int x, int y)
{
switch(button)
{
case GLUT_LEFT_BUTTON:
if(state==GLUT_DOWN)
{
start.x = x; //x1
start.y = y; //y1
}
if(state==GLUT_UP)
{
finish.x = x; //x2
finish.y = y; //y2
}
break;
glutPostRedisplay();
}
}
void motion( int x, int y )
{
finish.x = x;
finish.y = y;
glutPostRedisplay();
}
void setup()
{
glClearColor(0.0, 0.0, 0.0, 1.0); // *should* display black background
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,100);
glutCreateWindow("");
setup();
// initializing callbacks
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutMainLoop();
return 0;
}