Maths.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package holeg.utility.math;
  2. /**
  3. * A helper class for common math operations.
  4. * It's an extension for {@link java.lang.Math}.
  5. */
  6. public class Maths {
  7. public final static double EPSILON = 1E-6;
  8. /**
  9. * Linear Interpolation from first to second via alpha amount.
  10. *
  11. * @param first the first value
  12. * @param second the second value
  13. * @param alpha the alpha to calculate the double that is interpolated between first and second, normally a value between 0.0 and 1.0
  14. * @return the interpolated double via alpha
  15. */
  16. public static double lerp(double first, double second, double alpha) {
  17. return first * (1.0 - alpha) + second * alpha;
  18. }
  19. /**
  20. * Inverse linear interpolation from min to max to get the corresponding alpha from value.
  21. *
  22. * @param min the minimum value
  23. * @param max the maximum value
  24. * @param value the value to get the alpha from
  25. * @return the corresponding alpha
  26. */
  27. public static double invLerp(double min, double max, double value) {
  28. if (Math.abs(max - min) < EPSILON) {
  29. return max;
  30. } else {
  31. return (value - min) / (max - min);
  32. }
  33. }
  34. /**
  35. * Clamp a value between a minimum and a maximum.
  36. * @param value the value to be clamped
  37. * @param min the minimum value
  38. * @param max the maximum value
  39. * @return the value in Range[min;max]
  40. */
  41. public static int clamp(int value, int min, int max) {
  42. return Math.max(min, Math.min(max, value));
  43. }
  44. /**
  45. * Clamp a value between a minimum and a maximum.
  46. * @param value the value to be clamped
  47. * @param min the minimum value
  48. * @param max the maximum value
  49. * @return the value in Range[min;max]
  50. */
  51. public static float clamp(float value, float min, float max) {
  52. return Math.max(min, Math.min(max, value));
  53. }
  54. /**
  55. * Clamp a value between a minimum and a maximum.
  56. * @param value the value to be clamped
  57. * @param min the minimum value
  58. * @param max the maximum value
  59. * @return the value in Range[min;max]
  60. */
  61. public static double clamp(double value, double min, double max) {
  62. return Math.max(min, Math.min(max, value));
  63. }
  64. }