As an exercise, I've decided to try my hand at gradients using SFML. To truly make this a learning experience, I didn't look at any resources or papers that described an algorithm for doing so; I wanted to roll my own algorithm. I'm very pleased with the design and how the image turned out. I have a couple specific questions about this, which include:

• I've used a VertexArray to store all the pixels. Is there a more efficient way to do this?
• Is there any way to optimize the MapToColor function? It's essentially five lines of code, but I don't know all the niche C++ optimizations that are available.

Also, please excuse the overbearing comments in my code. I was writing them to remind myself why I made algorithm decisions.

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <iostream>

#define WIDTH 1920
#define HEIGHT 1080
#define PIXELS WIDTH * HEIGHT

#define min(a, b) a < b ? a : b

/**
* @brief For some reason C++ doesn't have a map function, so this is the
* version written for Arudino.
* https://www.arduino.cc/reference/en/language/functions/math/map/
*/
float map(float x, float in_min, float in_max, float out_min, float out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

sf::Color MapToColor(const int& x, const int& y) {

// Map our current pixel position to a [0, 255] range so we can work with
// it as RGB colors.
float v = map(x + y, 0, PIXELS, 0, 255);

// v will increase as we get farther into the points, so we can use this
// as to slowly decrease the red so we can fade into orange/green.
int r = 255 - v;

// Adding padding here to show a display the transition to orange and green
// Without this, red encompases a large part of the screen. We use min() in
// addition to the padding because when padding is 255 / 4 or larger, we get
// a purple line at the bottom of the screen that grows as PADDING grows.
// For original color, int g = v;
int g = min(255, v + PADDING);

// Because green is growing as red decreases, we only add blue when green is
// less than red, which allows a nice transition into cyan.
int b = g > r ? (g - r) : 0;

return sf::Color(r, g, b);

}

int main() {

sf::VertexArray points(sf::Points, PIXELS);

int j = 0;
for (int i = 0; i < PIXELS; i++) {
points[i].color = MapToColor(i, j);
points[i].position = sf::Vector2f(i % WIDTH, j);
j += (i % WIDTH == 0);
}

while (window.isOpen()) {

sf::Event event;

while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}

window.clear(sf::Color::Black);

window.draw(points);

window.display();

}

return 0;

}


Result of running the above code: