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.6KB

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