ewakwwg12
ewakwwg12

Reputation: 91

How can I pass along an array of floats as a uniform to shaders from Three JS

To clarify I am using Three JS, React-Three-Fiber, React

I have disc with points mapped on it, I have calculated the distance of every point to the center of the desk and stored results in an array. I would like to pass this array to the shaders but I am struggling to understand how to do it. I read in the docs you can also pass along vec3,mat3,float essentially. My array has a length of 1000 so I cannot use it with any of the data types uniforms can be used with, if I store the array as a define how can I go about using it in the shader file?

uniforms

  const uniforms = useMemo(() => ({
    uTime: {
      value: 0.0
    },
    uRadius: {
      value: radius
    },
    uDistance: {
      value: normalDistances
    }
  }), [])

fragment shader

const fragmentShader = `
uniform vec3 uDistance;

varying float vDistance;

  void main() {

    float x = uDistance[52];

    vec3 color = vec3(0.5, 0.5, x);

    gl_FragColor = vec4(color, 1.0);
  }

`

export default fragmentShader

I cannot import a uniform without specifying the data type, and I cannot find how to import a define which was passed along from javascript. Does anyone know what my issue is? Thanks!

Upvotes: 2

Views: 1164

Answers (1)

Mugen87
Mugen87

Reputation: 31086

uniform vec3 uDistance;

This is no valid declaration of a uniform array. You always have to define the length like so:

uniform vec3 uDistance[8];

However, keep in mind that uniform arrays require a uniform vector for each entry. If you want to use a length of 1000, you easily hit the maximum supported uniform vectors on devices.

I suggest you encode your distance data into a texture and then sample it in your shader. In three.js, you can use the DataTexture class for this.

Upvotes: 4

Related Questions