Inkscape
Vector Graphics Editor
Loading...
Searching...
No Matches
hsl.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: GPL-2.0-or-later
/*
4 * Authors: see git history
5 *
6 * Copyright (C) 2023 Authors
7 * Released under GNU GPL v2+, read the file 'COPYING' for more information.
8 */
9
10#include "hsl.h"
11
12#include <cmath>
13
14#include "colors/color.h"
15#include "colors/printer.h"
16
18
19static float hue_2_rgb(float v1, float v2, float h)
20{
21 if (h < 0)
22 h += 6.0;
23 if (h > 6)
24 h -= 6.0;
25 if (h < 1)
26 return v1 + (v2 - v1) * h;
27 if (h < 3)
28 return v2;
29 if (h < 4)
30 return v1 + (v2 - v1) * (4 - h);
31 return v1;
32}
33
37void HSL::spaceToProfile(std::vector<double> &output) const
38{
39 double h = output[0];
40 double s = output[1];
41 double l = output[2];
42
43 if (s == 0) { // Gray
44 output[0] = l;
45 output[1] = l;
46 output[2] = l;
47 } else {
48 double v2;
49 if (l < 0.5) {
50 v2 = l * (1 + s);
51 } else {
52 v2 = l + s - l * s;
53 }
54 double v1 = 2 * l - v2;
55
56 output[0] = hue_2_rgb(v1, v2, h * 6 + 2.0);
57 output[1] = hue_2_rgb(v1, v2, h * 6);
58 output[2] = hue_2_rgb(v1, v2, h * 6 - 2.0);
59 }
60}
61
65void HSL::profileToSpace(std::vector<double> &output) const
66{
67 double r = output[0];
68 double g = output[1];
69 double b = output[2];
70
71 double max = std::max(std::max(r, g), b);
72 double min = std::min(std::min(r, g), b);
73 double delta = max - min;
74
75 double h = 0;
76 double s = 0;
77 double l = (max + min) / 2.0;
78
79 if (delta != 0) {
80 if (l <= 0.5)
81 s = delta / (max + min);
82 else
83 s = delta / (2 - max - min);
84
85 if (r == max)
86 h = (g - b) / delta;
87 else if (g == max)
88 h = 2.0 + (b - r) / delta;
89 else if (b == max)
90 h = 4.0 + (r - g) / delta;
91
92 h = h / 6.0;
93
94 if (h < 0)
95 h += 1;
96 if (h > 1)
97 h -= 1;
98 }
99 output[0] = h;
100 output[1] = s;
101 output[2] = l;
102}
103
110std::string HSL::toString(std::vector<double> const &values, bool opacity) const
111{
112 auto oo = CssLegacyPrinter(3, "hsl", opacity && values.size() == 4);
113 // First entry is Hue, which is in degrees
114 return oo << (int)(values[0] * 360) << values[1] << values[2] << values.back();
115}
116
117}; // namespace Inkscape::Colors::Space
std::string toString(std::vector< double > const &values, bool opacity=true) const override
Print the HSL color to a CSS string.
Definition hsl.cpp:110
void spaceToProfile(std::vector< double > &output) const override
Convert the HSL color into sRGB components used in the sRGB icc profile.
Definition hsl.cpp:37
void profileToSpace(std::vector< double > &output) const override
Convert from sRGB icc values to HSL values.
Definition hsl.cpp:65
static float hue_2_rgb(float v1, float v2, float h)
Definition hsl.cpp:19
int delta