【问题标题】:How to create projection matrix from forward/left/up vectors in webgl如何从 webgl 中的前/左/上向量创建投影矩阵
【发布时间】:2019-10-04 16:02:10
【问题描述】:

我有 webgl 代码,它使用 3 个旋转角度来旋转相机,然后它返回向前、向左和向上的向量。它工作正常:

function matrixFromPositionAndRotation(aPosition, aRotX, aRotY, aRotZ) {
    var matrix = mat4.create();
    gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 2000.0, matrix);

    mat4.rotateX(matrix, aRotX);
    mat4.rotateY(matrix, aRotY);
    mat4.rotateZ(matrix, aRotZ);

    mat4.translate(matrix, aPosition);

    return {
        matrix: matrix,
        forward: vec3.create([matrix[2], matrix[6], matrix[10]]),
        left: vec3.create([matrix[0], matrix[4], matrix[8]]),
        up: vec3.create([matrix[1], matrix[5], matrix[9]])
    };
}        

但是我想做相反的事情。我知道位置、前向、左向和向上向量,我想计算投影矩阵。我尝试了相反的方法,但它不起作用:

function matrixFromPositionAndVectors(aPosition, aForward, aLeft, aUp) {
    var matrix = mat4.create();
    gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 2000.0, matrix);

    mat4.translate(matrix, aPosition);

    matrix[0] = aLeft[0];
    matrix[4] = aLeft[1];
    matrix[8] = aLeft[2];

    matrix[2] = aForward[0];
    matrix[6] = aForward[1];
    matrix[10] = aForward[2];

    matrix[1] = aUp[0];
    matrix[5] = aUp[1];
    matrix[9] = aUp[2];

    return {
        matrix: matrix
    };
}     

【问题讨论】:

  • 仅供参考,我认为大多数人称mat4.perspective 构成投影矩阵的矩阵。其他矩阵有其他名称,具体取决于它们的使用方式。

标签: javascript 3d opengl-es webgl


【解决方案1】:

您可能需要将您拥有的矩阵乘以您正在创建的矩阵

    mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 2000.0, matrix);

    mat4.translate(matrix, aPosition);

    const m = [
      ...aLeft, 0,
      ...aUp, 0,
      ...aForward, 0,
      0, 0, 0, 1,
    ];
    mat4.multiply(matrix, matrix, m);

请注意,尽管我希望 aLeft 实际上是 aRight。换句话说,考虑身份

[
  1, 0, 0, 0,    // points right (x = 1)
  0, 1, 0, 0,    // points up    (y = 1)
  0, 0, 1, 0,    // points ??    (z = 1) If you define +Z as forward.
  0, 0, 0, 1,
]

对于相机矩阵,-Z 通常是向前的。

我也猜你不熟悉 WebGL (OpenGL) 矩阵。他们称行为“列”

[
  1, 0, 0, 0,    // column 0
  0, 1, 0, 0,    // column 1
  0, 0, 1, 0,    // column 2
  0, 0, 0, 1,    // column 3
]

xAxis 就到这里了

[
  Xx, Xy, Xz,  0,    // column 0 (xAxis)
   0,  1,  0,  0,    // column 1
   0,  0,  1,  0,    // column 2
   0,  0,  0,  1,    // column 3
]

虽然你当然没有发布你的数学库。 mat4 不是任何标准的一部分,所以没有看到它我们无法知道它在做什么,只能猜测。

你可以测试。这样做

console.log(mat4.translate(mat4.create(), [11, 22, 33]));

你可能会得到

[
   1, 0, 0, 0,
   0, 1, 0, 0,
   0, 0, 1, 0,
  11,22,33, 1,
]

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 2015-08-06
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 2020-07-01
    • 2019-03-05
    • 2015-11-01
    • 2012-09-07
    相关资源
    最近更新 更多