1// LAF Gfx Library
2// Copyright (C) 2001-2017 David Capello
3//
4// This file is released under the terms of the MIT license.
5// Read LICENSE.txt for more information.
6
7#include "gfx/rgb.h"
8
9#include "gfx/hsl.h"
10#include "gfx/hsv.h"
11#include <cmath>
12
13namespace gfx {
14
15using namespace std;
16
17// Reference: http://en.wikipedia.org/wiki/HSL_and_HSV
18Rgb::Rgb(const Hsv& hsv)
19{
20 double chroma = hsv.value() * hsv.saturation();
21 double hue_prime = hsv.hue() / 60.0;
22 double x = chroma * (1.0 - std::fabs(std::fmod(hue_prime, 2.0) - 1.0));
23 double r, g, b;
24
25 r = g = b = 0.0;
26
27 switch (int(hue_prime)) {
28
29 case 6:
30 case 0:
31 r = chroma;
32 g = x;
33 break;
34 case 1:
35 r = x;
36 g = chroma;
37 break;
38
39 case 2:
40 g = chroma;
41 b = x;
42 break;
43 case 3:
44 g = x;
45 b = chroma;
46 break;
47
48 case 4:
49 b = chroma;
50 r = x;
51 break;
52 case 5:
53 b = x;
54 r = chroma;
55 break;
56 }
57
58 double m = hsv.value() - chroma;
59 r += m;
60 g += m;
61 b += m;
62
63 m_red = int(r*255.0+0.5);
64 m_green = int(g*255.0+0.5);
65 m_blue = int(b*255.0+0.5);
66}
67
68Rgb::Rgb(const Hsl& hsl)
69{
70 double chroma = (1.0 - std::fabs(2.0*hsl.lightness() - 1.0)) * hsl.saturation();
71 double hue_prime = hsl.hue() / 60.0;
72 double x = chroma * (1.0 - std::fabs(std::fmod(hue_prime, 2.0) - 1.0));
73 double r, g, b;
74
75 r = g = b = 0.0;
76
77 switch (int(hue_prime)) {
78
79 case 6:
80 case 0:
81 r = chroma;
82 g = x;
83 break;
84 case 1:
85 r = x;
86 g = chroma;
87 break;
88
89 case 2:
90 g = chroma;
91 b = x;
92 break;
93 case 3:
94 g = x;
95 b = chroma;
96 break;
97
98 case 4:
99 b = chroma;
100 r = x;
101 break;
102 case 5:
103 b = x;
104 r = chroma;
105 break;
106 }
107
108 double m = hsl.lightness() - chroma/2.0;
109 r += m;
110 g += m;
111 b += m;
112
113 m_red = int(r*255.0+0.5);
114 m_green = int(g*255.0+0.5);
115 m_blue = int(b*255.0+0.5);
116}
117
118int Rgb::maxComponent() const
119{
120 if (m_red > m_green)
121 return (m_red > m_blue) ? m_red: m_blue;
122 else
123 return (m_green > m_blue) ? m_green: m_blue;
124}
125
126int Rgb::minComponent() const
127{
128 if (m_red < m_green)
129 return (m_red < m_blue) ? m_red: m_blue;
130 else
131 return (m_green < m_blue) ? m_green: m_blue;
132}
133
134} // namespace gfx
135