Home > Enterprise >  Copy part of texture to another texture OpenGL 4.6 C
Copy part of texture to another texture OpenGL 4.6 C

Time:04-13

If I have to texture IDs

SrcID and DestID

How can i copy a part of srcID to DestId

Given the normalised coordinates of the part to be copied, width and height of both src and dest

By normailsed I mean they are between 0 and 1

CodePudding user response:

You can attach the textures to a framebuffer, and then use glBlitFramebuffer. I can't test the code below, but it should be about right. You only need to specify the coordinates in pixels, but it's easy to compute by multiplying normalized coordinates by texture dimensions.

GLuint FboID;
glGenFramebuffers(1, &FboID);
glBindFramebuffer(GL_FRAMEBUFFER, FboID);

// Attach the textures to atttachment slots
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, SrcID, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, DestID, 0);

// Prepare to read from first attachment (src texture)
// and draw into second attachment (dst texture)
glReadBuffer(GL_COLOR_ATTACHMENT0);
GLenum[] DstBuffer = { GL_COLOR_ATTACHMENT1 };
glDrawBuffers(1, &DstBuffer);

// Fill those pixel coordinates from your normalized coordinates 
// (e.g. srcX0 = 0.2f * srcWidth) 
GLint srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1;
glBlitFramebuffer(
    srcX0, srcY0, 
    srcX1, srcY1, 
    dstX0, dstY0, 
    dstX1, dstY1
    GL_COLOR_BUFFER_BIT, 
    GL_LINEAR);

glBindFramebuffer(GL_FRAMEBUFFER, 0); // disable FBO
// optionally delete FBO, if you won't need it anymore
// glDeleteFramebuffers(1, &FboID); 
  • Related