/* 矩阵初始化,正对角线上设为1,其余为0 */
void Matrix4x4SetIdentity(Matrix4x4 matIdent4x4)
{
GLint row, col;
for (row = 0; row < 4; row++)
for (col = 0; col < 4; col++)
matIdent4x4[row][col] = (row == col);
}
/* 两个矩阵相乘,结果存储到矩阵m2;
如果只是使用矩阵实现平移,可以省去这个步骤,
若是要用矩阵全部实现平移、旋转、缩放,则需要一个中间矩阵,最后将某点的中间矩阵与原坐标矩阵进行相乘,得出新的点坐标
*/
void Matrix4x4PreMultiply(Matrix4x4 m1, Matrix4x4 m2)
{
GLint row, col;
Matrix4x4 matTemp;
for (row = 0; row < 4; row++)
for (col = 0; col < 4; col++)
matTemp[row][col] = m1[row][0] * m2[0][col] + m1[row][1] *
m2[1][col] + m1[row][2] * m2[2][col] + m1[row][3] * m2[3][col];
for (row = 0; row < 4; row++)
for (col = 0; col < 4; col++)
m2[row][col] = matTemp[row][col];
}
/* 平移 */
void Translate3D(GLfloat tx, GLfloat ty, GLfloat tz)
{
Matrix4x4 matTransl;
Matrix4x4SetIdentity(matTransl);
matTransl[0][3] = tx;
matTransl[1][3] = ty;
matTransl[2][3] = tz;
Matrix4x4PreMultiply(matTransl, matComposite);
}
/*
旋转,全方位旋转
*/
void rotate3D (wcPt3D p1, wcPt3D p2, GLfloat radianAngle)
{
Matrix4x4 matQuatRot;
float axisVectLength = sqrt ((p2.x - p1.x) * (p2.x - p1.x) +
(p2.y - p1.y) * (p2.y - p1.y) +
(p2.z - p1.z) * (p2.z - p1.z));
float cosA = cosf (radianAngle);
float oneC = 1 - cosA;
float sinA = sinf (radianAngle);
float ux = (p2.x - p1.x) / axisVectLength;
float uy = (p2.y - p1.y) / axisVectLength;
float uz = (p2.z - p1.z) / axisVectLength;
translate3D (-p1.x, -p1.y, -p1.z);
matrix4x4SetIdentity (matQuatRot);
matQuatRot [0][0] = ux*ux*oneC + cosA;
matQuatRot [0][1] = ux*uy*oneC - uz*sinA;
matQuatRot [0][2] = ux*uz*oneC + uy*sinA;
matQuatRot [1][0] = uy*ux*oneC + uz*sinA;
matQuatRot [1][1] = uy*uy*oneC + cosA;
matQuatRot [1][2] = uy*uz*oneC - ux*sinA;
matQuatRot [2][0] = uz*ux*oneC - uy*sinA;
matQuatRot [2][1] = uz*uy*oneC + ux*sinA;
matQuatRot [2][2] = uz*uz*oneC + cosA;
matrix4x4PreMultiply (matQuatRot, matComposite);
translate3D (p1.x, p1.y, p1.z);
}
//仅对X轴旋转
void Rotate3Dx(wcPt3D pivotPt, GLfloat theta)
{
Matrix4x4 matRot;
/* Initialize rotation matrix to identity. */
Matrix4x4SetIdentity(matRot);
matRot[1][1] = cos(theta);
matRot[1][2] = sin(theta);
matRot[2][1] = -sin(theta);
matRot[2][2] = cos(theta);
Matrix4x4PreMultiply(matRot, matComposite);
}
//仅对Y轴旋转
void Rotate3Dy(wcPt3D pivotPt, GLfloat theta)
{
Matrix4x4 matRot;
/* Initialize rotation matrix to identity. */
Matrix4x4SetIdentity(matRot);
matRot[0][0] = cos(theta);
matRot[0][2] = sin(theta);
matRot[2][0] = -sin(theta);
matRot[2][2] = cos(theta);
Matrix4x4PreMultiply(matRot, matComposite);
}
/*缩放*/
void scale3D (Gfloat sx, GLfloat sy, GLfloat sz, wcPt3D fixedPt)
{
Matrix4x4 matScale3D;
matrix4x4SetIdentity (matScale3D);
matScale3D [0][0] = sx;
matScale3D [0][3] = (1 - sx) * fixedPt.x;
matScale3D [1][1] = sy;
matScale3D [1][3] = (1 - sy) * fixedPt.y;
matScale3D [2][2] = sz;
matScale3D [2][3] = (1 - sz) * fixedPt.z;
matrix4x4PreMultiply (matScale3D, matComposite);
}