-1
$\begingroup$

I don't know how to do this. I need help. My code looks like the following:

#version 120

uniform sampler2D sampler;
varying vec2 tex_coords;

void main() {   
     vec2 p = tex_coords;    
     vec4 red = vec4(1.0,0.0,0.0,1.0);
     vec4 green = vec4(0.0,1.0,0.0,1.0);     
     gl_FragColor = green + red; //I want to display green and red side by side      
}

I am trying to display red and green side by side using two vec4s. Any help?

$\endgroup$
1
$\begingroup$

This is not how Shaders work, if you add the colors, you add the final color for the fragment that is being worked on by the fragment shader - if you use this shader for a whole triangle, then all the fragments would end up with

$ gl\_FragColor = \left(\begin{array}{c}1.0\\1.0\\0.0\\1.0\end{array}\right) $

i.e. the color vectors are just summed.


If you want to display two colors next to each other, you would typically add two objects to your scene next to each other, draw one of them with your shader that only displays red color and the other with your shader that only displays green color.


Another possibility is to calculate the position of your fragment in Model Space, World Space or another space of your choosing. Once you know that, you set a threshold up to which you color the object red and over which color the object green.

In your fragment shader you would do something like

[...]
out vec3 vPos_ModelSpace;

void main()
{
    //do all your vertex shader stuff here

    //I assume your vertex position attribute is called aPosition
    vPos_ModelSpace = aPosition.xyz;
}

And then in your fragment shader you can go about it like this

in vec3 vPos_ModelSpace;
void main()
{
    if(vPos_ModelSpace.x < 0)
    {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
    else
    {
        gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
    }
}

This assumes of course, that your model has vertices on either side of 0 on the x-axis. You shouldn't generally use if statements in shaders, since they are bad for perfomance, but this shader is so simple that it doesn't matter. Also, if you go about it this way, then simply outputting the x coordinate from your model space position suffices, no need really to use the whole vec3.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.