Validate.Value.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. namespace Animancer
  3. {
  4. /// https://kybernetik.com.au/animancer/api/Animancer/Validate
  5. public static partial class Validate
  6. {
  7. /************************************************************************************************************************/
  8. /// <summary>A rule that defines which values are valid.</summary>
  9. /// https://kybernetik.com.au/animancer/api/Animancer/Value
  10. public enum Value
  11. {
  12. /// <summary>Any value is allowed.</summary>
  13. Any,
  14. /// <summary>Only values between 0 (inclusive) and 1 (inclusive) are allowed.</summary>
  15. ZeroToOne,
  16. /// <summary>Only 0 or positive values are allowed.</summary>
  17. IsNotNegative,
  18. /// <summary>Infinity and NaN are not allowed.</summary>
  19. IsFinite,
  20. /// <summary>Infinity is not allowed.</summary>
  21. IsFiniteOrNaN,
  22. }
  23. /************************************************************************************************************************/
  24. /// <summary>Enforces the `rule` on the `value`.</summary>
  25. public static void ValueRule(ref float value, Value rule)
  26. {
  27. switch (rule)
  28. {
  29. case Value.Any:
  30. default:
  31. return;
  32. case Value.ZeroToOne:
  33. if (!(value >= 0))// Reversed comparison to include NaN.
  34. value = 0;
  35. else if (value > 1)
  36. value = 1;
  37. break;
  38. case Value.IsNotNegative:
  39. if (!(value >= 0))// Reversed comparison to include NaN.
  40. value = 0;
  41. break;
  42. case Value.IsFinite:
  43. if (float.IsNaN(value))
  44. value = 0;
  45. else if (float.IsPositiveInfinity(value))
  46. value = float.MaxValue;
  47. else if (float.IsNegativeInfinity(value))
  48. value = float.MinValue;
  49. break;
  50. case Value.IsFiniteOrNaN:
  51. if (float.IsPositiveInfinity(value))
  52. value = float.MaxValue;
  53. else if (float.IsNegativeInfinity(value))
  54. value = float.MinValue;
  55. break;
  56. }
  57. }
  58. /************************************************************************************************************************/
  59. }
  60. }