Reuse bitmap memory for different sized bitmaps?

Hello,

I was wondering if there is a way to have bitmaps reuse the same preallocated memory rather than constantly reallocating via newBitmap/freeBitmap.

I know there is loadIntoBitmap, but that doesn't do what I need. My situation is: every time I load a level in my game I generate one big bitmap containing the image of my level's floor, and I generate this image procedurally (so I don't load an image from file). Each level has a different size, but I know the max allowed size, so to avoid memory fragmentation I would like to:

  • preallocate a chunk of memory large enough to store the largest possible bitmap
  • every time I load a level, clear the memory and use it to store that level floor's bitmap

I guess I could do it by allocating one large bitmap and then using clear to draw into it, but I'm not sure if that is going to give me the worst possible performance when drawing it (is drawBitmap going to always draw the full-sized image even though most pixels are transparents? I don't see how to avoid that).

So ideally I would need something like LCDBitmap *newBitmapIntoMemory(void *mem, int mem_size, int width, int height, LCDColor fill) or, alternatively, a way to set width/height of an existing bitmap without reallocating.

Is there a better way to go about this?

Bump: am I really the first one ever that's trying to reuse bitmap memory?

Any C Playdate programmer that can give me some pointers? (or a Panic dev even :innocent:)

If you're using the graphics->bitmap API from SDK you're a bit limited.
As you've discovered, you cannot assign the bitmap's memory for the image and mask from your own pre-allocated pool. It's good for loading static assets but not for reusing the precious memory.

Allocating enough for your largest possible bitmap sounds sensible enough.
There won't be much rendering penalty, the draw implementation is smart enough to cull anything not on screen and transparency is handled with the mask.

The other solution is to run your own bitmap implementation and handle draw yourself using markUpdatedRows.

There are some alternative bitmap implementations available for Playdate like HEBitmap. It can be used with a custom allocator to reuse your memory pool without new/free madness. (this one has the goal to draw faster at the cost of disk space, so maybe not fine tuned for your use case)