Clamp an angled rectangle within unit square

34 Views Asked by At

I have a rectangle that is defined using its center point, width, height and angle in radians calculated anti-clockwise from the x-axis. To keep the Rectangles unique the angle is clamped to $\pi$. I have another rectangle, the boundaries which is just the unit square.

My problem is I don't want any rectangles outside the boundaries and therefore want to clamp them, i.e. shrink them so they fit within the bounds. How can this be done? I have the following functions so far that could prove useful:

  • A function that calculates the corner points of the rectangle in anti-clockwise order (due to rotation there is no guarantee that the first is the "bottom left").
  • A function that returns the intersection point of two segments.
  • A function returning the bounding box of the target rectangle (purple in the sketch)

Below is an Illustration of what I am aiming for, the green rectangle is within bounds, the red is not and should be reduced to something like the blue one.

enter image description here