summaryrefslogtreecommitdiff
path: root/include/mbgl/util/color.hpp
blob: 178d0dc758669d843c234daabfd8f36390dd881d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#pragma once

#include <mbgl/util/optional.hpp>

#include <cassert>
#include <string>

namespace mbgl {

// Stores a premultiplied color, with all four channels ranging from 0..1
class Color {
public:
    constexpr Color() = default;
    constexpr Color(float r_, float g_, float b_, float a_)
        : r(r_), g(g_), b(b_), a(a_) {
        assert(r_ >= 0.0f);
        assert(r_ <= 1.0f);
        assert(g_ >= 0.0f);
        assert(g_ <= 1.0f);
        assert(b_ >= 0.0f);
        assert(b_ <= 1.0f);
        assert(a_ >= 0.0f);
        assert(a_ <= 1.0f);
    }

    float r = 0.0f;
    float g = 0.0f;
    float b = 0.0f;
    float a = 0.0f;

    static constexpr Color black() { return { 0.0f, 0.0f, 0.0f, 1.0f }; };
    static constexpr Color white() { return { 1.0f, 1.0f, 1.0f, 1.0f }; };

    static constexpr Color red()   { return { 1.0f, 0.0f, 0.0f, 1.0f }; };
    static constexpr Color green() { return { 0.0f, 1.0f, 0.0f, 1.0f }; };
    static constexpr Color blue()  { return { 0.0f, 0.0f, 1.0f, 1.0f }; };

    static optional<Color> parse(const std::string&);
};

constexpr bool operator==(const Color& colorA, const Color& colorB) {
    return colorA.r == colorB.r && colorA.g == colorB.g && colorA.b == colorB.b && colorA.a == colorB.a;
}

constexpr bool operator!=(const Color& colorA, const Color& colorB) {
    return !(colorA == colorB);
}

constexpr Color operator*(const Color& color, float alpha) {
    assert(alpha >= 0.0f);
    assert(alpha <= 1.0f);
    return {
        color.r * alpha,
        color.g * alpha,
        color.b * alpha,
        color.a * alpha
    };
}

} // namespace mbgl