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.

98 lines
2.2KB

  1. #pragma once
  2. #include "common.hpp"
  3. #include "string.hpp"
  4. #include "nanovg.h"
  5. namespace rack {
  6. namespace color {
  7. static const NVGcolor BLACK_TRANSPARENT = nvgRGBA(0x00, 0x00, 0x00, 0x00);
  8. static const NVGcolor BLACK = nvgRGB(0x00, 0x00, 0x00);
  9. static const NVGcolor WHITE = nvgRGB(0xff, 0xff, 0xff);
  10. static const NVGcolor WHITE_TRANSPARENT = nvgRGB(0xff, 0xff, 0xff);
  11. static const NVGcolor RED = nvgRGB(0xff, 0x00, 0x00);
  12. static const NVGcolor GREEN = nvgRGB(0x00, 0xff, 0x00);
  13. static const NVGcolor BLUE = nvgRGB(0x00, 0x00, 0xff);
  14. static const NVGcolor YELLOW = nvgRGB(0xff, 0xff, 0x00);
  15. static const NVGcolor MAGENTA = nvgRGB(0xff, 0x00, 0xff);
  16. static const NVGcolor CYAN = nvgRGB(0x00, 0xff, 0xff);
  17. inline NVGcolor clip(NVGcolor a) {
  18. for (int i = 0; i < 4; i++)
  19. a.rgba[i] = math::clamp(a.rgba[i], 0.f, 1.f);
  20. return a;
  21. }
  22. inline NVGcolor minus(NVGcolor a, NVGcolor b) {
  23. for (int i = 0; i < 3; i++)
  24. a.rgba[i] -= b.rgba[i];
  25. return a;
  26. }
  27. inline NVGcolor plus(NVGcolor a, NVGcolor b) {
  28. for (int i = 0; i < 3; i++)
  29. a.rgba[i] += b.rgba[i];
  30. return a;
  31. }
  32. inline NVGcolor mult(NVGcolor a, NVGcolor b) {
  33. for (int i = 0; i < 3; i++)
  34. a.rgba[i] *= b.rgba[i];
  35. return a;
  36. }
  37. inline NVGcolor mult(NVGcolor a, float x) {
  38. for (int i = 0; i < 3; i++)
  39. a.rgba[i] *= x;
  40. return a;
  41. }
  42. /** Screen blending with alpha compositing */
  43. inline NVGcolor screen(NVGcolor a, NVGcolor b) {
  44. if (a.a == 0.0)
  45. return b;
  46. if (b.a == 0.0)
  47. return a;
  48. a = mult(a, a.a);
  49. b = mult(b, b.a);
  50. NVGcolor c = minus(plus(a, b), mult(a, b));
  51. c.a = a.a + b.a - a.a * b.a;
  52. c = mult(c, 1.f / c.a);
  53. c = clip(c);
  54. return c;
  55. }
  56. inline NVGcolor alpha(NVGcolor a, float alpha) {
  57. a.a *= alpha;
  58. return a;
  59. }
  60. inline NVGcolor fromHexString(std::string s) {
  61. uint8_t r = 0;
  62. uint8_t g = 0;
  63. uint8_t b = 0;
  64. uint8_t a = 255;
  65. sscanf(s.c_str(), "#%2hhx%2hhx%2hhx%2hhx", &r, &g, &b, &a);
  66. return nvgRGBA(r, g, b, a);
  67. }
  68. inline std::string toHexString(NVGcolor c) {
  69. uint8_t r = std::round(c.r * 255);
  70. uint8_t g = std::round(c.g * 255);
  71. uint8_t b = std::round(c.b * 255);
  72. uint8_t a = std::round(c.a * 255);
  73. if (a == 255)
  74. return string::stringf("#%02x%02x%02x", r, g, b);
  75. else
  76. return string::stringf("#%02x%02x%02x%02x", r, g, b, a);
  77. }
  78. } // namespace color
  79. } // namespace rack