2

I have a simple program where I am trying to pass an array of fixed values (essentially a lookup table) to a shader. The calling code looks like this:

    var displacement = [];

    for ( var y=0; y<46; y++ ) {
        for ( var x=0; x<46; x++ ) {
            var sVal = Math.sin((((x/5.0)*40.0)/360.0)*Math.PI*2.0);
            var index = x + 46 * y;
            displacement[index] =  sVal;
        }
    }

    planeGeometry.addAttribute( 'displacement', new THREE.BufferAttribute( displacement, 1 ) );

    var shaderMaterial = new THREE.ShaderMaterial({
        uniforms:       uniforms,   // pass the "uniforms" vars
        //attributes:     attributes,   // and the attributes
        side:THREE.DoubleSide,      // want the texture on both sides of the wave
        vertexShader:   vs,         // pointers to the shaders
        fragmentShader: fs
    });

The shader looks like this:

<script id="vertexShader" type="x-shader/x-fragment">
        varying vec2        vUv;
        attribute float     displacement;
        uniform float       amplitude;
        void main() {
            vUv = uv;
            vec3 newPosition = position + normal * vec3(displacement * amplitude);
            gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
        }
    </script>

Prior to r72, I passed the array as an attribute in the constructor for the shader material, but now it has to be passed as a bufferGeometry attribute. The old way worked, but now I get

[.CommandBufferContext]GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 1

I've tried a whole bunch of ways to do this, but none of them work. Does anyone know the correct way to do this?

1 Answer 1

1

You need to use a typed-array for you displacement array, instead of a JS array.

var displacement = new Float32Array( size );

three.js r.75

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm! So simple! Thanks! You guys at three.js rock!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.