0

I'm trying to draw gradient (Both horizontal & vertical) background, problem is this causes high cpu usage. Size of a gradient paint is 32767x32767 but of course i'm only drawing based on screen width/height and on offset (starting point of painting). As far as i know i cant put such big painting in memory so paint should be created dynamically. I am using this code right now (on 1600x900 it uses 10-20% of cpu, without gradient paint (looping SDL_RenderDrawLine) it's just 0%):

    SDL_SetRenderDrawColor(Renderer, 59, 156, 156, 255);
    SDL_RenderClear(Renderer);

    for (int X = 0; X < Width; X++)
    {
        SDL_SetRenderDrawColor(Renderer, 75, 0, 130, X * 255 / 0xfff);
        SDL_RenderDrawLine(Renderer, X, 0, X, Height);
    }

    for (int Y = 0; Y < Height; Y++)
    {
        SDL_SetRenderDrawColor(Renderer, 75, 0, 130, Y * 255 / 0xfff);
        SDL_RenderDrawLine(Renderer, 0, Y, Width, Y);
    }

Is there better way to solve this problem ?

  • You should offload gradient calculation to GPU. Something similar to [gradient mesh patch](https://learn.microsoft.com/ru-ru/windows/desktop/api/d2d1_3/ns-d2d1_3-d2d1_gradient_mesh_patch). – user7860670 Aug 28 '18 at 10:49
  • Perfect job for shaders, but SDL don't give you access to that. How often you update your background? Is it scrollable? You can cache result in render texture (but you'll need to update in on device loss) if it isn't constantly changing. – keltar Aug 28 '18 at 11:04
  • 2
    This has already been asked but tagged with [tag:c]. Funny enough, the accepted answer suggests what you did. (I find this funny, as I don't know rather anything about SDL but did such gradient background with a simple GLSL shader.) However, the other answer provides a solution involving the GPU (probably better) with a little texture trick: [SO: How to create a color gradient in SDL](https://stackoverflow.com/a/42234816/7478597). Seems to me worth a look. – Scheff's Cat Aug 28 '18 at 11:12
  • I have locked frames to 100. And i'm planning to make it scrollable with width and height of 32767. It is not game, i'm making editor with this background –  Aug 28 '18 at 11:12
  • Btw. I don't believe that putting a painting with screen size into memory is a big problem on current common H/W. In Qt (and probably other GUI libs), there is often used double buffering to prevent flickering displays. This means nothing else then creating a `QPixmap` with widget size, painting all the new stuff into this `QPixmap`, and painting (i.e. copying or bit-blitting) finally the `QPixmap` at once to the display. – Scheff's Cat Aug 28 '18 at 11:28
  • 1
    @Scheff, I know that post, from there i got this code. Thanks anyway, i have solved by second post on that thread, i have created texture with big pixels and then changed rectangle x,y for specified point of rendering. (Code: https://pastebin.com/DCC4xrsy) –  Aug 28 '18 at 14:43

0 Answers0