我在纯C中为glRotatef编写替代函数时遇到问题。我需要实现哪些参数的函数:点列表,角度和旋转矢量。函数必须在旋转后返回点列表。我的功能如下:
void rotate(float * current, float a, float x, float y, float z)
{
float sina = sinf(a);
float cosa = cosf(a);
float rotateMatrix[9] = //creating rotate matrix
{
x*x*(1-cosa) + cosa, x*y*(1-cosa) - z*sina, x*z*(1-cosa) + y*sina,
y*x*(1-cosa) + z*sina, y*y*(1-cosa) + cosa, y*z*(1-cosa) - x*sina,
z*x*(1-cosa) - y*sina, z*y*(1-cosa) + x*sina, z*z*(1-cosa) + cosa
};
float *resultVertexList = current; //temporary help
int i;
for(i=0;current[i] != 0;i++) //multiplying CURRENT_MATRIX * ROTATE_MATRIX
{
int currentVertex = (i/3) * 3;
int rotateColumn = i%3;
resultVertexList[i] =
current[currentVertex] * rotateMatrix[rotateColumn] +
current[currentVertex+1] * rotateMatrix[rotateColumn+3] +
current[currentVertex+2] * rotateMatrix[rotateColumn+6];
}
current = resultVertexList;
}
我在这里称呼它为rotate(current, M_PI/10, 0, 1, 0);
之后,我获取current
点列表,然后使用openGL绘制它们。为了测试我尝试旋转表示立方体的点列表。它会旋转,但每次调用rotate
函数都会缩小。我不知道为什么。看一些截图:
在rotate
函数的多次调用之后,它缩小到一点。
我做错了什么?
答案 0 :(得分:0)
这行代码:
float *resultVertexList = current; //temporary help
不会复制您的顶点列表。您只是将指针复制到列表中,因此在此之后您有两个指向同一列表的指针。因此,以下循环使用已旋转的x / y坐标来计算新的y / z坐标,这显然是错误的。
我也想知道你的终止条件:
current[i] != 0
没错,但它可以防止你有任何零坐标的顶点。相反,我建议一个额外的参数来明确传递顶点数。
我也会旋转每个顶点而不是每个坐标,它更自然,更容易理解:
void rotate(float * current, int vertexCount, float a, float x, float y, float z)
{
float sina = sinf(a);
float cosa = cosf(a);
float rotateMatrix[9] =
{
x*x*(1 - cosa) + cosa, x*y*(1 - cosa) - z*sina, x*z*(1 - cosa) + y*sina,
y*x*(1 - cosa) + z*sina, y*y*(1 - cosa) + cosa, y*z*(1 - cosa) - x*sina,
z*x*(1 - cosa) - y*sina, z*y*(1 - cosa) + x*sina, z*z*(1 - cosa) + cosa
};
int i;
for (i = 0; i < vertexCount; ++i)
{
float* vertex = current + i * 3;
float x = rotateMatrix[0] * vertex[0] + rotateMatrix[1] * vertex[1] + rotateMatrix[2] * vertex[2];
float y = rotateMatrix[3] * vertex[0] + rotateMatrix[4] * vertex[1] + rotateMatrix[5] * vertex[2];
float z = rotateMatrix[6] * vertex[0] + rotateMatrix[7] * vertex[1] + rotateMatrix[8] * vertex[2];
vertex[0] = x;
vertex[1] = y;
vertex[2] = z;
}
}
答案 1 :(得分:0)
实现矩阵向量多重复制的方式非常粗糙 - 更重要的是 - 只是错误。
问题是您覆盖了仍然需要的数据。因此,在非常简单的交互中,您有效地写入current[0]
(并且您的resultVertexList
指针根本没有任何帮助。它指向您的唯一数据的复制品,直接将其覆盖在原位在接下来的两次迭代中,将使用current[0]
的新值,而不是原始值。
我建议您只需实现一个直接的mat3 * vec3
函数,该函数可以在循环中轻松调用,并且不需要覆盖它仍然需要的数据。