Skip to content

Commit c7020b1

Browse files
committed
Add u8 channel retrieval methods and equality operator for Rgb class
1 parent 4f86100 commit c7020b1

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/jngl/Rgb.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
#include "Color.hpp"
66

7+
#include <cmath>
8+
#include <iostream>
9+
710
namespace jngl {
811

912
Rgb::Rgb(float red, float green, float blue) : red(red), green(green), blue(blue) {
@@ -44,6 +47,18 @@ void Rgb::setBlue(const float blue) {
4447
this->blue = blue;
4548
}
4649

50+
uint8_t Rgb::getRed_u8() const {
51+
return static_cast<uint8_t>(std::lround(red * 255.f));
52+
}
53+
54+
uint8_t Rgb::getGreen_u8() const {
55+
return static_cast<uint8_t>(std::lround(green * 255.f));
56+
}
57+
58+
uint8_t Rgb::getBlue_u8() const {
59+
return static_cast<uint8_t>(std::lround(blue * 255.f));
60+
}
61+
4762
Rgb::operator Color() const {
4863
return Color{ static_cast<unsigned char>(red * 255), static_cast<unsigned char>(green * 255),
4964
static_cast<unsigned char>(blue * 255) };
@@ -54,6 +69,16 @@ Rgb interpolate(Rgb a, Rgb b, float t) {
5469
a.getBlue() * (1.f - t) + b.getBlue() * t };
5570
}
5671

72+
bool operator==(Rgb a, Rgb b) {
73+
return a.getRed_u8() == b.getRed_u8() && a.getGreen_u8() == b.getGreen_u8() &&
74+
a.getBlue_u8() == b.getBlue_u8();
75+
}
76+
77+
std::ostream& operator<<(std::ostream& os, Rgb color) {
78+
os << "jngl::Rgb{ " << color.getRed() << ", " << color.getGreen() << ", " << color.getBlue() << " }";
79+
return os;
80+
}
81+
5782
} // namespace jngl
5883

5984
jngl::Rgb operator""_rgb(const unsigned long long hex) {

src/jngl/Rgb.hpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#pragma once
66

77
#include <cstdint>
8+
#include <iosfwd>
89

910
namespace jngl {
1011

@@ -41,6 +42,15 @@ class Rgb {
4142
/// 0.0f ... 1.0f
4243
void setBlue(float);
4344

45+
/// 0 ... 255
46+
uint8_t getRed_u8() const;
47+
48+
/// 0 ... 255
49+
uint8_t getGreen_u8() const;
50+
51+
/// 0 ... 255
52+
uint8_t getBlue_u8() const;
53+
4454
/// Conversion for backwards compatibility
4555
explicit operator Color() const;
4656

@@ -53,6 +63,13 @@ class Rgb {
5363
/// Returns a color mix between a (t == 0) and b (t == 1)
5464
Rgb interpolate(Rgb a, Rgb b, float t);
5565

66+
/// Returns true if the two colors are equal in 24 bit SDR space, i.e. each channel rounded to
67+
/// uint8_t
68+
bool operator==(Rgb a, Rgb b);
69+
70+
/// Prints the color as `jngl::Rgb{ red, green, blue }`
71+
std::ostream& operator<<(std::ostream& os, Rgb color);
72+
5673
} // namespace jngl
5774

5875
/// Create a jngl::Rgb object from a literal. E.g. `0x00ff00_rgb` for green.

0 commit comments

Comments
 (0)