基本上,你正在寻找一个替代OpenGL的矩阵堆栈的做你的转换。
假设你正在使用C/C++,我建议有一个看GLM库:http://glm.g-truc.net/
这是一个只有头库,易于使用,并为预OpenGL ES 2.0的矩阵堆栈的完美替代。它甚至为gluOrtho()和gluPerspective()等不推荐的glu函数提供了功能。 Glm的矩阵可以很容易地传递给着色器,因为它们考虑着色器。
您必须对您的代码进行一些变化;例如将自己的顶点/矩阵定义转换为glm :: vec3/glm :: mat4。
下面是我如何构建我传递给顶点着色器的mvp矩阵的一个示例:在这种情况下,actorInstance类具有一些像位置(在世界中)和旋转定义为glm :: vec3的属性。将构建的模型,模型/视图和模型/视图/投影矩阵是类的所有属性:
void CActorInstance::update(glm::mat4 viewMatrix, glm::mat4 projectionMatrix)
{
// act according to class behavior
this->actorClass->act(&input, &world, &direction, &rotation);
// calculate the translation matrix
glm::mat4 translate = glm::mat4();
translate = glm::translate(glm::mat4(), world);
// calculate the rotation matrix
glm::mat4 rotateX = glm::rotate(glm::mat4(1.0f), rotation.x, glm::vec3(1,0,0));
glm::mat4 rotateY = glm::rotate(glm::mat4(1.0f), rotation.y, glm::vec3(0,1,0));
glm::mat4 rotateZ = glm::rotate(glm::mat4(1.0f), rotation.z, glm::vec3(0,0,1));
glm::mat4 rotate = rotateX * rotateY * rotateZ;
// calculate the model matrix
mMatrix = translate * rotate;
// calculate the model/view matrix
mvMatrix = viewMatrix * mMatrix;
// calculate the model/view/projection matrix
mvpMatrix = projectionMatrix * mvMatrix;
};
显然每个对象的MVP矩阵获取根据该对象的位置和旋转更新每一帧。 viewMatrix和projectionMatrix从我的相机类传下来。 这个矩阵然后被用来渲染网格:
void CMesh::renderMesh(GLuint program, glm::mat4 *mvp)
{
glUseProgram(program);
int mvpLocation = glGetUniformLocation(program, "mvpMatrix");
int texLocation = glGetUniformLocation(program, "baseMap");
glUniformMatrix4fv(mvpLocation, 1, GL_FALSE, glm::value_ptr(*mvp));
// rendering code ommitted
};
希望这有助于:)
编辑:建议实施矩阵堆栈
stl::stack<glm::mat4> matrixStack; // the matrix stack
matrixStack.push_back(glm::mat4()); // push an identity matrix on the stack
,这是你glLoadIdentity( )...
刚刚查找OpenGL规范。每个操作都有矩阵公式。 – alxx 2012-02-06 08:25:25