D.Cole
D.Cole

Reputation: 27

OpenGL ES 2.0, quad does not change colour when background is changed

I have drawn a circle in a quad on OpenGL ES 2.0. The code in the fragment shader takes the centre and radius that has been set and creates a circle within the quad. This worked fine until I tried to change the colour of the background as the quad still shows up blank and does not get filled with the background colour/texture. Is there an easy way to make the quad fill with the same colour/texture as the background whilst also keeping the circle on show?

The code in the fragment shader is as follows:

"varying highp vec2 textureCoordinate;\n"

"const highp vec2 center = vec2(0.5, 0.5);\n"
"const highp float radius = 0.5;\n"

"void main()\n"
"{\n"
"highp float distanceFromCenter = distance(center, textureCoordinate);\n"
"lowp float checkForPresenceWithinCircle = step(distanceFromCenter, radius);\n"

"gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * checkForPresenceWithinCircle;\n"
"}\n"

Upvotes: 0

Views: 248

Answers (2)

Jan-Harald
Jan-Harald

Reputation: 383

The trick is not to fill the quad with the background, but to avoid replacing it outside the area covered by the circle.

Your fragment shader will always output a value - even if it's outside the circle. That is, if checkForPresenceWithinCircle is 0.0, gl_FragColor gets assigned vec4(0.0, 0.0, 0.0, 0.0) - transparent black.

I think what you are looking for is the discard keyword, which prevents the shader from outputting anything for that fragment. Something like:

if ( checkForPresenceWithinCircle > 0.0 )
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
else
    discard;

Since you know that the alpha will be 0.0 outside the circle and 1.0 within, you could also achieve the same effect using alpha blending from the API-side:

draw_background();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
draw_circle();
glDisable(GL_BLEND);

Upvotes: 1

ClayMontgomery
ClayMontgomery

Reputation: 2832

The alpha part of gl_FragColor is normally read from the texture, like this:

vec4 vTexture = texture2D(gsuTexture0, gsvTexCoord);
gl_FragColor = vTexture;

Also, be sure your color buffer clear has the alpha set to 0.0, like this:

glClearColor(fRed, fGreen, fBlue, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

And there is also the problem that you can't use alpha textures with the Android Bitmap class as discussed here:

http://software.intel.com/en-us/articles/porting-opengl-games-to-android-on-intel-atom-processors-part-1/

Upvotes: 0

Related Questions