我正在尝试在WebGL应用程序中移动3d对象,问题是我遇到了错误:


  GL错误:GL_INVALID_OPERATION:glUniformMatrix4fv:类型的统一函数错误


// Vertex Shader

    var vertCode =
        'attribute vec4 coordinates;' +
        'uniform vec4 translation;'+
        'void main(void) {' +
        'gl_Position = coordinates * translation;' +
    '}';

...

// Associating shaders to buffer objects

         gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
         var coordinatesVar = gl.getAttribLocation(shaderProgram, "coordinates");
         gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0);
         gl.enableVertexAttribArray(coordinatesVar);

// Translation
        var Tx = 0.5, Ty = 0.5, Tz =-0.5;
        var translationMatrix = new Float32Array([
            1,0,0,0,
            0,1,0,0,
            0,0,1,0,
            Tx,Ty,Tz,1
         ]);

         var translation = gl.getUniformLocation(shaderProgram, 'translation');
         gl.uniformMatrix4fv(translation, false, translationMatrix);

// Draw

    gl.clearColor(0.5, 0.5, 0.5, 0.9);
    gl.enable(gl.DEPTH_TEST);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.viewport(0,0,canvas.width,canvas.height);
    gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);

最佳答案

统一translation的类型必须是mat4,而不是vec4
这会导致GL_INVALID_OPERATION错误,因为glUniformMatrix4fv与类型vec4不匹配。

此外,必须在顶点着色器中从右将向量乘以矩阵:

attribute vec4 coordinates;
uniform mat translation;
void main(void) {
    gl_Position = translation * coordinates;
}


参见GLSL Programming/Vector and Matrix Operations


  此外,*运算符可用于相应维度的矩阵向量乘积,例如:

vec2 v = vec2(10., 20.);
mat2 m = mat2(1., 2.,  3., 4.);
vec2 w = m * v; // = vec2(1. * 10. + 3. * 20., 2. * 10. + 4. * 20.)

  
  请注意,必须将向量从右边乘以矩阵。
  
  如果将向量从左侧乘以矩阵,则结果相当于将列向量从右侧乘以转置矩阵。这相当于将列向量从右边乘以转置矩阵:
  因此,从左向矩阵乘以一个向量对应于从右向转置矩阵乘以一个向量:

vec2 v = vec2(10., 20.);
mat2 m = mat2(1., 2.,  3., 4.);
vec2 w = v * m; // = vec2(1. * 10. + 2. * 20., 3. * 10. + 4. * 20.)





请注意,如果您想将向量乘以右边的矩阵,

gl_Position = coordinates * translation;


那么您必须转置矩阵。如果将第二个参数设置为uniformMatrix4fv,则true将转置矩阵:

gl.uniformMatrix4fv(translation, true, translationMatrix);

10-06 00:11