jjxtra
jjxtra

Reputation: 21100

Run OpenGL shader to modify existing texture / frame buffer

How do I use an OpenGL shader to modify an existing texture / frame buffer in place without using a second texture or frame buffer? Is this even possible?

Upvotes: 4

Views: 2049

Answers (2)

user5440338
user5440338

Reputation: 1

It's tricky to make it using the following code.

// in fragment shader
uniform sampler2D input;

out vec4 color;// bind sampler and framebuffer with same texture
void main(){
ivec2 pos = ivec2(gl_FragCoord.xy);
if(cond){
    color = vec4(0.0);
}else{
    color = texelFetch(input, pos, 0);
  }
}

Upvotes: 0

Thomas
Thomas

Reputation: 725

At first: It is technically possible and safe to read and write in the same pass using this extension - however i wouldn't recommend this, especially for learners, since the extension is tightly limited and might not be supported on every hardware.

That being said:

So it's not possible to use the same texture as a sampler and frame buffer?

You can use the same texture as a framebuffer texture attachment and render to it and as a texture sampler to look up values in the shader, but not in the same pass. That means, if you have two textures you could read from A and write to B and afterwards switch textures and read from B and write to A. But never A->A or B->B (without the extension mentioned).

As a technical detail, a texture currently being used as a target can also be bound to a sampler shader variable at the same time, but you must not use it.

So let's say I want to blur just a small part of a texture. I have to run it through a shader to a second texture and then copy that texture back to the first texture / frame buffer?

Second texture yes. But for efficiency reasons do not copy the texture data back. Just delete the source texture and use the target texture you have rendered to in the future. If you have to do this often, keep the source texture as a render target for later use to increase performance. If you have to do it every frame just swap the textures every frame. The overhead is minimal.

Upvotes: 6

Related Questions