javascript - 为什么这个简单的平移矩阵不起作用

标签 javascript graphics webgl webgl2

首先,这是翻译的工作版本:https://jsfiddle.net/zhenghaohe/5yc8exo3/4/

(代码取自 https://webgl2fundamentals.org/webgl/lessons/webgl-2d-matrices.html 并修改)

在代码的工作版本中,平移矩阵为

[
    1, 0, 0,
    0, 1, 0,    
    tx, ty, 1,
] 

这是我的图形课上教授的平移矩阵的转置。在我的类里面,平移矩阵表示为

 [
        1, 0, tx,
        0, 1, ty,    
        0, 0, 1,
    ] 

我试图找出差异从何而来。因此,我决定更改工作版本的顶点着色器,从 js 文件发送翻译矩阵,如下所示

uniform mat3 u_matrix;
void main() {
  // Multiply the position by the matrix.
  vec2 position = (u_matrix * vec3(a_position, 1)).xy;
} 

直接在顶点着色器中构造平移矩阵

uniform float tx;
uniform float ty;
void main() {
 mat3 u_matrix = mat3( 1, 0, tx,
            0, 1, ty,
            0, 0, 1,);
 vec2 position = (u_matrix * vec3(a_position, 1)).xy; 
...}

这是修改后的版本https://jsfiddle.net/zhenghaohe/5yc8exo3/

但是似乎有一个错误,

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
webgl-utils.js:67 *** Error compiling shader '[object WebGLShader]':ERROR: 0:18: ')' : syntax error 

谁能指出我修改后的代码版本哪里错误以及为什么翻译矩阵存在差异?

最佳答案

您有 2 个问题

1。你有一个错字。

正如@Rabbid76指出的

这个

 mat3 u_matrix = mat3( 1, 0, tx,
            0, 1, ty,
            0, 0, 1,);   // <=== remove the ending comma

2。 GL 矩阵将其列指定为行

所以要么改成这样

 mat3 u_matrix = mat3(
     1,  0,  0,
     0,  1,  0,
    tx, ty,  1);

或者如果它不那么令人困惑的话这个

 vec3 col0 = vec3(1, 0, 0);
 vec3 col1 = vec3(0, 1, 0);
 vec3 col2 = vec3(tx, ty, 1);

 mat3 u_matrix = mat3(col0, col1, col2);

参见https://webgl2fundamentals.org/webgl/lessons/webgl-matrix-vs-math.html

关于javascript - 为什么这个简单的平移矩阵不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095859/

相关文章:

javascript - 如何将多个属性传递给 React 中的 onChange 处理程序?

javascript - 从本地node_modules执行pug

javascript - 自定义 useFetch Hook 中的无限循环

c - 寻找 C/C++ 中的 GD 教程

html - WebGL : How do make part of an object transparent?

opengl-es - 如何读取 WebGL 中的深度缓冲区?

javascript - Animate 阅读更多/更少 JQuery

c# - imageList.Draw 不会以不同的尺寸绘制?

python - 导入禁用图形的 Pandas

javascript - 使用 THREE.LineBasicMaterial 的线条粗细