Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Is there a better way to draw multiple points  (Read 2773 times)

0 Members and 1 Guest are viewing this topic.

stati30241

  • Newbie
  • *
  • Posts: 2
    • View Profile
Is there a better way to draw multiple points
« 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();
        }
}

 

G.

  • Hero Member
  • *****
  • Posts: 1593
    • View Profile
Re: Is there a better way to draw multiple points
« Reply #1 on: April 11, 2021, 12:52:52 am »
You could use an sf::VertexArray, 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.
« Last Edit: April 11, 2021, 12:56:13 am by G. »

Stauricus

  • Sr. Member
  • ****
  • Posts: 369
    • View Profile
    • A Mafia Graphic Novel
    • Email
Re: Is there a better way to draw multiple points
« Reply #2 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?
Visit my game site (and hopefully help funding it? )
Website | IndieDB