c++renderingsdl-2mandelbrot

Why is there a double Image when using SDL2?


I have a Mandelbrot set rendering code in c++and I'm using SDL2 to display the image. When I wanted to make my program interactive I reached a problem. By pressing W my code should clear the previous image and display a new one with new parameters, but no matter what I did the previous render does not clear out.Btw I noticed that everytime I press W my memory usage goes higher. How should I fix this?

#include <complex>
#include <iostream>
#include <SDL.h>
#include <chrono>
#include <omp.h>
using namespace std;

int main(int argc, char** argv) {
    const int resolution= 2000;

    const int rows = resolution;
    const int cols = resolution;
    complex<long double> position;
    
    int dots[rows][cols];
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            dots[i][j] = 0;
        }
    }
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        std::cerr << "SDL initialization failed: " << SDL_GetError() << std::endl;
        return 1;
    }

    const int screenWidth = cols * 1; // Adjust the window size as needed
    const int screenHeight = rows * 1;
    SDL_Window* window = SDL_CreateWindow("Mandelbrot set Visualization", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, SDL_WINDOW_SHOWN);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_Rect rect;

    long double startx = -2;
    long double endx = 2;
    long double starty = 2;
    long double endy = -2;
    
    long double stepx = (endx - startx) / (cols - 1);
    long double stepy = (endy - starty) / (rows - 1);

    rect.w = screenWidth / cols;
    rect.h = screenHeight / rows;

    int numThreads = 16;
    omp_set_num_threads(numThreads);

    #pragma omp parallel
    {
        int threadID = omp_get_thread_num(); // Get the thread ID

    #pragma omp for
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                long double real = startx + j * stepx;
                long double imag = starty + i * stepy;
                position = complex<long double>(real, imag);
                complex<long double> iterate(0, 0);
                int color = 0;
                for (int n = 0; n < 256; n++) {
                    iterate = iterate * iterate + position;
                    color++;
                    if (abs(iterate) > 2) {
                        dots[i][j] = color;
                        break;
                    }
                }
            }
        }
    }
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {

            SDL_SetRenderDrawColor(renderer, 0, dots[i][j], dots[i][j], 255); 


            rect.x = j * (screenWidth / cols);
            rect.y = i * (screenHeight / rows);
            SDL_RenderFillRect(renderer, &rect);
        }
    }
    SDL_RenderPresent(renderer);



    // Main game loop
    bool quit = false;
    SDL_Event event;
    while (!quit) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }
            else if (event.type == SDL_KEYDOWN) {
                if (event.key.keysym.sym == SDLK_w) {
                    // Zoom or change parameters, as needed
                    cout << "loop start";
                    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
                    SDL_RenderClear(renderer);
                    long double decreaseAmountx = (abs(endx) + abs(startx)) / 20;
                    long double decreaseAmounty = (abs(endy) + abs(starty)) / 20;
                    endx -= decreaseAmountx;
                    startx += decreaseAmountx;
                    endy += decreaseAmounty;
                    starty -= decreaseAmounty;
                    stepx = (endx - startx) / (cols - 1);
                    stepy = (endy - starty) / (rows - 1);
                    // Render the Mandelbrot set with new parameters
                    #pragma omp parallel
                    {
                        int threadID = omp_get_thread_num(); // Get the thread ID

                        #pragma omp for
                        for (int i = 0; i < rows; i++) {
                            for (int j = 0; j < cols; j++) {
                                long double real = startx + j * stepx;
                                long double imag = starty + i * stepy;
                                position = complex<long double>(real, imag);
                                complex<long double> iterate(0, 0);
                                int color = 0;
                                for (int n = 0; n < 256; n++) {
                                    iterate = iterate * iterate + position;
                                    color++;
                                    if (abs(iterate) > 2) {
                                        dots[i][j] = color;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    for (int i = 0; i < rows; i++) {
                        for (int j = 0; j < cols; j++) {

                            SDL_SetRenderDrawColor(renderer, 0, dots[i][j], dots[i][j], 255); 


                            rect.x = j * (screenWidth / cols);
                            rect.y = i * (screenHeight / rows);
                            SDL_RenderFillRect(renderer, &rect);
                        }
                    }
                    cout << "Present";
                    SDL_RenderPresent(renderer);
                    

                }
                else if (event.key.keysym.sym == SDLK_r) {
                    // Trigger an SDL_QUIT event to exit the application
                    SDL_Event quitEvent;
                    quitEvent.type = SDL_QUIT;
                    SDL_PushEvent(&quitEvent);
                }
            }
        }
    }

    // Cleanup and quit
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

The result of pressing W in the code


Solution

  • The problem is in the loop where you assign new values in the existing dots array.

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            long double real = startx + j * stepx;
            long double imag = starty + i * stepy;
            position = complex<long double>(real, imag);
            complex<long double> iterate(0, 0);
            int color = 0;
            for (int n = 0; n < 256; n++) {
                iterate = iterate * iterate + position;
                color++;
                if (abs(iterate) > 2) {
                    dots[i][j] = color;                    // <- here
                    break;
                }
            }
        }
    }
    

    The old values are still in the array so you'll get an overlay effect.

    First, I would recommend not allocating the huge array on the stack, but on the heap. Not all environments lets you allocate that much on the stack. Just

    #include <algorithm>
    #include <vector>
    

    and replace int dots[rows][cols]; with

    std::vector<int[cols]> dots(rows);
    

    Then, in order to test my theory, I cleared dots just before the above rescaling loop:

    std::for_each(dots.begin(), dots.end(),
                  [](auto& inner) {
                      std::fill(std::begin(inner), std::end(inner), 0);
                  });
    

    or with execution policies to maybe clear it a bit faster:

    #include <execution>
    //...
    std::for_each(std::execution::par, dots.begin(), dots.end(),
                  [](auto& inner) {
                      std::fill(std::begin(inner), std::end(inner), 0);
                  });
    

    With those changes, it repaints properly. You could also combine clearing with drawing using a parallel execution policy (or ). With a standard execution policy, it could look like this:

    std::for_each(std::execution::par_unseq, dots.begin(), dots.end(),
        [&](auto& inner) {
            // clear this row first:
            std::fill(std::begin(inner), std::end(inner), 0);
    
            auto i = std::distance(dots.data(), &inner);
            long double imag = starty + i * stepy;
    
            for(int j = 0; j < cols; j++) {
                long double real = startx + j * stepx;
                position = complex<long double>(real, imag);
                complex<long double> iterate(0, 0);
                int color = 0;
                for(int n = 0; n < 256; n++) {
                    iterate = iterate * iterate + position;
                    color++;
                    if(abs(iterate) > 2) {
                        inner[j] = color;
                        break;
                    }
                }
            }
        });