gpt4 book ai didi

javascript - 在 WebGL 中翻译 3d 对象

转载 作者:行者123 更新时间:2023-11-30 06:21:17 24 4
gpt4 key购买 nike

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

GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type

// 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);

最佳答案

统一翻译的类型必须是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 :

Furthermore, the *-operator can be used for matrix-vector products of the corresponding dimension, e.g.:

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.)

Note that the vector has to be multiplied to the matrix from the right.

If a vector is multiplied to a matrix from the left, the result corresponds to to multiplying a column vector to the transposed matrix from the right. This corresponds to multiplying a column vector to the transposed matrix from the right:

Thus, multiplying a vector from the left to a matrix corresponds to multiplying it from the right to the transposed matrix:

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); 

关于javascript - 在 WebGL 中翻译 3d 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52908205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com