OpenGL:矩阵堆栈的功能

时间:2015-02-08 08:37:29

标签: opengl graphics

我有一些代码可以执行各种转换,并在调用glPushMatrix()和glPopMatrix()之间设置颜色,基本上是这样的:

glLoadIdentity();
glPushMatrix();

glPushMatrix();
// C++ code to perform transformations
// C++ code to set colour
// C++ code to draw polygon
glPopMatrix();

// Other similar code "blocks" between calls to glPushMatrix() and glPopMatrix()

glPushMatrix();
// C++ code to perform transformations
// C++ code to set colour
// C++ code to draw polygon
glPopMatrix();

我的理解是,一个单位矩阵在开始时被压入堆栈,随后被每个连续的"块"复制,转换,渲染和弹出。代码和弹出消除了以前转换的所有效果。

但是,如果我注释掉在不是最后一个块的任何块中设置颜色的代码,那么该块现在继承了在最后一个块中设置的颜色

如果将颜色应用于整个堆栈并因此对glPopMatrix()的调用仍然存在,这是有意义的。但是,在最后一个块中创建的多边形似乎是最后渲染的,因为它位于所有其他多边形的顶部 - 因此我看不到最终块中设置的颜色如何应用于已经存在的多边形已被渲染。

问题:

1)对glPopMatrix()的调用有什么属性/效果?

2)上述代码中的操作顺序是什么?这些块是以相反的顺序执行的,每个块中的代码是以相反的顺序执行,还是两者都执行?

1 个答案:

答案 0 :(得分:2)

正如其名称所暗示的那样,glPushMatrix() and glPopMatrix()仅保存/恢复矩阵状态。不存储颜色值 - 您需要改为使用glPushAttrib()

OpenGL指令按照您期望的顺序处理:从头到尾。如果删除第一个多边形的glColor3f()内容,您通常会看到使用 final 多边形的颜色值,因为最后定义的颜色值(即为最终多边形设置的值)仍然是"活动"重新绘制屏幕时的颜色值

顺便说一句,您不需要在开始时将矩阵状态推送两次:

glLoadIdentity();
glPushMatrix();

glPushMatrix();

glLoadIdentity()函数设置当前矩阵状态 - 之后不需要将其推入堆栈。您的代码可能如下所示:

glLoadIdentity();  // Set the matrix to an "identity" state.

glPushMatrix();  // Save the identity matrix.
transformTheMatrix();
drawSomething();
glPopMatrix();  // Restore the identity matrix.

glPushMatrix();  // Save the identity matrix.
transformTheMatrix();
drawSomething();
glPopMatrix();  // Restore the identity matrix.

......甚至是这个:

glLoadIdentity();
transformTheMatrix();
drawSomething();

glLoadIdentity();
transformTheMatrix();
drawSomething();