color.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * color.cpp - Color types
  3. * Copyright (C) 2017 caryoscelus
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <core/color.h>
  19. namespace rainynite::core {
  20. namespace colors {
  21. template <>
  22. string to_hex24(RGBA<uint8_t> const& color) {
  23. return "#{:02x}{:02x}{:02x}"_format(color.r, color.g, color.b);
  24. }
  25. template <>
  26. string to_hex32(RGBA<uint8_t> const& color) {
  27. return "#{:02x}{:02x}{:02x}{:02x}"_format(color.r, color.g, color.b, color.a);
  28. }
  29. RGBA32 parse_hex(string const& s) {
  30. RGBA32 color;
  31. color.a = 0xff;
  32. size_t sz = s.size()-1;
  33. if (s[0] != '#' || !(sz == 3 || sz == 4 || sz == 6 || sz == 8)) {
  34. throw std::runtime_error("Can't parse color '"+s+"'");
  35. }
  36. uint32_t c = std::stoul(s.c_str()+1, nullptr, 16);
  37. switch (sz) {
  38. case 4:
  39. color.a = (c & 0xf) * 1.0 * 0xff / 0xf;
  40. c >>= 4;
  41. __attribute__ ((fallthrough));
  42. case 3:
  43. color.b = (c & 0xf) * 1.0 * 0xff / 0xf;
  44. c >>= 4;
  45. color.g = (c & 0xf) * 1.0 * 0xff / 0xf;
  46. c >>= 4;
  47. color.r = (c & 0xf) * 1.0 * 0xff / 0xf;
  48. break;
  49. case 8:
  50. color.a = c & 0xff;
  51. c >>= 8;
  52. __attribute__ ((fallthrough));
  53. case 6:
  54. color.b = c & 0xff;
  55. c >>= 8;
  56. color.g = c & 0xff;
  57. c >>= 8;
  58. color.r = c & 0xff;
  59. break;
  60. }
  61. return color;
  62. }
  63. std::ostream& operator<<(std::ostream& stream, Color c) {
  64. return stream << to_hex32(c);
  65. }
  66. } // namespace color
  67. } // namespace rainynite::core