SDL_RenderReadPixels

Did anyone use this function? I want to use it for a drawing/animation program. I would like a source code example.

dummySuf = IMG_Load("fire.png");
scope(exit)
SDL_FreeSurface(dummySuf);
SDL_Rect r = {100, 50, 32,32};
ubyte* data;
//dummySuf.format.BytesPerPixel (or SDL_PIXELFORMAT_BGRA8888)
assert(SDL_RenderReadPixels(gRenderer, &r, SDL_PIXELFORMAT_BGRA8888,
data, dummySuf.pitch) == 0, "render read pixels fail");

This doesn’t work.

It looks like you’re not allocating memory for the data. You need to do this before you call the function.

I use it in my code to take screen shots. Here’s my code: (Using screen format RGBA8888

void Crender::readPixels(float x, float y, float w, float h)
{
int ix = x;
int iy = y;
int iw = w;
int ih = h;

pixelDataWidth = iw;
pixelDataHeight = ih;

size = pixelDataWidth * pixelDataHeight * 4 * sizeof(unsigned char); //  w * h * 4 * sizeof(unsigned char);            // RGBA floats
    pixelData = (unsigned char*)malloc(size);
    pixelDataSize = size;

memset(pixelData, 0, pixelDataSize);

SDL_Rect rect;
rect.x = ix;
rect.y = iy;
rect.w = iw;
rect.h = ih;

int pitch = rect.w * 4;
SDL_RenderReadPixels(engine->platform.getRenderer(), &rect, SDL_PIXELFORMAT_RGBA8888, pixelData, pitch);

}

I’ve made an edited version of your code, that compiles. But how do I get a 2D array from it?

auto copyArea(int x, int y, int w, int h) {
	int ix = x;
	int iy = y;
	int iw = w;
	int ih = h;

	int pixelDataWidth = iw;
	int pixelDataHeight = ih;

	int size = pixelDataWidth * pixelDataHeight * 4 * cast(int)ubyte.sizeof; //  w * h * 4 * sizeof(unsigned char);            // RGBA floats

	import core.stdc.stdlib : malloc;
	import core.stdc.string : memset;

	auto pixelData = cast(ubyte*)malloc(size);
	int pixelDataSize = size;

	memset(pixelData, 0, pixelDataSize);

	SDL_Rect rect;
	rect.x = ix;
	rect.y = iy;
	rect.w = iw;
	rect.h = ih;

	int pitch = rect.w * 4;
	SDL_RenderReadPixels(gRenderer, &rect, SDL_PIXELFORMAT_RGBA8888, pixelData, pitch);

	return pixelData;
}

For a drawing application, I’d suggest keeping the drawing in an SDL_Image, in program memory .
Then you can draw to it on the CPU without using expensive copying operations.
Then, keep a texture around that has the same size of the in-memory image. Copy rectangular areas that have changed between frames into this texture, and use that with the renderer to present the result to the user.
If you want to use the Renderer’s features themselves to do the drawing operations, create a software renderer. Then, the image backing store stays on the CPU, allowing you to implement things that the renderer doesn’t support without expensive memory copy roundtrips between the CPU and the GPU.