How exactly can one get to the RGBA pixel arrays of SDL 2.0 textures? Does the texture need to be specially initialized and locked down?
1 Answer
Call SDL_LockTexture
to get the data and SDL_UnlockTexture
when you are finished:
byte * bytes= nullptr;
int pitch = 0;
SDL_LockTexture(texturePointer, nullptr, reinterpret_cast<void **>(&bytes), &pitch);
// ...read data...
SDL_UnlockTexture(texturePointer);
Both methods have return codes you should check for errors, obviously.
The bytes
pointer will refer to the locked bits of the texture, and the pitch
variable will contain the number of bytes between successive rows of a texture (to account for padding).
Note that the texture must have been created with the streaming access flag (SDL_TEXTUREACCESS_STREAMING
).
Also note that you get the raw bytes of the texture data, which may not always be RGBA (for example, the texture may not have alpha).
-
2\$\begingroup\$
you get the raw bytes of the texture data
Per the API docs, you don't! wiki.libsdl.org/SDL_LockTexture -As an optimization, the pixels made available for editing don't necessarily contain the old texture data. This is a write-only operation, and if you need to keep a copy of the texture data you should do that at the application level.
It's hard to think of a way this restriction could actually be implemented, but still seems dodgy to rely on something they explicitly don't guarantee. I worry that folk doing this somehow risk the client code breaking one day, when it'd be too late \$\endgroup\$ Jul 23, 2016 at 14:03