Ah I see your using SDL_framerateDelay.
Using SDL_RenderFillRect I am using about 60% - 70% of the cpu rendering 131072 (2 ^ 17).
Using SDL_RenderFillRects I am using about 30% of the cpu rendering 131072 (2 ^ 17).
Not sure you can change colors with this approach though.
int SDL_RenderFillRects(SDL_Renderer* renderer,
const SDL_Rect* rects,
int count)
Possible solutions
- Do not draw a rect if you know you won’t be able to see it on the screen.
- Use a texture to replicate the drawing of a Rect, the new version of SDL2 uses texture batching which should improve rendering speed.
Example of solution 2, about 27- 30% cpu
#include <SDL.h>
#include <array>
struct Square {
SDL_Rect rect;
SDL_Color col;
};
// Create a 1x1 white texture
SDL_Texture* create1x1Texture(SDL_Renderer* const renderer) {
SDL_Surface* surface(SDL_CreateRGBSurface(0, 1, 1, 8, 0, 0, 0, 0));
if (surface) {
SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
return texture;
}
return nullptr;
}
int main(int argc, const char* argv[])
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window* window = SDL_CreateWindow("Frames", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, 0);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
SDL_Texture* texture = create1x1Texture(renderer);
std::array<Square, 131072> squares{ };
// Change squares data
squares[0].rect = {10, 10, 10, 10};
squares[0].col = {255, 0, 0};
bool running = true;
while (running) {
SDL_Event e;
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT:
running = false;
break;
}
}
SDL_RenderClear(renderer);
for (const auto& square : squares) {
SDL_SetTextureColorMod(texture, square.col.r, square.col.g, square.col.b);
SDL_RenderCopy(renderer, texture, nullptr, &square.rect);
}
SDL_RenderPresent(renderer);
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}