Skip to content

Instantly share code, notes, and snippets.

@mcspr
Last active August 20, 2019 14:17
Show Gist options
  • Save mcspr/4a0a7001c9b52c0dd09ca1af13b287c5 to your computer and use it in GitHub Desktop.
Save mcspr/4a0a7001c9b52c0dd09ca1af13b287c5 to your computer and use it in GitHub Desktop.
HSV test
$ g++ -std=c++17 -o hsv hsv.cpp
$ ./hsv 2,100,59
brightness=0, rgb=0,0,0
input=2,100,59
_setRGBInputValue(255,8,0)
brightness=150, rgb=255,8,0
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
constexpr unsigned char LIGHT_MIN_VALUE = 0;
constexpr unsigned char LIGHT_MAX_VALUE = 255;
unsigned char red = 0;
unsigned char green = 0;
unsigned char blue = 0;
unsigned char _light_brightness = 0;
void dump() {
std::cout
<< "brightness="<< int(_light_brightness)
<< ", " << "rgb="
<< int(std::clamp(red, LIGHT_MIN_VALUE, LIGHT_MAX_VALUE))
<< "," << int(std::clamp(green, LIGHT_MIN_VALUE, LIGHT_MAX_VALUE))
<< "," << int(std::clamp(blue, LIGHT_MIN_VALUE, LIGHT_MAX_VALUE))
<< std::endl;
}
void _setRGBInputValue(unsigned char _red, unsigned char _green, unsigned char _blue) {
red = _red; green = _green; blue = _blue;
std::cout << "_setRGBInputValue(";
std::cout << int(std::clamp(red, LIGHT_MIN_VALUE, LIGHT_MAX_VALUE)) << ",";
std::cout << int(std::clamp(green, LIGHT_MIN_VALUE, LIGHT_MAX_VALUE)) << ",";
std::cout << int(std::clamp(blue, LIGHT_MIN_VALUE, LIGHT_MAX_VALUE));
std::cout << ")" << std::endl;
}
void _fromHSV(const char * hsv) {
std::string str(hsv);
std::cout << "input=" << str << std::endl;
if (!str.length()) return;
unsigned char value[3] = {0,0,0};
unsigned char idx = 0;
unsigned char pos = 0;
do {
if (!str.length()) break;
pos = str.find(',');
if (pos == std::string::npos) break;
value[idx++] = std::stoi(str.substr(0, pos));
str.erase(0, pos + 1);
} while(pos != std::string::npos);
if (idx != 3) return;
// HSV to RGB transformation -----------------------------------------------
//INPUT: [0,100,57]
//IS: [145,0,0]
//SHOULD: [255,0,0]
double h = (value[0] == 360) ? 0 : (double) value[0] / 60.0;
double f = (h - std::floor(h));
double s = (double) value[1] / 100.0;
_light_brightness = std::round((double) value[2] * 2.55); // (255/100)
unsigned char p = std::lround(255 * (1.0 - s));
unsigned char q = std::lround(255 * (1.0 - s * f));
unsigned char t = std::lround(255 * (1.0 - s * (1.0 - f)));
switch (int(h)) {
case 0:
_setRGBInputValue(255, t, p);
break;
case 1:
_setRGBInputValue(q, 255, p);
break;
case 2:
_setRGBInputValue(p, 255, t);
break;
case 3:
_setRGBInputValue(p, q, 255);
break;
case 4:
_setRGBInputValue(t, p, 255);
break;
case 5:
_setRGBInputValue(255, p, q);
break;
default:
_setRGBInputValue(0, 0, 0);
break;
}
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "[prog] [h,s,v string]" << std::endl;
std::terminate();
}
dump();
_fromHSV(argv[1]);
dump();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment