Package util

Class MathUtils

java.lang.Object
util.MathUtils

public class MathUtils extends Object
An util class containing a lot of useful methods to do maths and physics calculations.
Since:
07.12.2021
Author:
Juyas
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    static float
    boundingSphere(org.joml.Vector2f centroid, org.joml.Vector2f... vertices)
    Calculates the radius of a minimum sphere that contains the given polygon and shares the same centroid.
    static float
    constrain(float value, float min, float max)
    Takes a float value clamps/constrains it between a minimum and maximum.
    static int
    constrain(int value, int min, int max)
    Takes an integer value clamps/constrains it between a minimum and maximum.
    static org.joml.Vector2f[]
    convexHull(org.joml.Vector2f[] points)
    Calculates the convex hull of a given set of points using Jarvis March.
    static org.joml.Vector2f[]
    copy(org.joml.Vector2f[] original)
    Make a dereferenced copy of a vector array
    static float
    dist(float x1, float y1, float x2, float y2)
    Returns the distance between two sets of X and Y coordinates.
    static float
    dist(org.joml.Vector2f pos1, org.joml.Vector2f pos2)
    Returns the distance between two sets of X and Y coordinates in the form of "physics.Vector2"s.
    static short
    encode(int data)
    Encodes a given input into a short.
    static short
    encode(int[] data)
    Encodes all given input into a short.
    static Optional<org.joml.Vector2f>
    expandingPolytopeAlgorithm(PrimitiveShape shapeA, PrimitiveShape shapeB, org.joml.Vector2f[] simplex)
    The EPA algorithm to find a penetration vector of two given shapes and the result of the GJK algorithm.
    static double
    fastRandom(int pos, int seed)
    An alternative randomization method.
    Calculates whether a shape collides/overlaps with another shape using their support function only.
    static boolean
    inCircle(float inX, float inY, float circleX, float circleY, float radius)
    Checks if a set of X and Y coordinates are inside of a circle.
    static boolean
    inCircle(org.joml.Vector2f in, float circleX, float circleY, float radius)
    Checks if a set of X and Y coordinates are inside of a circle.
    static boolean
    inCircle(org.joml.Vector2f in, org.joml.Vector2f circle, float radius)
    Checks if a set of X and Y coordinates are inside of a circle.
    static boolean
    inRect(float inX, float inY, float rectX, float rectY, float rectWidth, float rectHeight)
    Checks if a set of X and Y coordinates are inside of a rectangle.
    static boolean
    inRect(org.joml.Vector2f in, float rectX, float rectY, float rectWidth, float rectHeight)
    Checks if a set of X and Y coordinates are inside of a rectangle.
    static float
    lerp(float start, float end, float amt)
    Linearly interpolates between floats by a certain amount.
    static float
    map(float value, float start1, float stop1, float start2, float stop2)
    Re-maps a number from one range to another.
    static org.joml.Vector2f
    maxDotPoint(org.joml.Vector2f[] convexShapePoints, org.joml.Vector2f direction)
    Finds the point with the highest dot product in a shape to a given direction d, by doing a simple max search over all dot products dot(a,d) where a element of A.
    static org.joml.Vector2f
    maxDotPointMinkDiff(PrimitiveShape shapeA, PrimitiveShape shapeB, org.joml.Vector2f direction)
    Calculates the maximum point of a convex shape C in a specific direction, where C is considered the minkowskiDiff(A,B).
    static org.joml.Vector2f
    polygonCentroid(org.joml.Vector2f... vertices)
    Calculate the centroid of a polygon.
    static float
    radian(float degree)
    Transforms an angle from degree into radian.
    static float
    random(float min, float max)
    Generates a random number from a range of floats.
    static int
    randomInt(int min, int max)
    Generates a random number from a range of ints.
    static Optional<Pair<org.joml.Vector2f,org.joml.Vector2f>>
    rayCastIntersection(org.joml.Vector2f pointA, org.joml.Vector2f rayA, org.joml.Vector2f pointB, org.joml.Vector2f rayB)
    Cast two rays and see if they intersect.
    static Optional<org.joml.Vector2f>
    rayCastIntersectionPoint(org.joml.Vector2f pointA, org.joml.Vector2f rayA, org.joml.Vector2f pointB, org.joml.Vector2f rayB)
    Cast two rays and see if they intersect.
    static Optional<org.joml.Vector2f>
    rayCastToLineIntersectionPoint(org.joml.Vector2f rayStart, org.joml.Vector2f rayDirectionAndLength, org.joml.Vector2f linePointA, org.joml.Vector2f linePointB)
    Cast a ray against a fixed line and see if they intersect.
    static boolean
    Checks if a rectangle is completely inside of another rectangle.
    static org.joml.Vector2f
    rotateAroundOrigin(org.joml.Vector2f point, float radianAngle)
    Rotates a point around the origin of the system.
    static org.joml.Vector2f
    rotateAroundPoint(org.joml.Vector2f point, org.joml.Vector2f relativeOrigin, float radianAngle)
    Rotates a point around a given point in the same system.
    static float
    round(float x)
    This is for people who are too lazy to even import Math, but do want to import util.Utils.
    static int
    shiftOverwrite(float[] array, int fromIndex, int toIndex)
    Shifts a part of the array to overwrite the given region (fromIndex, toIndex) FromIndex is INCLUSIVE, ToIndex is EXCLUSIVE
    static org.joml.Vector2f
    solveSimultaneousEquations(org.joml.Matrix3x2f linearSystem)
    A universal linear system solver for two dimensional linear systems.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • MathUtils

      public MathUtils()
  • Method Details

    • gjksmCollision

      public static CollisionInformation gjksmCollision(PrimitiveShape shapeA, PrimitiveShape shapeB)
      Calculates whether a shape collides/overlaps with another shape using their support function only.

      The support function of a shape calculates the furthest point in a set direction.

      By GJKSM it is required, that both given shapes are convex shapes. If you wanna test concave shapes, you will have to split them into convex shapes first.

      This method is based on the GJKSM invariant named by and after GJK the basic underlying principle Stelly a gamedev working at valve (at least at the time) and Muratori reducing its compexity down to testing instead of heavy math.

      This algorithm below is adjusted to 2d space instead of 3d space and therefore some checks arent necessary, since an unfinished triangle (3 points, 2 vectors) already determines collision.

      This algorithm was implemented and alternated on 19th of June by Julius K.

      Parameters:
      shapeA - shape a
      shapeB - shape b
      Returns:
      whether shape a and shape b intersect
    • expandingPolytopeAlgorithm

      public static Optional<org.joml.Vector2f> expandingPolytopeAlgorithm(PrimitiveShape shapeA, PrimitiveShape shapeB, org.joml.Vector2f[] simplex)
      The EPA algorithm to find a penetration vector of two given shapes and the result of the GJK algorithm. Since it depends on the GJK algorithm, this algorithm will fail in an undefined way, if the shapes do not actually collide.
      Parameters:
      shapeA - the first shape
      shapeB - the second shape, that collides with the first one
      simplex - the simplex returned by GJK or any simplex inside both shapes borders enclosing the overlapping area of both shapes
      Returns:
      the penetration vector of both shapes, if there is one found within a series of steps
    • maxDotPointMinkDiff

      public static org.joml.Vector2f maxDotPointMinkDiff(PrimitiveShape shapeA, PrimitiveShape shapeB, org.joml.Vector2f direction)
      Calculates the maximum point of a convex shape C in a specific direction, where C is considered the minkowskiDiff(A,B).
      Returns:
      the maximum point in a specific direction
    • maxDotPoint

      public static org.joml.Vector2f maxDotPoint(org.joml.Vector2f[] convexShapePoints, org.joml.Vector2f direction)
      Finds the point with the highest dot product in a shape to a given direction d, by doing a simple max search over all dot products dot(a,d) where a element of A. Can be used as support function for all convex polygons defined by a finite number of points.
      Parameters:
      convexShapePoints - all points on the convex shape
      direction - the direction/reach to look for a point
      Returns:
      the point with the highest dot product by the given direction
    • convexHull

      public static org.joml.Vector2f[] convexHull(org.joml.Vector2f[] points)
      Calculates the convex hull of a given set of points using Jarvis March. The result will have the same length as the input, but not all of them have to be filled in depending on the input. If the input set is just a set of points already defining a convex polygon, the points are just sorted.
      Parameters:
      points - the set of points forming the convex shape
      Returns:
      a sorted array of points forming the convex hull of all input points
    • solveSimultaneousEquations

      public static org.joml.Vector2f solveSimultaneousEquations(org.joml.Matrix3x2f linearSystem)
      A universal linear system solver for two dimensional linear systems. Works usually by shifting the left 2x2 matrix to an identity matrix and read the results on the right side. This method here is using a mathematical approach and is designed to find only one result, if there is none, it may result in some kind of infinity. For more than 1 result the behaviour is undefined. Primarily used to find the intersection point of two lines or rays.
      Parameters:
      linearSystem - the two dimensional linear system
      Returns:
      the solution of linear system, Matrix3x2f.m20 will be x and Matrix3x2f.m21 will be y in the result vector
    • rayCastIntersectionPoint

      public static Optional<org.joml.Vector2f> rayCastIntersectionPoint(org.joml.Vector2f pointA, org.joml.Vector2f rayA, org.joml.Vector2f pointB, org.joml.Vector2f rayB)
      Cast two rays and see if they intersect.
      Parameters:
      pointA - the starting point of ray 1
      rayA - the direction and length of ray 1
      pointB - the starting point of ray 2
      rayB - the direction and length of ray 2
      Returns:
      the intersection point
      See Also:
    • rayCastIntersection

      public static Optional<Pair<org.joml.Vector2f,org.joml.Vector2f>> rayCastIntersection(org.joml.Vector2f pointA, org.joml.Vector2f rayA, org.joml.Vector2f pointB, org.joml.Vector2f rayB)
      Cast two rays and see if they intersect. The solution will be calculated based on endless rays with a fixpoint and a ray direction. If a there is intersection point of both ray, they arent parallel and the factors x and y are calculated, so that intersection = pointA+x*rayA = pointB+y*rayB is valid. To ensure a finite ray, the conditions 0 <= x <= 1 and 0 <= y <= 1 are checked.
      Parameters:
      pointA - the starting point of ray 1
      rayA - the direction and length of ray 1
      pointB - the starting point of ray 2
      rayB - the direction and length of ray 2
      Returns:
      a pair containing the intersection point first and a vector with factors x and y
    • rayCastToLineIntersectionPoint

      public static Optional<org.joml.Vector2f> rayCastToLineIntersectionPoint(org.joml.Vector2f rayStart, org.joml.Vector2f rayDirectionAndLength, org.joml.Vector2f linePointA, org.joml.Vector2f linePointB)
      Cast a ray against a fixed line and see if they intersect.
      Parameters:
      rayStart - the starting point of the ray
      rayDirectionAndLength - the direction and length of the ray
      linePointA - the start point of the line
      linePointB - the end point of the line
      Returns:
      the intersection point
    • boundingSphere

      public static float boundingSphere(org.joml.Vector2f centroid, org.joml.Vector2f... vertices)
      Calculates the radius of a minimum sphere that contains the given polygon and shares the same centroid.
      Parameters:
      centroid - the centroid of the polygon
      vertices - the vertices of the polygon
      Returns:
      the minimum sphere containing the polygon
    • polygonCentroid

      public static org.joml.Vector2f polygonCentroid(org.joml.Vector2f... vertices)
      Calculate the centroid of a polygon.
      Parameters:
      vertices - the vertices of the polygon
      Returns:
      the centroid of a polygon
    • inCircle

      public static boolean inCircle(float inX, float inY, float circleX, float circleY, float radius)
      Checks if a set of X and Y coordinates are inside of a circle.
      Parameters:
      inX - X position of point to check
      inY - Y position of point to check
      circleX - X position of circle
      circleY - Y position of circle
      radius - Radius of circle
      Returns:
      Returns true if the point is inside the circle, otherwise returns false.
    • inCircle

      public static boolean inCircle(org.joml.Vector2f in, float circleX, float circleY, float radius)
      Checks if a set of X and Y coordinates are inside of a circle.
      Parameters:
      in - physics.org.joml.Vector2f containing coordinates of point to check
      circleX - X position of circle
      circleY - Y position of circle
      radius - Radius of circle
      Returns:
      Returns true if the point is inside the circle, otherwise returns false.
    • inCircle

      public static boolean inCircle(org.joml.Vector2f in, org.joml.Vector2f circle, float radius)
      Checks if a set of X and Y coordinates are inside of a circle.
      Parameters:
      in - physics.Vector2f containing coordinates of point to check
      circle - physics.Vector2f containing coordinates of the circle
      radius - Radius of circle
      Returns:
      Returns true if the point is inside the circle, otherwise returns false.
    • inRect

      public static boolean inRect(float inX, float inY, float rectX, float rectY, float rectWidth, float rectHeight)
      Checks if a set of X and Y coordinates are inside of a rectangle.
      Parameters:
      inX - X position of point to check
      inY - Y position of point to check
      rectX - X position of rectangle
      rectY - Y position of rectangle
      rectWidth - Width of rectangle
      rectHeight - Height of rectangle
      Returns:
      Returns true if the point is inside the rectangle, otherwise returns false.
    • inRect

      public static boolean inRect(org.joml.Vector2f in, float rectX, float rectY, float rectWidth, float rectHeight)
      Checks if a set of X and Y coordinates are inside of a rectangle.
      Parameters:
      in - physics.Vector2f containing coordinates of point to check
      rectX - X position of rectangle
      rectY - Y position of rectangle
      rectWidth - Width of rectangle
      rectHeight - Height of rectangle
      Returns:
      Returns true if the point is inside the rectangle, otherwise returns false.
    • rectInRect

      public static boolean rectInRect(Transform t1, Transform t2)
      Checks if a rectangle is completely inside of another rectangle.
      Parameters:
      t1 -
      t2 -
      Returns:
      returns boolean true if t1 is inside of t2
    • radian

      public static float radian(float degree)
      Transforms an angle from degree into radian.
      Parameters:
      degree - the angle in degree
      Returns:
      the radian angle
    • rotateAroundOrigin

      public static org.joml.Vector2f rotateAroundOrigin(org.joml.Vector2f point, float radianAngle)
      Rotates a point around the origin of the system.
      Parameters:
      point - the point to rotate
      radianAngle - the radian angle to rotate
      Returns:
      a new point that is rotated by radianAngle starting from the given point
    • rotateAroundPoint

      public static org.joml.Vector2f rotateAroundPoint(org.joml.Vector2f point, org.joml.Vector2f relativeOrigin, float radianAngle)
      Rotates a point around a given point in the same system.
      Parameters:
      point - the point to rotate
      relativeOrigin - the point to rotate around
      radianAngle - the radian angle to rotate
      Returns:
      a new point that is rotated by radianAngle around the given relativeOrigin point starting from the given point
    • random

      public static float random(float min, float max)
      Generates a random number from a range of floats.
      Parameters:
      min - Minimum possible output
      max - Maximum possible output
      Returns:
      returns a random float from the range passed.
    • randomInt

      public static int randomInt(int min, int max)
      Generates a random number from a range of ints.
      Parameters:
      min - Minimum possible output
      max - Maximum possible output
      Returns:
      returns a random int from the range passed.
    • round

      public static float round(float x)
      This is for people who are too lazy to even import Math, but do want to import util.Utils. ¯\_(ツ)_/¯
      Parameters:
      x - Number to be rounded
      Returns:
      Returns the rounded number "x".
    • dist

      public static float dist(org.joml.Vector2f pos1, org.joml.Vector2f pos2)
      Returns the distance between two sets of X and Y coordinates in the form of "physics.Vector2"s.
      Parameters:
      pos1 - First physics.Vector2 position
      pos2 - Second physics.Vector2 position
      Returns:
      Returns the distance as a float.
    • map

      public static float map(float value, float start1, float stop1, float start2, float stop2)
      Re-maps a number from one range to another.
      Parameters:
      value - Number to me re-mapped
      start1 - Lowest number of first range
      stop1 - Highest number of first range
      start2 - Lowest number of second range
      stop2 - Highest number of second range
      Returns:
      Returns the re-mapped value as a float.
    • dist

      public static float dist(float x1, float y1, float x2, float y2)
      Returns the distance between two sets of X and Y coordinates.
      Parameters:
      x1 - First X coordinate
      y1 - First Y coordinate
      x2 - Second X coordinate
      y2 - Second Y coordinate
      Returns:
      Returns the distance as a float.
    • constrain

      public static int constrain(int value, int min, int max)
      Takes an integer value clamps/constrains it between a minimum and maximum.
      Parameters:
      value - Input to be constrained
      min - Minimum possible value
      max - Maximum possible value
      Returns:
      Constrained value as an int.
    • constrain

      public static float constrain(float value, float min, float max)
      Takes a float value clamps/constrains it between a minimum and maximum.
      Parameters:
      value - Input to be constrained
      min - Minimum possible value
      max - Maximum possible value
      Returns:
      Constrained value as a float.
    • lerp

      public static float lerp(float start, float end, float amt)
      Linearly interpolates between floats by a certain amount.
      Parameters:
      start - starting value
      end - ending value
      amt - amount to interpolate (0-1)
      Returns:
      returns a float that is the lerp of the two values by the amount.
    • fastRandom

      public static double fastRandom(int pos, int seed)
      An alternative randomization method.
      Based on noise generation and hashing techniques - it generates a random value using a position and a seed.
      - Could also be used as one dimensional value noise.
      - Guarantees reproducible results for identical inputs.
      - The seed is less significant than the position.
      Parameters:
      pos - the position in the spectrum.
      seed - the seed used for fixing the spectrum
      Returns:
      a reproducible randomized number between 0 and 1
    • encode

      public static short encode(int[] data)
      Encodes all given input into a short. Note, that the range of Short is 16 bytes and therefore only 0-14 (15 different values) can be encoded. Any value that is not within this range, will lead to undefined behaviour.
      Parameters:
      data - a list of integers in no particular order
      Returns:
      the encoded data as a short
    • encode

      public static short encode(int data)
      Encodes a given input into a short. Note, that the range of Short is 16 bytes and therefore only 0-14 (15 different values) can be encoded. Any value that is not within this range, will lead to undefined behaviour.
      Parameters:
      data - the integer in range to encode
      Returns:
      the encoded data as a short
    • copy

      public static org.joml.Vector2f[] copy(org.joml.Vector2f[] original)
      Make a dereferenced copy of a vector array
      Parameters:
      original - the original array
      Returns:
      a array containing a copy of each vector
    • shiftOverwrite

      public static int shiftOverwrite(float[] array, int fromIndex, int toIndex)
      Shifts a part of the array to overwrite the given region (fromIndex, toIndex) FromIndex is INCLUSIVE, ToIndex is EXCLUSIVE
      Parameters:
      array - the array from which the region has to be removed
      fromIndex - start of the region
      toIndex - end of the region
      Returns:
      the new effective length