Ethan Lipson
Ethan Lipson

Reputation: 488

Reading the current fragment color in GLSL

I'm trying to draw a circle on the screen, where the circle's color is always the opposite of the color of what was there before. Similar to the crosshairs in Minecraft, which are always a different color than what they are currently focused on. Is there a way to access the current fragment color in GLSL?

Minecraft crosshairs

Upvotes: 1

Views: 1760

Answers (1)

derhass
derhass

Reputation: 45322

In GLSL, there is no such thing. I can think of a couple of ways to achieve that effect in the GL:

  1. as @Rabbid already suggestet in the comment, use Blending.
  2. another seldom used feature of the GL which might be able to achieve such an effect are the Logical Operations, which allow to define some bitwise operations between the incoming source color (the fragment shader's output) and the destination color in the framebuffer.
  3. If you can use OpenGL 4.5 or the GL_ARB_TEXTURE_BARRIER, you can sample from the same texture you are writing to, if you only sample from exactly that texel the fragment shader will write to. So this is basically exactly what you asked for: you get the actual color value your framebuffer has, at that fragment's location, and can do whatever operation you like on it. It does require a render-to-texture setup, though.
  4. Use render-to-texture in a multipass approach. First render your ordinary image to the texture, and in a separate pass, render to another render target and compose your objects with different color on top of it. This is quite similar to option 3, but does not require GL 4.5 or any advanced extensions, just OpenGL 3.0 or 2.x + FBO extensions will do.

Upvotes: 1

Related Questions