FTXUI 7.0.3
C++ functional terminal UI.
Loading...
Searching...
No Matches
src/ftxui/dom/linear_gradient.cpp
Go to the documentation of this file.
1// Copyright 2023 Arthur Sonzogni. All rights reserved.
2// Use of this source code is governed by the MIT license that can be found in
3// the LICENSE file.
4#include <algorithm> // for max, min, sort, copy
5#include <cmath> // for fmod, cos, sin
6#include <cstddef> // for size_t
7#include <ftxui/dom/linear_gradient.hpp> // for LinearGradient::Stop, LinearGradient
8#include <memory> // for allocator_traits<>::value_type, make_shared
9#include <optional> // for optional, operator!=, operator<
10#include <utility> // for move
11#include <vector> // for vector
12
13#include "ftxui/dom/elements.hpp" // for Element, Decorator, bgcolor, color
14#include "ftxui/dom/node_decorator.hpp" // for NodeDecorator
15#include "ftxui/screen/box.hpp" // for Box
16#include "ftxui/screen/color.hpp" // for Color, Color::Default, Color::Blue
17#include "ftxui/screen/screen.hpp" // for Cell, Screen
18
19namespace ftxui {
20namespace {
21
22struct LinearGradientNormalized {
23 float angle = 0.F;
24 std::vector<Color> colors;
25 std::vector<float> positions; // Trié.
26};
27
28// Convertit un LinearGradient en une version normalisée.
29LinearGradientNormalized Normalize(LinearGradient gradient) {
30 // Gère les dégradés de taille 0.
31 if (gradient.stops.empty()) {
32 return LinearGradientNormalized{
33 0.F,
34 {Color::Default, Color::Default},
35 {0.F, 1.F},
36 };
37 }
38
39 // Remplit les deux étendues, si non fournies.
40 if (!gradient.stops.front().position) {
41 gradient.stops.front().position = 0.F;
42 }
43 if (!gradient.stops.back().position) {
44 gradient.stops.back().position = 1.F;
45 }
46
47 // Remplit les blancs, en interpolant les positions.
48 size_t last_checkpoint = 0;
49 for (size_t i = 1; i < gradient.stops.size(); ++i) {
50 if (!gradient.stops[i].position) {
51 continue;
52 }
53
54 if (i - last_checkpoint >= 2) {
55 const float min = gradient.stops[i].position.value(); // NOLINT
56 const float max =
57 gradient.stops[last_checkpoint].position.value(); // NOLINT
58 for (size_t j = last_checkpoint + 1; j < i; ++j) {
59 gradient.stops[j].position = min + (max - min) *
60 float(j - last_checkpoint) /
61 float(i - last_checkpoint);
62 }
63 }
64
65 last_checkpoint = i;
66 }
67
68 // Trie les arrêts par position.
69 std::sort(
70 gradient.stops.begin(), gradient.stops.end(),
71 [](const auto& a, const auto& b) { return a.position < b.position; });
72
73 // Si on ne commence pas à zéro, ajoute un arrêt à zéro.
74 if (gradient.stops.front().position != 0) {
75 gradient.stops.insert(gradient.stops.begin(),
76 {gradient.stops.front().color, 0.F});
77 }
78 // Si on ne termine pas à un, ajoute un arrêt à un.
79 if (gradient.stops.back().position != 1) {
80 gradient.stops.push_back({gradient.stops.back().color, 1.F});
81 }
82
83 // Normalise l'angle.
84 LinearGradientNormalized normalized;
85 const float modulo = 360.F;
86 normalized.angle =
87 std::fmod(std::fmod(gradient.angle, modulo) + modulo, modulo);
88 for (auto& stop : gradient.stops) {
89 normalized.colors.push_back(stop.color);
90 // NOLINTNEXTLINE
91 normalized.positions.push_back(stop.position.value());
92 }
93 return normalized;
94}
95
96Color Interpolate(const LinearGradientNormalized& gradient, float t) {
97 // Trouve la bonne couleur dans les arrêts du dégradé.
98 size_t i = 1;
99 while (true) {
100 // Notez que `t` peut être légèrement supérieur à 1.0 en raison de la précision des nombres flottants.
101 // C'est pourquoi nous devons gérer le cas où `t` est supérieur à la position du dernier arrêt.
102 // Voir https://github.com/ArthurSonzogni/FTXUI/issues/998 if (i >= gradient.positions.size()) {
103 if (i >= gradient.positions.size()) {
104 const float half = 0.5F;
105 return Color::Interpolate(half, gradient.colors.back(),
106 gradient.colors.back());
107 }
108 if (t <= gradient.positions[i]) {
109 break;
110 }
111 ++i;
112 }
113
114 const float t0 = gradient.positions[i - 1];
115 const float t1 = gradient.positions[i - 0];
116 const float tt = (t - t0) / (t1 - t0);
117
118 const Color& c0 = gradient.colors[i - 1];
119 const Color& c1 = gradient.colors[i - 0];
120 const Color& cc = Color::Interpolate(tt, c0, c1);
121
122 return cc;
123}
124
125class LinearGradientColor : public NodeDecorator {
126 public:
127 explicit LinearGradientColor(Element child,
128 const LinearGradient& gradient,
129 bool background_color)
130 : NodeDecorator(std::move(child)),
131 gradient_(Normalize(gradient)),
132 background_color_{background_color} {}
133
134 private:
135 void Render(Screen& screen) override {
136 const float degtorad = 0.01745329251F;
137 const float dx = std::cos(gradient_.angle * degtorad);
138 const float dy = std::sin(gradient_.angle * degtorad);
139
140 // Projeter chaque coin pour obtenir l'étendue du dégradé.
141 const float p1 = float(box_.x_min) * dx + float(box_.y_min) * dy;
142 const float p2 = float(box_.x_min) * dx + float(box_.y_max) * dy;
143 const float p3 = float(box_.x_max) * dx + float(box_.y_min) * dy;
144 const float p4 = float(box_.x_max) * dx + float(box_.y_max) * dy;
145 const float min = std::min({p1, p2, p3, p4});
146 const float max = std::max({p1, p2, p3, p4});
147
148 // Renormaliser la projection à [0, 1] en utilisant l'étendue et la géométrie projective. const float dX = dx / (max - min);
149 const float dX = dx / (max - min);
150 const float dY = dy / (max - min);
151 const float dZ = -min / (max - min);
152
153 // Projeter chaque pixel pour obtenir la couleur.
154 if (background_color_) {
155 for (int y = box_.y_min; y <= box_.y_max; ++y) {
156 for (int x = box_.x_min; x <= box_.x_max; ++x) {
157 const float t = float(x) * dX + float(y) * dY + dZ;
158 screen.CellAt(x, y).background_color = Interpolate(gradient_, t);
159 }
160 }
161 } else {
162 for (int y = box_.y_min; y <= box_.y_max; ++y) {
163 for (int x = box_.x_min; x <= box_.x_max; ++x) {
164 const float t = float(x) * dX + float(y) * dY + dZ;
165 screen.CellAt(x, y).foreground_color = Interpolate(gradient_, t);
166 }
167 }
168 }
169
170 NodeDecorator::Render(screen);
171 }
172
173 LinearGradientNormalized gradient_;
174 bool background_color_;
175};
176
177} // namespace
178
179/// @brief Construit le dégradé "vide". Ceci est souvent suivi d'appels à
180/// LinearGradient::Angle() et LinearGradient::Stop().
181/// Exemple:
182/// ```cpp
183/// auto gradient =
184/// LinearGradient()
185/// .Angle(45)
186/// .Stop(Color::Red, 0.0)
187/// .Stop(Color::Green, 0.5)
188/// .Stop(Color::Blue, 1.0);;
189/// ```
190LinearGradient::LinearGradient() = default;
191
192/// @brief Construit un dégradé avec deux couleurs.
193/// @param begin La couleur au début du dégradé.
194/// @param end La couleur à la fin du dégradé.
195LinearGradient::LinearGradient(Color begin, Color end)
196 : LinearGradient(0, begin, end) {}
197
198/// @brief Construit un dégradé avec deux couleurs et un angle.
199/// @param a L'angle du dégradé.
200/// @param begin La couleur au début du dégradé.
201/// @param end La couleur à la fin du dégradé.
202LinearGradient::LinearGradient(float a, Color begin, Color end) : angle(a) {
203 stops.push_back({begin, {}});
204 stops.push_back({end, {}});
205}
206
207/// @brief Définit l'angle du dégradé.
208/// @param a L'angle du dégradé.
209/// @return Le dégradé.
210LinearGradient& LinearGradient::Angle(float a) {
211 angle = a;
212 return *this;
213}
214
215/// @brief Ajoute un arrêt de couleur au dégradé.
216/// @param c La couleur de l'arrêt.
217/// @param p La position de l'arrêt.
218LinearGradient& LinearGradient::Stop(Color c, float p) {
219 stops.push_back({c, p});
220 return *this;
221}
222
223/// @brief Ajoute un arrêt de couleur au dégradé.
224/// @param c La couleur de l'arrêt.
225/// @return Le dégradé.
226/// @note La position de l'arrêt est interpolée à partir des arrêts voisins.
227LinearGradient& LinearGradient::Stop(Color c) {
228 stops.push_back({c, {}});
229 return *this;
230}
231
232/// @brief Définit la couleur de premier plan d'un élément avec un effet de dégradé linéaire.
233/// @param gradient L'effet de dégradé à appliquer sur l'élément de sortie.
234/// @param child L'élément d'entrée.
235/// @return L'élément de sortie coloré.
236/// @ingroup dom
237///
238/// ### Exemple
239///
240/// ```cpp
241/// color(LinearGradient{0, {Color::Red, Color::Blue}}, text("Hello"))
242/// ```
243Element color(const LinearGradient& gradient, Element child) {
244 return std::make_shared<LinearGradientColor>(std::move(child), gradient,
245 /*background_color*/ false);
246}
247
248/// @brief Définit la couleur de fond d'un élément avec un effet de dégradé linéaire.
249/// @param gradient L'effet de dégradé à appliquer sur l'élément de sortie.
250/// @param child L'élément d'entrée.
251/// @return L'élément de sortie coloré.
252/// @ingroup dom
253///
254/// ### Exemple
255///
256/// ```cpp
257/// bgcolor(LinearGradient{0, {Color::Red, Color::Blue}}, text("Hello"))
258/// ```
259Element bgcolor(const LinearGradient& gradient, Element child) {
260 return std::make_shared<LinearGradientColor>(std::move(child), gradient,
261 /*background_color*/ true);
262}
263
264/// @brief Décore en utilisant un effet de dégradé linéaire sur la couleur de premier plan.
265/// @param gradient L'effet de dégradé à appliquer sur l'élément de sortie.
266/// @return Le Decorator appliquant la couleur.
267/// @ingroup dom
268///
269/// ### Exemple
270///
271/// ```cpp
272/// text("Hello") | color(LinearGradient{0, {Color::Red, Color::Blue}})
273/// ```
274Decorator color(const LinearGradient& gradient) {
275 return
276 [gradient](Element child) { return color(gradient, std::move(child)); };
277}
278
279/// @brief Décore en utilisant un effet de dégradé linéaire sur la couleur de fond.
280/// @param gradient L'effet de dégradé à appliquer sur l'élément de sortie.
281/// @return Le Decorator appliquant la couleur.
282/// @ingroup dom
283///
284/// ### Exemple
285///
286/// ```cpp
287/// text("Hello") | color(LinearGradient{0, {Color::Red, Color::Blue}})
288/// ```
289Decorator bgcolor(const LinearGradient& gradient) {
290 return
291 [gradient](Element child) { return bgcolor(gradient, std::move(child)); };
292}
293
294} // namespace ftxui
Element bgcolor(Color color, Element child)
Définit la couleur d'arrière-plan d'un élément.
Definition dom/color.cpp:96
Element color(Color color, Element child)
Définit la couleur de premier plan d'un élément.
Definition dom/color.cpp:81
L'espace de noms FTXUI ftxui::
Definition animation.hpp:11
std::shared_ptr< Node > Element
Definition elements.hpp:25
std::function< Element(Element)> Decorator
Definition elements.hpp:27
int y
Definition elements.hpp:134
void Render(Screen &screen, Node *node, Selection &selection)
Definition node.cpp:105
std::vector< Color > colors
std::vector< float > positions