You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

color.cpp 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include <color.hpp>
  2. #include <math.hpp>
  3. namespace rack {
  4. namespace color {
  5. bool isEqual(NVGcolor a, NVGcolor b) {
  6. for (int i = 0; i < 4; i++) {
  7. if (a.rgba[i] != b.rgba[i])
  8. return false;
  9. }
  10. return true;
  11. }
  12. NVGcolor clamp(NVGcolor a) {
  13. for (int i = 0; i < 4; i++)
  14. a.rgba[i] = math::clamp(a.rgba[i], 0.f, 1.f);
  15. return a;
  16. }
  17. NVGcolor minus(NVGcolor a, NVGcolor b) {
  18. for (int i = 0; i < 3; i++)
  19. a.rgba[i] -= b.rgba[i];
  20. return a;
  21. }
  22. NVGcolor plus(NVGcolor a, NVGcolor b) {
  23. for (int i = 0; i < 3; i++)
  24. a.rgba[i] += b.rgba[i];
  25. return a;
  26. }
  27. NVGcolor mult(NVGcolor a, NVGcolor b) {
  28. for (int i = 0; i < 3; i++)
  29. a.rgba[i] *= b.rgba[i];
  30. return a;
  31. }
  32. NVGcolor mult(NVGcolor a, float x) {
  33. for (int i = 0; i < 3; i++)
  34. a.rgba[i] *= x;
  35. return a;
  36. }
  37. /** Screen blending with alpha compositing */
  38. NVGcolor screen(NVGcolor a, NVGcolor b) {
  39. if (a.a == 0.f)
  40. return b;
  41. if (b.a == 0.f)
  42. return a;
  43. a = mult(a, a.a);
  44. b = mult(b, b.a);
  45. NVGcolor c = minus(plus(a, b), mult(a, b));
  46. c.a = a.a + b.a - a.a * b.a;
  47. c = mult(c, 1.f / c.a);
  48. c = clamp(c);
  49. return c;
  50. }
  51. NVGcolor alpha(NVGcolor a, float alpha) {
  52. a.a *= alpha;
  53. return a;
  54. }
  55. NVGcolor fromHexString(std::string s) {
  56. uint8_t r = 0;
  57. uint8_t g = 0;
  58. uint8_t b = 0;
  59. uint8_t a = 255;
  60. // If only three hex pairs are given, this will leave `a` unset.
  61. sscanf(s.c_str(), "#%2hhx%2hhx%2hhx%2hhx", &r, &g, &b, &a);
  62. return nvgRGBA(r, g, b, a);
  63. }
  64. std::string toHexString(NVGcolor c) {
  65. uint8_t r = std::round(c.r * 255);
  66. uint8_t g = std::round(c.g * 255);
  67. uint8_t b = std::round(c.b * 255);
  68. uint8_t a = std::round(c.a * 255);
  69. if (a == 255)
  70. return string::f("#%02x%02x%02x", r, g, b);
  71. else
  72. return string::f("#%02x%02x%02x%02x", r, g, b, a);
  73. }
  74. } // namespace network
  75. } // namespace rack