How do I trim a polygon to be inside of a square

32 Views Asked by At

I want the below question answered so I can code it and help my understanding of how this works so that I can eventually use it as a part of a 3D engine. I am asking it here, because I want to understand how the math behind it works, rather than be provided with an example.

I have a polygon and a square.

I could not figure out how to paste images from my paste bin.

The square is centered around the origin, with no rotation. It is made up of 4 points, being the following:

(w,h), (-w,h), (-w,-h), (w,-h)

It has a width and a height value, being the w and h, respectively, where the w and h are each half the width and height of the center square, as is how it works.

In my case, cw and ch are the following:

cw=48.0625
ch=37.5

The polygon is made up of any number of points, but I used 4 points, and in this case that could be represented by the following:

(p1.x,p1.y), (p2.x,p2.y), (p3.x,p3.y), (p4.x,p4.y) (,(pn.x,pn.y))

Where n equals 4, there are n lines, each represented by using the point slope formula with the slope of point n and n+1 (modulus of n).

In my case, the coordinates are:

(-30,-16), (20,-18), (30,60), (-40,70)

That makes a polygon that looks like this:

I could not figure out how to paste images from my paste bin.

Putting them together, I get this:

I could not figure out how to paste images from my paste bin.

What I want to do is trim the polygon, such that for ANY point coordinates for either the polygon points or cw and ch, the polygon is cut down such that the only visible parts are inside of the box, making the part inside the box visually the same. That would maybe look like this:

I could not figure out how to paste images from my paste bin.

The top part, in this case, is cut off as it extends out of the box.

How I plan on doing that is getting the intercepts of the lines with the edges of the box, creating new points there, connecting the ones at the edges such that they remain to look the same, and connecting them together while getting rid of the points outside of the box.

I used the point-slope formula to get the line from each point to the next, got the points of which the lines intersected the boxes sides, and plotted them like so:

I could not figure out how to put images from my paste bin into here.

Some of the points may be not showing as they are out of view.

This is a lot of points, and I have tried to order what should be done in each instance of where each point is relative to the box and the other point that makes the line.

It looks like so:

Outside(-x,+y) Outside(+y) Outside(+x,+y)
Outside(-x) Inside Outside(+x)
Outside(-x,-y) Outside(-y) Outside(+x,-y)

My question is what do I do for each instance, where a line can be made from two points, each point can be in any of the 9 areas, where I want to make the line reside to being in the “inside” area?