SFML community forums

Help => Graphics => Topic started by: stati30241 on April 10, 2021, 07:54:09 pm

Title: Is there a better way to draw multiple points
Post by: stati30241 on April 10, 2021, 07:54:09 pm
I am trying to draw every pixel on an 800 by 800 window with a random color, and I am drawing the pixel using sf::Vertex, but when I run the program, it is very slow. Is there a better way to draw multiple points that is faster and uses less memory. Here is the code I wrote:

#include <SFML/Graphics.hpp>

#include <ctime>
#include <random>


int main() {
        // Window
        sf::RenderWindow window{ sf::VideoMode{ 800u, 800u }, "Views" };
        sf::Clock clock;

        static std::mt19937 randomEngine{ static_cast<unsigned int>(std::time(nullptr)) };
        std::uniform_int_distribution<int> randDist{ 0, 255 };

        // Main game loop
        while (window.isOpen()) {
                // Event loop
                sf::Event sfmlEvent;
                while (window.pollEvent(sfmlEvent)) {
                        if (sfmlEvent.type == sf::Event::Closed) {
                                window.close();
                        }
                }

                // Draw
                for (float i = 0; i < window.getSize().x; ++i) {
                        for (float j = 0; j < window.getSize().y; ++j) {
                                uint8_t r = randDist(randomEngine);
                                uint8_t g = randDist(randomEngine);
                                uint8_t b = randDist(randomEngine);
                                sf::Vertex pixel{ { i, j }, { r, g, b } };
                                window.draw(&pixel, 1, sf::Points);
                        }
                }

                // Display
                window.display();
        }
}

 
Title: Re: Is there a better way to draw multiple points
Post by: G. on April 11, 2021, 12:52:52 am
You could use an sf::VertexArray (https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1VertexArray.php), fill it with your points and draw the VertexArray once (with the sf::PrimitiveType::Points primitive type) instead of drawing each Vertex independently.
(Possibly an sf::VertexBuffer but I don't know much about them)

Pretty Sure it's gonna be a lot faster.
Title: Re: Is there a better way to draw multiple points
Post by: Stauricus on April 12, 2021, 05:33:32 pm
on top of what G. said, are you aware that you are randomizing 3 colors of 800x800 pixels (640000 pixels, resulting in 1920000 random uint8_t) every frame?