How to correctly use uniform buffers in webgpu?

Hi Team,

I’ve had a recurring issue when trying to write shaders in webgpu, in that uniforms never seem to have any data in them (or are misaligned). This seems particularly obvious when attempting to pass an array of values. Everything compiles, but even the simplest data i.e. if (0.0 > myUniform). where my Uniform is hardcoded to some large value. Doesn’t work. Hardcoding the values in the shader works as expected so its not the shader itself.

Heres some code similar to how I’m setting it:


    const positions = new Float32Array(maxNumber * 3);
    const blendRadii = new Float32Array(maxNumber);
    const indices = new Float32Array(maxNumber);
  
    manager.getList().forEach((p, idx) => {
      positions.set(p.worldPosition, idx * 3);
      blendRadii[idx] = 5;
      indicies[idx] = idx;
    });
    app.root.findComponents('render').forEach((r) =>
      r.meshInstances.forEach((m: MeshInstance) => {
        const mat = m.material;
        mat.setParameter('pCount', textures.length);
        mat.setParameter('positions', positions);
        mat.setParameter('blendRadii', blendRadii);
        mat.setParameter('indices', indices);
        mat.update();
      })
    );

And the uniforms in the shader:

    uniform pCount: u32;
    uniform positions: array<vec3f, 4>;
    uniform blendRadii: array<f32, 4>;
    uniform indicies: array<f32, 4>;

This is almost certainly the same issue that blocked me when doing my other rnd work on volumetrics on webgpu (even though it works in webgl, I couldn’t for the life of me get the webgpu version working)

What am I doing wrong?

We have many examples where this works, so not sure what your problem is. I assume you checked WGSL Specifics | PlayCanvas Developer Site
See the Uniforms section, it mentions the wrapped types as well, which is applicable to your case.

Note that for arrays, instead of

mat.setParameter('positions', positions);

you need this, for WebGL and also WebGPU

mat.setParameter('positions[0]', positions);
2 Likes

Great thanks, yes I’m probably being dumb. I’ll try that later, If not I’ll get a test case together

1 Like

Yup Massive face palm time :man_facepalming:

All working now thanks and it looks great

1 Like