Best way to re-render a section of texture with some pixels changed?

I have a big texture. It’s basically a background image. It gets rendered. Appears on the screen.

Then, I render some other textures over it.

Some areas of the background image should NOT appear pasted over. In effect, they are foreground. They are generally not simple rectangles in shape.

I can do a simple re-render when the foreground section is a rectangle, as so:

		                background,  // the big background image texture
		                &srcrect,        //  rectangle defining which piece is the foreground
		                &srcrect);         //  rectangle defining which piece is the foreground - it's just pasted over the top, in effect

but what’s the idiomatic way when the foreground section isn’t a simple rectangle?

Right now, I’m considering copying it to a whole next texture as a rectangle, editing pixels individually so that any pixel not in the foreground polygon has its alpha set to transparent, and then rendering that altered texture just as above. Is this the best I can do?

In the old days, this would be something like a dirty rect optimization or masking for pixel-sized differences. You can do it with the right shader and it’s also possible to do this sort of masking update with a stencil buffer. Neither of those options are particularly compatible with standard SDL rendering. Coincidentally, I’m thinking about an abstracted API for stencil buffers lately, so I might have something useful in a few weeks. If you’re interested, I’d love to see specifics of use-cases and concerns.

Someone asked for an example before deleting their reply. I’ll answer anyway.

The image on screen starts like this:

Just the background texture, rendered to screen.

Then an object texture gets rendered into position:

Now, from the viewpoint we have, that vertical wooden pile should actually be this side of the walker. It should be in the foreground.

And then a small rectangle of the background texture gets rendered again, over the top:

The top right edge of the newly rendered rectangle can be seen sharply against the previous object that was rendered.

The foreground section is precisely known as a polygon shape, but I have to render rectangles. So it’s looking like I will have to grab that rectangular part that I know is foreground, and then use the polygon I have defining the precise shape of the foreground (in this context, the upright wooden pile shown) to set all pixels in the foreground rectangular texture that are NOT inside that polygon to a new value - transparent - and then I can render the altered texture rect in place.