【问题标题】:WebGL2 : cannot set uniform floatWebGL2:无法设置统一浮动
【发布时间】:2021-10-30 10:24:50
【问题描述】:

假设我有一个使用 WebGL2 中的顶点着色器和片段着色器编译和链接的程序。

这是我的着色器的样子:

var vertex_shader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertex_shader,
    `#version 300 es
    in vec2 pos;
    out vec2 texCoord;
    void main(){
        gl_Position = vec4(pos,0.0,1.0);
        texCoord = (pos+vec2(1.0))*0.5;
    }`
);

var math_pass_shader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(math_pass_shader,
    `#version 300 es
    precision highp float;

    const float bailout = 300.0;

    in vec2 texCoord;

    uniform float zoom;
    uniform float center_x;
    uniform float center_y;

    layout (location = 0) out vec4 outColor;
    layout (location = 1) out vec2 z0;
    layout (location = 2) out vec2 zn;
    layout (location = 3) out uint iteration_count;

    vec2 add(vec2 c1, vec2 c2){
        return vec2(c1.x + c2.x, c1.y + c2.y);
    }

    vec2 mul(vec2 c1, vec2 c2){
        return vec2(c1.x*c2.x - c1.y*c2.y, c1.x*c2.y + c1.y*c2.x);
    }

    float mag2(vec2 c){
        return c.x*c.x + c.y*c.y;
    }

    float mag(vec2 c){
        return sqrt(mag2(c));
    }

    float mag_norm(highp vec2 c){
        return log(mag2(c)/bailout)/log(bailout);
    }

    float arg(vec2 c){
        return 2.0 * atan(c.y / (c.x + sqrt(mag2(c))));
    }

    float arg_norm(vec2 c){
        return arg(c)/6.282 + 0.5;
    }

    void main() {
        z0.x = center_x + texCoord.x*zoom - zoom * 0.5;
        z0.y = center_y + texCoord.y*zoom - zoom * 0.5;

        zn = z0;
        for(iteration_count =0u ; iteration_count < 200u; iteration_count++){
            if(mag2(zn)>bailout){
                outColor = vec4(1, 1, 0.5, 1); // return reddish-purple
                return;
            }
            zn = add(mul(zn,zn),z0);
        }
        outColor = vec4(zn.x, zn.y, 0.5, 1); // return reddish-purple
    }`
);

然后我链接我的程序,并检查链接/编译错误,没有找到:

var math_program = gl.createProgram();
gl.attachShader(math_program, vertex_shader);
gl.attachShader(math_program, math_pass_shader);
gl.linkProgram(math_program);

我得到了我在我的程序中使用过的所有制服:

var zoom = gl.getUniformLocation(math_program, "zoom");
var x = gl.getUniformLocation(math_program, "center_x");
var y = gl.getUniformLocation(math_program, "center_y");

而且,当我设置这些制服时,我会收到警告:WebGL warning: uniform setter: No active linked Program.

gl.uniform1f(zoom, 2.5);
gl.uniform1f(x, -0.5);
gl.uniform1f(y, 0.0);

这里有什么我遗漏的吗?

提前致谢

【问题讨论】:

    标签: javascript glsl shader webgl webgl2


    【解决方案1】:

    gl.uniform1f 在当前安装程序的默认统一块中设置统一变量。因此,您必须先使用gl.useProgram 安装程序,然后才能设置制服:

    gl.useProgram(math_program);
    gl.uniform1f(zoom, 2.5);
    gl.uniform1f(x, -0.5);
    gl.uniform1f(y, 0.0);
    

    【讨论】:

      猜你喜欢
      • 2017-08-22
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多