目前我正在学习3D渲染理论,使用的是《现代3D图形编程》一书,并且现在卡在了第四章复习中的一个“进一步研究”活动上,具体来说是最后一个活动。
第三个活动已经在这个问题中得到解答,我没有任何问题地理解了它。然而,这个最后一个活动要求我这次只使用矩阵来完成所有操作。
我有一个部分工作的解决方案,但对我来说感觉很麻烦,可能不是正确的方法。
我的第三个问题的解决方案涉及将3D向量E
的x、y和z分量振荡在任意范围内,并产生一个缩放的立方体(从左下角开始增长,根据OpenGL原点)。我想再次使用矩阵来完成这个过程,它看起来像这样:
但是我使用矩阵得到的结果如下(忽略背景颜色的变化):
现在看代码...
矩阵是一个名为theMatrix
的float[16],表示一个4x4矩阵,数据按列主序写入,除以下元素外,所有元素都初始化为零:
float fFrustumScale = 1.0f; float fzNear = 1.0f; float fzFar = 3.0f;
theMatrix[0] = fFrustumScale;
theMatrix[5] = fFrustumScale;
theMatrix[10] = (fzFar + fzNear) / (fzNear - fzFar);
theMatrix[14] = (2 * fzFar * fzNear) / (fzNear - fzFar);
theMatrix[11] = -1.0f;
然后,剩下的代码保持不变,就像matrixPerspective教程中的那样,直到我们到达void display()
函数:
//Hacked-up variables pretending to be a single vector (E)
float x = 0.0f, y = 0.0f, z = -1.0f;
//variables used for the oscilating zoom-in-out
int counter = 0;
float increment = -0.005f;
int steps = 250;
void display()
{
glClearColor(0.15f, 0.15f, 0.2f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(theProgram);
//Oscillating values
while (counter <= steps)
{
x += increment;
y += increment;
z += increment;
counter++;
if (counter >= steps)
{
counter = 0;
increment *= -1.0f;
}
break;
}
//Introduce the new data to the array before sending as a 4x4 matrix to the shader
theMatrix[0] = -x * -z;
theMatrix[5] = -y * -z;
//Update the matrix with the new values after processing with E
glUniformMatrix4fv(perspectiveMatrixUniform, 1, GL_FALSE, theMatrix);
/*
cube rendering code ommited for simplification
*/
glutSwapBuffers();
glutPostRedisplay();
}
这里是使用矩阵的顶点着色器代码:
#version 330
layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;
smooth out vec4 theColor;
uniform vec2 offset;
uniform mat4 perspectiveMatrix;
void main()
{
vec4 cameraPos = position + vec4(offset.x, offset.y, 0.0, 0.0);
gl_Position = perspectiveMatrix * cameraPos;
theColor = color;
}
我在做什么错误的事情,或者我在混淆什么?感谢您花时间阅读所有这些。