c - OpenGL:按下显示窗口时形状改变位置

标签 c opengl glut

我在运行我的程序时遇到了问题,当我按下我的 3D 形状所在的窗口时,它会改变位置。当我第二次按下它时,形状就会消失。

这是我的程序的样子:

GLsizei winWidth = 500, winHeight = 500;
int userLongitude, userLatitude;
GLenum drawStyle;
bool isSolid = false;

void keyboardFunc(unsigned char, int, int);

void init(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
}

void keyboardFunc(unsigned char Key, int x, int y) {
switch (Key) {
case 's':
    //drawStyle = GLU_FILL;
    isSolid = true;

    break;
case 'w':
    //drawStyle = GLU_LINE;
    isSolid = false;
    break;
}
//cout << Key << endl;
//glutPostRedisplay();
}
void wireQuadSurfs(void)
{
glClear(GL_COLOR_BUFFER_BIT);

glColor3f(0.0, 0.0, 1.0);

gluLookAt(1.0, 1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);


GLUquadricObj *cylinder;
glPushMatrix();
glTranslatef(0.0, 1.2, 0.8);
glRotatef(45, 1, 0, 0);
cylinder = gluNewQuadric();


//cylinder, baseRad, topRad, height, slices, stacks
//gluCylinder(cylinder, 0.6, 0.6, 1.5, userLongitude, userLatitude);
//gluQuadricDrawStyle(cylinder, GLU_LINE);
//gluQuadricDrawStyle(cylinder, drawStyle);

if (isSolid) {
    gluQuadricDrawStyle(cylinder, GLU_FILL);
}
else {
    gluQuadricDrawStyle(cylinder, GLU_LINE);
}
gluCylinder(cylinder, 0.6, 0.6, 1.5, userLongitude, userLatitude);
glPopMatrix();
glFlush();
}

void winReshapeFcn(GLint newWidth, GLint newHeight)
{
glViewport(0, 0, newWidth, newHeight);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-2.0, 2.0, -2.0, 2.0, 0.0, 5.0);

glMatrixMode(GL_MODELVIEW);

glClear(GL_COLOR_BUFFER_BIT);
}

void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(winWidth, winHeight);
glutCreateWindow("CSC 313 HW 8 Part 2");

cout << "Enter number of longitude: ";
cin >> userLongitude;
cout << "Enter number of latitude: ";
cin >> userLatitude;
cout << "Switch between solid and wireframe views with 's' and 'w' keys" << endl;

glutKeyboardFunc(keyboardFunc);
init();
glutDisplayFunc(wireQuadSurfs);
glutReshapeFunc(winReshapeFcn);
glutMainLoop();
}

我试图用我的程序做的是在我的形状的实体和线框之间切换。但是当我点击显示窗口时,它会改变位置然后从 View 中消失。我不确定是不是因为我的键盘功能或其他原因。抱歉缺少详细信息,谢谢您告诉我!

最佳答案

在设置正交投影之前,您必须使用单位矩阵初始化投影矩阵堆栈(参见 glLoadIdentity):

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-2.0, 2.0, -2.0, 2.0, 0.0, 5.0);

请注意,glOrtho将当前矩阵乘以正交投影矩阵。
这意味着它不会分配一个新的 4*4 矩阵,它将当前矩阵乘以新矩阵并将结果分配给矩阵堆栈。每次调用 winReshapeFcn 时,投影矩阵堆栈上的矩阵都会在您问题的代码中逐渐变化。

如果调用 glLoadIdentity,则矩阵堆栈由单位矩阵初始化。 glOrtho 的调用将单位矩阵乘以新的正交投影。结果是正交投影本身。

关于c - OpenGL:按下显示窗口时形状改变位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479951/

相关文章:

c - 在 malloc 实体内存块中使用标准数组索引

java - JOGL 程序纹理在缩放时会出现 Blob

c++ - glutswapbuffers 实际上做了什么?

opengl - 了解 OpenGL 中的光照

c - 如何设计一个可扩展到恰好 n 个元素的哈希函数?

android - 如何使用头文件正确设置动态库加载?

c - 二维数组 += 1 给出负数

c++ - 在调用 rotatef c++ 后获取对象的值

c++ - 使 Sprite 居中还是移动相机? C++/Opengl

c++ - 将 glutTimerFunc 与 glutMouseFunc 一起使用