Geometry.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package holeg.utility.math.vector;
  2. import holeg.utility.math.Maths;
  3. import java.awt.*;
  4. import java.util.Optional;
  5. import static holeg.utility.math.Maths.EPSILON;
  6. public class Geometry {
  7. public static Rectangle createRectangleFromCorners(Vec2i corner, Vec2i otherCorner){
  8. //Calculate left top corner, width, height
  9. Vec2i topLeft = new Vec2i(Math.min(corner.getX(), otherCorner.getX()), Math.min(corner.getY(), otherCorner.getY()));
  10. Vec2i bottomRight = new Vec2i(Math.max(corner.getX(), otherCorner.getX()), Math.max(corner.getY(), otherCorner.getY()));
  11. int width = bottomRight.getX() - topLeft.getX();
  12. int height = bottomRight.getY() - topLeft.getY();
  13. return new Rectangle(topLeft.getX(),topLeft.getY(), width, height);
  14. }
  15. public static Optional<Vec2f> getProjectionOnSegmentIfInRange(Line line , Circle circle){
  16. float lineLengthSqr = line.distanceSqr();
  17. if(lineLengthSqr < EPSILON) {
  18. if(line.p1.getSquaredDistance(circle.position) < circle.radius * circle.radius){
  19. return Optional.of(new Vec2f(line.p1));
  20. }else{
  21. return Optional.empty();
  22. }
  23. }
  24. Vec2f p2p1 = line.p2.subtract(line.p1);
  25. float t = Maths.Clamp(Vec2f.dot(circle.position.subtract(line.p1), p2p1) / lineLengthSqr, 0.0f, 1.0f);
  26. Vec2f projection = line.p1.add(p2p1.multiply(t));
  27. if(projection.getSquaredDistance(circle.position) < circle.radius * circle.radius){
  28. return Optional.of(projection);
  29. }else{
  30. return Optional.empty();
  31. }
  32. }
  33. public static class Circle{
  34. public Vec2f position;
  35. public float radius;
  36. public Circle(Vec2f position, float radius){
  37. this.position = position;
  38. this.radius = radius;
  39. }
  40. }
  41. public static class Line{
  42. Vec2f p1;
  43. Vec2f p2;
  44. public Line(Vec2f p1, Vec2f p2){
  45. this.p1 = p1;
  46. this.p2 = p2;
  47. }
  48. float distanceSqr(){
  49. return p1.getSquaredDistance(p2);
  50. }
  51. }
  52. }