0
\$\begingroup\$

Given:

const int w = 10;
const int h = 10;
const int d = 8;
uint8_t* pixels = new uint8_t[w * h]

SDL_Surface* src = SDL_CreateRGBSurfaceFrom(pixels, w, h, d, w, 0, 0, 0, 0);
SDL_Surface* dst = SDL_ConvertSurface(src, src->format, 0);
// src->pitch == 10;
// dst->pitch == 12;
//std:: cout << src->pitch == dst->pitch << std::endl;

My expected result is that the two pitches must match.

In this case I have the "weird" 12 pitch value for the dst image create from the src.

  • Is that due to memory alignment optimization?
  • Is there any reasonable explanation about it?
  • Are those padding bytes used somehow or just wasted?
\$\endgroup\$
3
\$\begingroup\$

The following is based on a quick look at the SDL source code for SDL_ConvertSurface:

SDL_ConvertSurface calls SDL_CreateRGBSurface, which determines the used pitch with SDL_CalculatePitch, which aims to pad the surface to 4-bytes for speed reasons. This makes sense as memory is likely to be fetched in minimum 32-bit chunks (at least on x86).

So yes, this is indeed a memory alignment optimization (12 is padded to 4, 10 is not). The extra allocated bytes don't seem to be used, as they are allocated to be part of the surface's pixel array.

\$\endgroup\$
2
  • \$\begingroup\$ yes i was starting looking at the source code too! :) So basically it is not completely neither correct how i did in the first create surface. (or potentially as well SDL should realloc in memory alignement from the pointer) thanks \$\endgroup\$ – Raffaello Apr 12 '20 at 11:04
  • 1
    \$\begingroup\$ Yeah, all though a better idea is to forget about the optimizations that are required for efficient CPU-side rendering and just switch to SDL_Textures if possible. \$\endgroup\$ – Tyyppi_77 Apr 12 '20 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.