HslColor.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Globalization;
  4. using System.Runtime.InteropServices;
  5. using Microsoft.Xna.Framework;
  6. namespace MonoGame.Extended
  7. {
  8. /// <summary>
  9. /// Represents a color in the HSL (Hue, Saturation, Lightness) color space.
  10. /// </summary>
  11. /// <remarks>
  12. /// <list type="bullet">
  13. /// <item>Hue (H) represents the color, ranging from 0 to 360 degrees on the color wheel.</item>
  14. /// <item>Saturation (S) represents the intensity of the color, ranging from 0.0 (gray) to 1.0 (full color).</item>
  15. /// <item>Lightness (L) represents the brightness, ranging from 0.0 (black) to 1.0 (white).</item>
  16. /// </list>
  17. /// </remarks>
  18. [StructLayout(LayoutKind.Sequential)]
  19. public struct HslColor : IEquatable<HslColor>, IComparable<HslColor>
  20. {
  21. private float _h;
  22. private float _s;
  23. private float _l;
  24. /// <summary>
  25. /// The hue component value (in degrees) of the color ranging from 0.0 to 360.0.
  26. /// </summary>
  27. public readonly float H => _h;
  28. /// <summary>
  29. /// The saturation component value of the color ranging from 0.0 to 1.0.
  30. /// </summary>
  31. public readonly float S => _s;
  32. /// <summary>
  33. /// The lightness component value of the color ranging from 0.0 to 1.0.
  34. /// </summary>
  35. public readonly float L => _l;
  36. /// <summary>
  37. /// Normalizes a hue value to be within the range [0, 360).
  38. /// Handles negative values by wrapping them around.
  39. /// </summary>
  40. /// <param name="h">The hue value to normalize.</param>
  41. /// <returns>The normalized hue value.</returns>
  42. private static float NormalizeHue(float h)
  43. {
  44. if (h < 0) return h + 360 * ((int)(h / 360) + 1);
  45. return h % 360;
  46. }
  47. /// <summary>
  48. /// Initializes a new instance of the <see cref="HslColor"/> struct with the specified hue, saturation,
  49. /// and lightness component values.
  50. /// </summary>
  51. /// <param name="h">The hue component value (in degrees) from 0.0 to 360.0.</param>
  52. /// <param name="s">The saturation component value from 0.0 to 1.0.</param>
  53. /// <param name="l">The lightness component value from 0.0 to 1.0.</param>
  54. public HslColor(float h, float s, float l)
  55. {
  56. _h = Math.Clamp(h, 0.0f, 360.0f);
  57. _s = Math.Clamp(s, 0.0f, 1.0f);
  58. _l = Math.Clamp(l, 0.0f, 1.0f);
  59. }
  60. /// <summary>
  61. /// Copies the values of this <see cref="HslColor"/> struct to a new instance.
  62. /// </summary>
  63. /// <param name="destination">When this method returns, contains a copy of this <see cref="HslColor"/>.</param>
  64. [Obsolete("Use CopyToRef instead. This will be removed in the next major SemVer release.")]
  65. public readonly void CopyTo(out HslColor destination)
  66. {
  67. destination = new HslColor(H, S, L);
  68. }
  69. /// <summary>
  70. /// Copies the value of this <see cref="HslColor"/> struct to an existing destination.
  71. /// </summary>
  72. /// <param name="destination">A reference to the destination <see cref="HslColor"/> struct where values will be copied to.</param>
  73. /// <remarks>
  74. /// This method directly modifies the internal components of the destination struct for improved performance.
  75. /// Unlike typical operations on immutable structs, this method does not create a new instance but alters
  76. /// the existing one in-place. It should be used only in scenarios where performance is critical.
  77. /// </remarks>
  78. public readonly void CopyToRef(ref HslColor destination)
  79. {
  80. destination._h = _h;
  81. destination._s = _s;
  82. destination._l = _l;
  83. }
  84. /// <summary>
  85. /// Deconstructs this <see cref="HslColor"/> into its hue, saturation, and lightness component values.
  86. /// </summary>
  87. /// <param name="h">When this method returns, contains the hue component value of this <see cref="HslColor"/>.</param>
  88. /// <param name="s">When this method returns, contains the saturation component value of this <see cref="HslColor"/>.</param>
  89. /// <param name="l">When this method returns, contains the lightness component value of this <see cref="HslColor"/>.</param>
  90. [Obsolete("Will be removed in next major SemVer release. Use Deconstruct instead.")]
  91. public readonly void Destructure(out float h, out float s, out float l)
  92. {
  93. h = H;
  94. s = S;
  95. l = L;
  96. }
  97. /// <summary>
  98. /// Deconstructs this <see cref="HslColor"/> into its hue, saturation, and lightness component values.
  99. /// </summary>
  100. /// <param name="h">When this method returns, contains the hue component value of this <see cref="HslColor"/>.</param>
  101. /// <param name="s">When this method returns, contains the saturation component value of this <see cref="HslColor"/>.</param>
  102. /// <param name="l">When this method returns, contains the lightness component value of this <see cref="HslColor"/>.</param>
  103. public readonly void Deconstruct(out float h, out float s, out float l)
  104. {
  105. h = H;
  106. s = S;
  107. l = L;
  108. }
  109. /// <summary>
  110. /// Executes a callback with the components of this <see cref="HslColor"/>.
  111. /// </summary>
  112. /// <param name="callback">The callback to execute.</param>
  113. /// <exception cref="ArgumentNullException">
  114. /// Thrown when <paramref name="callback"/> is <see langword="null"/>.
  115. /// </exception>
  116. public readonly void Match(Action<float, float, float> callback)
  117. {
  118. ArgumentNullException.ThrowIfNull(callback);
  119. callback(H, S, L);
  120. }
  121. /// <summary>
  122. /// Maps the components of this <see cref="HslColor"/> to a new value using the specified mapping function.
  123. /// </summary>
  124. /// <typeparam name="T">The type of the result of the mapping function.</typeparam>
  125. /// <param name="map">The mapping function to apply to the components of this <see cref="HslColor"/>.</param>
  126. /// <returns>
  127. /// The result of applying the mapping function to the components of this <see cref="HslColor"/>.
  128. /// </returns>
  129. /// <exception cref="ArgumentNullException">
  130. /// Thrown when <paramref name="map"/> is <see langword="null"/>.
  131. /// </exception>
  132. public readonly T Map<T>(Func<float, float, float, T> map)
  133. {
  134. ArgumentNullException.ThrowIfNull(map);
  135. return map(H, S, L);
  136. }
  137. /// <summary>
  138. /// Implicitly converts a string to an <see cref="HslColor"/>.
  139. /// </summary>
  140. /// <param name="value">The string to convert.</param>
  141. /// <returns>The <see cref="HslColor"/> represented by the string.</returns>
  142. [Obsolete("Use HslColor.Parse instead to make string parsing explicit and improve code readability. This method will be removed in the next major SemVer release.")]
  143. public static implicit operator HslColor(string value)
  144. {
  145. return Parse(value);
  146. }
  147. /// <inheritdoc/>
  148. /// <remarks>
  149. /// This comparison uses a lexicographic approach that establishes a hierarchy among the HSL components:
  150. ///
  151. /// <list type="bullet">
  152. /// <item>Hue is the primary sorting factor</item>
  153. /// <item>Lightness is the secondary sorting factor</item>
  154. /// <item>Saturation is the tertiary sorting factor</item>
  155. /// </list>
  156. ///
  157. /// The comparison returns the result of the first differing component, ensuring that hue differences
  158. /// take precedence over lightness differences, which in turn take precedence over saturation differences.
  159. /// This creates a consistent and predictable ordering for color intervals while prioritizing the most
  160. /// visually significant color properties.
  161. /// </remarks>
  162. public readonly int CompareTo(HslColor other)
  163. {
  164. int result = _h.CompareTo(other._h);
  165. if (result != 0)
  166. {
  167. return result;
  168. }
  169. result = _l.CompareTo(other._l);
  170. if (result != 0)
  171. {
  172. return result;
  173. }
  174. return _s.CompareTo(other._s);
  175. }
  176. /// <inheritdoc/>
  177. public override bool Equals([NotNullWhen(true)] object obj)
  178. {
  179. return obj is HslColor other && Equals(other);
  180. }
  181. /// <inheritdoc/>
  182. public readonly bool Equals(HslColor value)
  183. {
  184. return H.Equals(value.H) &&
  185. L.Equals(value.L) &&
  186. S.Equals(value.S);
  187. }
  188. /// <inheritdoc/>
  189. public override readonly int GetHashCode()
  190. {
  191. return H.GetHashCode() ^
  192. S.GetHashCode() ^
  193. L.GetHashCode();
  194. }
  195. /// <inheritdoc/>
  196. public override readonly string ToString()
  197. {
  198. return string.Format(CultureInfo.InvariantCulture, "H:{0:N1}° S:{1:N1} L:{2:N1}",
  199. H, 100 * S, 100 * L);
  200. }
  201. /// <summary>
  202. /// Parses a string into an <see cref="HslColor"/>.
  203. /// </summary>
  204. /// <param name="s">The string to parse.</param>
  205. /// <returns>The <see cref="HslColor"/> represented by the string.</returns>
  206. /// <remarks>
  207. /// The input string should be in the format "hue,saturation,lightness", where hue is in degrees
  208. /// (optionally followed by the '°' symbol), and saturation and lightness are decimal values.
  209. /// </remarks>
  210. public static HslColor Parse(string s)
  211. {
  212. var hsl = s.Split(',');
  213. var hue = float.Parse(hsl[0].TrimEnd('°'), CultureInfo.InvariantCulture.NumberFormat);
  214. var sat = float.Parse(hsl[1], CultureInfo.InvariantCulture.NumberFormat);
  215. var lig = float.Parse(hsl[2], CultureInfo.InvariantCulture.NumberFormat);
  216. return new HslColor(hue, sat, lig);
  217. }
  218. /// <summary>
  219. /// Determines whether two <see cref="HslColor"/> values are equal.
  220. /// </summary>
  221. /// <param name="x">The first <see cref="HslColor"/> to compare.</param>
  222. /// <param name="y">The second <see cref="HslColor"/> to compare.</param>
  223. /// <returns>
  224. /// <see langword="true"/> if the <see cref="HslColor"/> values are equal; otherwise, <see langword="false"/>.
  225. /// </returns>
  226. public static bool operator ==(HslColor x, HslColor y)
  227. {
  228. return x.Equals(y);
  229. }
  230. /// <summary>
  231. /// Determines whether two <see cref="HslColor"/> values are not equal.
  232. /// </summary>
  233. /// <param name="x">The first <see cref="HslColor"/> to compare.</param>
  234. /// <param name="y">The second <see cref="HslColor"/> to compare.</param>
  235. /// <returns>
  236. /// <see langword="true"/> if the <see cref="HslColor"/> values are not equal; otherwise, <see langword="false"/>.
  237. /// </returns>
  238. public static bool operator !=(HslColor x, HslColor y)
  239. {
  240. return !x.Equals(y);
  241. }
  242. /// <summary>
  243. /// Adds two <see cref="HslColor"/> values together.
  244. /// </summary>
  245. /// <param name="a">The first <see cref="HslColor"/> to add.</param>
  246. /// <param name="b">The second <see cref="HslColor"/> to add.</param>
  247. /// <returns>
  248. /// A new <see cref="HslColor"/> value where the hue, saturation, and light component values are the sum of
  249. /// the components of the two input colors.
  250. /// </returns>
  251. public static HslColor operator +(HslColor a, HslColor b)
  252. {
  253. return new HslColor(
  254. a._h + b._h,
  255. a._s + b._s,
  256. a._l + b._l
  257. );
  258. }
  259. /// <summary>
  260. /// Subtracts one <see cref="HslColor"/> value from another.
  261. /// </summary>
  262. /// <param name="a">The <see cref="HslColor"/> to subtract from.</param>
  263. /// <param name="b">The <see cref="HslColor"/> to subtract.</param>
  264. /// <returns>
  265. /// A new <see cref="HslColor"/> value where the hue, saturation, and light component values are the difference
  266. /// of the components of the two input colors.
  267. /// </returns>
  268. public static HslColor operator -(HslColor a, HslColor b)
  269. {
  270. return new HslColor(
  271. a._h - b._h,
  272. a._s - b._s,
  273. a._l - b._l
  274. );
  275. }
  276. /// <summary>
  277. /// Linearly interpolates between two <see cref="HslColor"/> values.
  278. /// </summary>
  279. /// <param name="c1">The first <see cref="HslColor"/>.</param>
  280. /// <param name="c2">The second <see cref="HslColor"/>.</param>
  281. /// <param name="t">The interpolation factor. A value of 0 returns <paramref name="c1"/>, a value of 1 returns <paramref name="c2"/>.</param>
  282. /// <returns>The interpolated <see cref="HslColor"/>.</returns>
  283. public static HslColor Lerp(HslColor c1, HslColor c2, float t)
  284. {
  285. // loop around if c2.H < c1.HF
  286. var h2 = c2.H >= c1.H ? c2.H : c2.H + 360;
  287. return new HslColor(
  288. c1.H + t * (h2 - c1.H),
  289. c1.S + t * (c2.S - c1.S),
  290. c1.L + t * (c2.L - c1.L));
  291. }
  292. /// <summary>
  293. /// Convers a <see cref="HslColor"/> value to a <see cref="Microsoft.Xna.Framework.Color"/> value.
  294. /// </summary>
  295. /// <param name="hsl">The <see cref="HslColor"/> value to convert.</param>
  296. /// <returns>
  297. /// A <see cref="Microsoft.Xna.Framework.Color"/> value representing the RGB equivalent of the specified
  298. /// <see cref="HslColor"/> value.
  299. /// </returns>
  300. public static Color ToRgb(HslColor hsl)
  301. {
  302. float h = hsl._h;
  303. float s = hsl._s;
  304. float l = hsl._l;
  305. if (s < MathExtended.MachineEpsilon)
  306. {
  307. return new Color(l, l, l);
  308. }
  309. if (l <= MathExtended.MachineEpsilon)
  310. {
  311. return Color.Black;
  312. }
  313. h /= 360.0f;
  314. float max = l < 0.5f ?
  315. l * (1 + s) :
  316. l + s - l * s;
  317. float min = 2.0f * l - max;
  318. float r = RgbFromHue(min, max, h + 0.3333333f);
  319. float g = RgbFromHue(min, max, h);
  320. float b = RgbFromHue(min, max, h - 0.3333333f);
  321. return new Color(r, g, b);
  322. }
  323. private static float RgbFromHue(float min, float max, float hue)
  324. {
  325. hue = (hue + 1.0f) % 1.0f;
  326. if (hue * 6.0f < 1.0f)
  327. {
  328. return min + (max - min) * 6.0f * hue;
  329. }
  330. if (hue * 2.0f < 1.0f)
  331. {
  332. return max;
  333. }
  334. if (hue * 3.0f < 2.0f)
  335. {
  336. return min + (max - min) * (2.0f / 3.0f - hue) * 6.0f;
  337. }
  338. return min;
  339. }
  340. /// <summary>
  341. /// Converts an RGB color to an HSL color.
  342. /// </summary>
  343. /// <param name="color">The RGB color to convert.</param>
  344. /// <returns>The equivalent HSL color.</returns>
  345. public static HslColor FromRgb(Color color)
  346. {
  347. float r = color.R / 255f;
  348. float g = color.G / 255f;
  349. float b = color.B / 255f;
  350. float max = MathF.Max(r, MathF.Max(g, b));
  351. float min = MathF.Min(r, MathF.Min(g, b));
  352. float delta = max - min;
  353. float h = 0.0f;
  354. float s = 0.0f;
  355. float l = (max + min) * 0.5f;
  356. if (MathF.Abs(delta) < float.Epsilon)
  357. {
  358. return new HslColor(h, s, l);
  359. }
  360. if (MathF.Abs(r - max) < float.Epsilon)
  361. {
  362. h = (g - b) / delta;
  363. }
  364. else if (MathF.Abs(g - max) < float.Epsilon)
  365. {
  366. h = (b - r) / delta + 2.0f;
  367. }
  368. else if (MathF.Abs(b - max) < float.Epsilon)
  369. {
  370. h = (r - g) / delta + 4.0f;
  371. }
  372. h *= 60.0f;
  373. h = NormalizeHue(h);
  374. if (l <= 0.5f)
  375. {
  376. s = delta / (max + min);
  377. }
  378. else
  379. {
  380. s = delta / (2.0f - max - min);
  381. }
  382. return new HslColor(h, s, l);
  383. }
  384. }
  385. }