Geometry.java 1.9 KB

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