user56725
user56725

Reputation:

three.js - fragment shader basics - color a fragment by it's position

I try to color the fragments in my shader according to their position between highest and lowest vertex. Here are the shaders:

<script type="x-shader/x-vertex" id="vertexshader">

    uniform     float   span;

    attribute   float   displacement;

    varying     vec3    vNormal;
    varying     float   color_according_to_z;

                float   z_actual;

    void main() {
        vNormal = normal;

        vec3 newPosition = position + normal * vec3(0.0, 0.0, displacement);
        gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);

        z_actual = gl_Position.z + span / 2.0;
        color_according_to_z = 1.0 / span * z_actual;
    }

</script>

<script type="x-shader/x-fragment" id="fragmentshader">

    uniform     float   span;

    varying     float   color_according_to_z;

    void main()
    {
        gl_FragColor = vec4(color_according_to_z, 0.5, 0.5, 1.0);
    }

</script>

Here is my render function:

function render() {
    requestAnimationFrame(render);

    plane.rotation.x = global_x_rotation;
    plane.rotation.z = global_z_rotation;

    for(var i = attributes.displacement.value.length - 1; i >= 0; i--) {
        attributes.displacement.value[i] = attributes.displacement.value[i] - 0.5 + Math.random();
    };

    uniforms.lowest = attributes.displacement.value.min();
    uniforms.highest = attributes.displacement.value.max();
    uniforms.span = uniforms.highest - uniforms.lowest;

    attributes.displacement.needsUpdate = true;

    uniforms.lowest.needsUpdate = true;
    uniforms.highest.needsUpdate = true;
    uniforms.span.needsUpdate = true;

    renderer.render(scene, camera);
}

I change the displacement from frame to frame and the recalculate the span between the highest and the lowest vertices.

The final piece, how to paint a fragment according to it's position towards highest or lowest, I couldn't figure out yet.

Here is a jsfiddle with the mentioned code.

Upvotes: 1

Views: 2577

Answers (1)

WestLangley
WestLangley

Reputation: 104783

You have a several errors that I can see. Check for NaN's in your variables.

The shader logic looks OK, except it might not produce the color you want.

var max = -1.0e30;
var min = +1.0e30;
var x;
for(var i = attributes.displacement.value.length - 1; i >= 0; i--) {
    x = attributes.displacement.value[i] += - 0.5 + Math.random();
    if (x < min ) min = x;
    if (x > max ) max = x;
};

uniforms.lowest.value = min; // lowest.value !
uniforms.highest.value = max;
uniforms.span.value = max - min;

attributes.displacement.needsUpdate = true;

//uniforms.lowest.needsUpdate = true; // not needed for uniforms
//uniforms.highest.needsUpdate = true;
//uniforms.span.needsUpdate = true;

fiddle: http://jsfiddle.net/c2jry/2/

Upvotes: 0

Related Questions