Fork of the espurna firmware for `mhsw` switches
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.

87 lines
2.6 KiB

  1. /*
  2. Part of the GARLAND MODULE
  3. Copyright (C) 2020 by Dmitry Blinov <dblinov76 at gmail dot com>
  4. Inspired by https://github.com/Vasil-Pahomov/ArWs2812 (currently https://github.com/Vasil-Pahomov/Liana)
  5. */
  6. #pragma once
  7. #if GARLAND_SUPPORT
  8. #include <Arduino.h>
  9. struct Color
  10. {
  11. byte r;
  12. byte g;
  13. byte b;
  14. inline Color() : r(0), g(0), b(0) {}
  15. // allow construction from R, G, B
  16. inline Color(uint8_t ir, uint8_t ig, uint8_t ib)
  17. : r(ir), g(ig), b(ib) {
  18. }
  19. // allow construction from 32-bit (really 24-bit) bit 0xRRGGBB color code
  20. inline Color(uint32_t colorcode)
  21. : r((colorcode >> 16) & 0xFF), g((colorcode >> 8) & 0xFF), b((colorcode >> 0) & 0xFF) {
  22. }
  23. //interpolates between this color and provided.
  24. //x is from 0 to 1, 0 gives this color, 1 gives provided color, values between give interpolation
  25. Color interpolate(Color color, float x) const {
  26. int r0 = x * (color.r - r) + r;
  27. int g0 = x * (color.g - g) + g;
  28. int b0 = x * (color.b - b) + b;
  29. return Color(r0, g0, b0);
  30. }
  31. //creates color with decreased brightness
  32. Color brightness(byte k) const {
  33. int r0 = r * (int)k / 255;
  34. int g0 = g * (int)k / 255;
  35. int b0 = b * (int)k / 255;
  36. return Color(r0, g0, b0);
  37. }
  38. //fades (decreases all RGB channels brightness) this color by k
  39. void fade(byte k) {
  40. if (r>=k) { r=r-k; } else { r=0; }
  41. if (g>=k) { g=g-k; } else { g=0; }
  42. if (b>=k) { b=b-k; } else { b=0; }
  43. }
  44. //fades color separately for each channel
  45. void fade3(byte dr, byte dg, byte db) {
  46. if (r>=dr) { r=r-dr; } else { r=0; }
  47. if (g>=dg) { g=g-dg; } else { g=0; }
  48. if (b>=db) { b=b-db; } else { b=0; }
  49. }
  50. //checks whether this color is visually close to given one
  51. bool isCloseTo(Color c) const {
  52. int diff = abs(r - c.r) + abs(g - c.g) + abs(b - c.b);
  53. return diff <= 220; //220 is magic number. Low values give "true" on closer colors, while higher can cause infinite loop while trying to find different color
  54. }
  55. //return value, that can be used to define how close one color to another
  56. int howCloseTo(Color c) const {
  57. return abs(r - c.r) + abs(g - c.g) + abs(b - c.b);
  58. }
  59. bool empty() const {
  60. return r == 0 && g == 0 && b == 0;
  61. }
  62. void println() const {
  63. Serial.print(("r="));Serial.print(r);Serial.print((" "));
  64. Serial.print(("g="));Serial.print(g);Serial.print( (" "));
  65. Serial.print(("b="));Serial.println(b);
  66. }
  67. friend bool operator== (const Color &c1, const Color &c2);
  68. };
  69. #endif // GARLAND_SUPPORT