color.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include "pch.h"
  2. //////////////////////////////////////////////////////////////////////////////
  3. //
  4. // Color
  5. //
  6. //////////////////////////////////////////////////////////////////////////////
  7. float HueComponent(float hue)
  8. {
  9. hue = abs(mod(hue + 3, 6) - 3);
  10. if (hue > 2) {
  11. return 0;
  12. } else if (hue > 1) {
  13. return (2 - hue);
  14. } else {
  15. return 1;
  16. }
  17. }
  18. void Color::SetHSBA(float hue, float saturation, float brightness, float alpha)
  19. {
  20. hue = hue * 6;
  21. float white = (1 - saturation);
  22. m_r = brightness * (white + saturation * HueComponent(hue ));
  23. m_g = brightness * (white + saturation * HueComponent(hue - 2.0f));
  24. m_b = brightness * (white + saturation * HueComponent(hue + 2.0f));
  25. m_a = alpha;
  26. }
  27. void Color::GetHSB(float& h, float& s, float& b)
  28. {
  29. float c0 = m_r;
  30. float cm = m_g;
  31. float c1 = m_b;
  32. //
  33. // find the largest component
  34. //
  35. if (c0 > cm) {
  36. swap(c0, cm);
  37. }
  38. if (cm > c1) {
  39. swap(cm, c1);
  40. }
  41. if (c0 > cm) {
  42. swap(c0, cm);
  43. }
  44. //
  45. // solve for h, s, b
  46. //
  47. b = c1;
  48. s = (b - c0) / b;
  49. h = (cm + b * (s - 1)) / (b * s);
  50. //
  51. // shift the hue
  52. //
  53. if (c1 == m_b) {
  54. // blue is the largest component
  55. if (m_g == c0) {
  56. h = -2 + h;
  57. } else {
  58. h = -2 - h;
  59. }
  60. } else if (c1 == m_g) {
  61. // green is the largest component
  62. if (m_r == c0) {
  63. h = 2 + h;
  64. } else {
  65. h = 2 - h;
  66. }
  67. } else {
  68. // red is the larget component
  69. if (m_b == c0) {
  70. h = h;
  71. } else {
  72. h = -h;
  73. }
  74. }
  75. h = h / 6.0f;
  76. }
  77. const Color Color::s_colorWhite(1, 1, 1);
  78. const Color Color::s_colorRed(1, 0, 0);
  79. const Color Color::s_colorGreen(0, 1, 0);
  80. const Color Color::s_colorBlue(0, 0, 1);
  81. const Color Color::s_colorYellow(1, 1, 0);
  82. const Color Color::s_colorMagenta(1, 0, 1);
  83. const Color Color::s_colorCyan(0, 1, 1);
  84. const Color Color::s_colorBlack(0, 0, 0);
  85. const Color Color::s_colorGray(0.5f, 0.5f, 0.5f);