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.

99 lines
1.9KB

  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. NVGcolor lerp(NVGcolor a, NVGcolor b, float t) {
  38. NVGcolor c;
  39. for (int i = 0; i < 4; i++)
  40. c.rgba[i] = a.rgba[i] * (1 - t) + b.rgba[i] * t;
  41. return c;
  42. }
  43. /** Screen blending with alpha compositing */
  44. NVGcolor screen(NVGcolor a, NVGcolor b) {
  45. if (a.a == 0.f)
  46. return b;
  47. if (b.a == 0.f)
  48. return a;
  49. a = mult(a, a.a);
  50. b = mult(b, b.a);
  51. NVGcolor c = minus(plus(a, b), mult(a, b));
  52. c.a = a.a + b.a - a.a * b.a;
  53. c = mult(c, 1.f / c.a);
  54. c = clamp(c);
  55. return c;
  56. }
  57. NVGcolor alpha(NVGcolor a, float alpha) {
  58. a.a *= alpha;
  59. return a;
  60. }
  61. NVGcolor fromHexString(std::string s) {
  62. uint8_t r = 0;
  63. uint8_t g = 0;
  64. uint8_t b = 0;
  65. uint8_t a = 255;
  66. // If only three hex pairs are given, this will leave `a` unset.
  67. sscanf(s.c_str(), "#%2hhx%2hhx%2hhx%2hhx", &r, &g, &b, &a);
  68. return nvgRGBA(r, g, b, a);
  69. }
  70. std::string toHexString(NVGcolor c) {
  71. uint8_t r = std::round(c.r * 255);
  72. uint8_t g = std::round(c.g * 255);
  73. uint8_t b = std::round(c.b * 255);
  74. uint8_t a = std::round(c.a * 255);
  75. if (a == 255)
  76. return string::f("#%02x%02x%02x", r, g, b);
  77. else
  78. return string::f("#%02x%02x%02x%02x", r, g, b, a);
  79. }
  80. } // namespace network
  81. } // namespace rack