c++ - 模板和矩阵转换

标签 c++ templates matrix transformation

在我提问之前:

  1. 虽然代码使用了 Eigen图书馆,问题不在于那个特定的图书馆
  2. 虽然典型的旋转矩阵是 3x3,但下面的矩阵是用于图形编程的 4x4(使用齐次坐标)。

所以,把那个排除在外......

可以分别使用以下函数计算关于 X、Y 和 Z 轴的旋转矩阵:

Eigen::Matrix4f rotateX(float angle) {
    float radianAngle = radians(angle);
    float Sin = sinf(radianAngle);
    float Cos = cosf(radianAngle);

    Eigen::Matrix4f rotationMatrix( Eigen::Matrix4f::Identity() );

    rotationMatrix(1, 1) =  Cos;
    rotationMatrix(1, 2) =  Sin;
    rotationMatrix(2, 1) = -Sin;
    rotationMatrix(2, 2) =  Cos;

    return rotationMatrix;
}

Eigen::Matrix4f rotateY(float angle) {
    float radianAngle = radians(angle);
    float Sin = sinf(radianAngle);
    float Cos = cosf(radianAngle);

    Eigen::Matrix4f rotationMatrix( Eigen::Matrix4f::Identity() );

    rotationMatrix(0, 0) =  Cos;
    rotationMatrix(0, 2) =  Sin;
    rotationMatrix(2, 0) = -Sin;
    rotationMatrix(2, 2) =  Cos;

    return rotationMatrix;
}

Eigen::Matrix4f rotateZ(float angle) {
    float radianAngle = radians(angle);
    float Sin = sinf(radianAngle);
    float Cos = cosf(radianAngle);

    Eigen::Matrix4f rotationMatrix( Eigen::Matrix4f::Identity() );

    rotationMatrix(0, 0) =  Cos;
    rotationMatrix(0, 1) =  Sin;
    rotationMatrix(1, 0) = -Sin;
    rotationMatrix(1, 1) =  Cos;

    return rotationMatrix;
}

这些功能非常相似;如您所见,唯一的区别在于索引矩阵。这些实现也出现在 glm 中。标题。

有没有一种方法可以将这三个函数表达为一个,可以使用模板,而不增加运行时开销?

欢迎对代码提出任何意见。

最佳答案

像这样:

enum Axis {X, Y, Z};

// in C++14 you can just use std::max and std::min instead
constexpr int mymax(int a, int b) { return a > b ? a : b; }
constexpr int mymin(int a, int b) { return a < b ? a : b; }

template <Axis axis>
Eigen::Matrix4f rotateAxis(float angle) {
    float radianAngle = radians(angle);
    float Sin = sinf(radianAngle);
    float Cos = cosf(radianAngle);

    Eigen::Matrix4f rotationMatrix( Eigen::Matrix4f::Identity() );

    constexpr int c1 = mymin((axis + 1) % 3, (axis + 2) % 3);
    constexpr int c2 = mymax((axis + 1) % 3, (axis + 2) % 3);

    rotationMatrix(c1, c1) =  Cos;
    rotationMatrix(c1, c2) =  Sin;
    rotationMatrix(c2, c1) = -Sin;
    rotationMatrix(c2, c2) =  Cos;

    return rotationMatrix;
}

关于c++ - 模板和矩阵转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26847532/

相关文章:

c++ - cppreference 中的哪一部分告诉我结构化绑定(bind)声明仅适用于编译时已知对象?

c++ - 如何释放指针数组指向的结构的内存?

c++ - int 和 double 类型的无效操作数到二进制 'operator%'

django - 防止 Django 模板中的整数出现 NUMBER_GROUPING

R:使用矩阵作为输入,使用 deSolve 包求解 ODE

python - 在矩阵中找到最大值的索引(python)

c++ - 在 O(1) 中维护一个排序数组?

c++ - 令人困惑的 C++ 模板

c++ - 获取 std::vector/std::array 的维数

python - 如何从 pandas 数据帧计算 jaccard 相似度