OpenGL 3D矩阵的位移、缩放变换

class wcPt3D {
public:
	GLfloat x, y, z;
};

typedef GLfloat Matrix4x4[4][4];

// 打印矩阵
void printMatrix4x4(Matrix4x4 mat)
{
	printf("[");
	for (int row = 0; row < 4; ++row)
	{
		for (int col = 0; col < 4; ++col)
		{
			printf("%.2f, ", mat[row][col]);
		}
		printf("\n");
	}
	printf("]\n");
}

// 转置矩阵
void matrix4x4Transpose(Matrix4x4 mat)
{
	Matrix4x4 mat_transp;
	for (int row = 0; row < 4; ++row)
	{
		for (int col = 0; col < 4; ++col)
		{
			mat_transp[col][row] = mat[row][col];
		}
	}

	for (int row = 0; row < 4; ++row)
	{
		for (int col = 0; col < 4; ++col)
		{
			mat[row][col] = mat_transp[row][col];
		}
	}
}

// 初始化为单位矩阵
void matrix4x4SetIdentity(Matrix4x4 &mat)
{
	for (int row = 0; row < 4; ++row)
	{
		for (int col = 0; col < 4; ++col)
		{
			mat[row][col] = (row == col);
		}
	}
}

/*
	四阶矩阵相乘并将结果保存到mat2
*/
void matrix4x4PreMultiply(Matrix4x4 mat1, Matrix4x4 mat2)
{
	Matrix4x4 mat_ret;

	for (int row = 0; row < 4; ++row)
	{
		for (int col = 0; col < 4; ++col)
		{
			GLfloat sum = 0;
			for (int i = 0; i < 4; ++i)
			{
				sum += mat1[row][i] * mat2[i][col];
			}
			mat_ret[row][col] = sum;
		}
	}

	for (int row = 0; row < 4; ++row)
	{
		for (int col = 0; col < 4; ++col)
		{
			mat2[row][col] = mat_ret[row][col];
		}
	}
}

// 位移
void translate3D(Matrix4x4 mat, const GLfloat tx,const GLfloat ty,const GLfloat tz)
{
	Matrix4x4 trans_mat;
	matrix4x4SetIdentity(trans_mat);
	trans_mat[0][3] = tx;
	trans_mat[1][3] = ty;
	trans_mat[2][3] = tz;
	matrix4x4PreMultiply(trans_mat, mat);
}

// 缩放
void scale3D(Matrix4x4 mat, const GLfloat sx, const GLfloat sy, const GLfloat sz)
{
	Matrix4x4 mat_scale;
	matrix4x4SetIdentity(mat_scale);
	mat_scale[0][0] = sx;
	mat_scale[1][1] = sy;
	mat_scale[2][2] = sz;
	matrix4x4PreMultiply(mat_scale, mat);
}

 

posted @ 2019-05-14 21:20  鞭挞代码  阅读(771)  评论(0编辑  收藏  举报