MSSQL geography::STIntersects returns incorrect results when on or very close to a bounding box edge. What is the correct way to "Fix" this - rounding

Consider the following (derived from SQL Geography point inside polygon not returning true on STIntersect (but returns true using Geometry))
-- TEST CASE1
DECLARE #point1 GEOGRAPHY = GEOGRAPHY::STGeomFromText('POINT (0 -0.0000001)', 4326)
DECLARE #polygon1 GEOGRAPHY = GEOGRAPHY::STGeomFromText('POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))', 4326)
SELECT #polygon1.STIntersects(#point1), #point1.STIntersects(#polygon1), #point1.STDistance(#polygon1)
-- TEST CASE2
DECLARE #point2 GEOGRAPHY = GEOGRAPHY::STGeomFromText('POINT (-4.278563 55.833035)', 4326)
DECLARE #polygon2 GEOGRAPHY = GEOGRAPHY::STGeomFromText('POLYGON ((
-4.351235 55.833035,
-4.245494 55.833035,
-4.245494 55.879491,
-4.351235 55.879491,
-4.351235 55.833035))', 4326)
SELECT #polygon2.STIntersects(#point2), #point2.STIntersects(#polygon2), #point2.STDistance(#polygon2)
In the above:
Test case 1 returns TRUE (0 distance), although the point falls outside of the polygon.
Test case 2 returns FALSE (1m distance), although the point lies on the edge of the polygon.
How should I handle the rounding errors of geography points.
Backgound
Test 2 - is a real-world issue. The bounding box is derived from a point cluster atlas.data.BoundingBox.fromPositions(coords) (azure maps). When the items are selected from SQL using the bounding box there are items missing from the result set even though these are the same points used to create the bounding box!
If I need, I could expand the bounding box slightly or select data where distance < 2 metres. I can't help but think that I'm missing a trick somewhere and my google-foo is lacking.
I've tried Range(xx) no luck (or not understood)
Perhaps the expectation is that you "just" need to +/-EPSILON?
Ideas welcome
x x x

I came across this before with SQL when using bounding boxes. The issue comes down to geography object vs geometry object. When using a geography, the lines between points follow a geodesic path (a path that follows the curvature of the earth). So, when using geography, a "bounding box" actually represents an area that looks more like the following image:
This is why Geometry has a STEnvelope method and Geography doesn't. When working with Geography, a bounding circle is more accurate.EnvelopeCenter, EnvelopeAngle methods). You would be surprised to know that most major map platforms actually store their spatial data as geometries for the purpose of rendering and queries based on square bounding boxes.
There are a couple of solutions to your situation;
Solution 1
Since your query shape is coming from a Mercator map, using Geometry instead of Geography will work much more accurately (it is also faster). One caveat is that it won't work well if you need to support shapes that cross the anti-Merdian (-180/180 longitude). A second caveat is that all distances will be in degrees, not meters. Here is what this would look like:
-- TEST CASE1
DECLARE #point1 GEOMETRY = GEOMETRY::STGeomFromText('POINT (0 -0.0000001)', 4326)
DECLARE #polygon1 GEOMETRY = GEOMETRY::STGeomFromText('POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))', 4326)
SELECT #polygon1.STIntersects(#point1), #point1.STIntersects(#polygon1), #point1.STDistance(#polygon1)
-- TEST CASE2
DECLARE #point2 GEOMETRY = GEOMETRY::STGeomFromText('POINT (-4.278563 55.833035)', 4326)
DECLARE #polygon2 GEOMETRY = GEOMETRY::STGeomFromText('POLYGON ((
-4.351235 55.833035,
-4.245494 55.833035,
-4.245494 55.879491,
-4.351235 55.879491,
-4.351235 55.833035))', 4326)
SELECT #polygon2.STIntersects(#point2), #point2.STIntersects(#polygon2), #point2.STDistance(#polygon2)
Here is what the output looks like:
To get distances in meters rather than degrees, you can convert the geometry to geography. Note that this will not align with what your see visually on a Mercator map but will be spatially accurate. Here is an example:
DECLARE #point2 GEOMETRY = GEOMETRY::STGeomFromText('POINT (-4.278563 55.833035)', 4326)
DECLARE #polygon2 GEOMETRY = GEOMETRY::STGeomFromText('POLYGON ((
-4.351235 55.833035,
-4.245494 55.833035,
-4.245494 55.879491,
-4.351235 55.879491,
-4.351235 55.833035))', 4326)
DECLARE #polygonGeo2 GEOGRAPHY = GEOGRAPHY::STGeomFromWKB(#polygon2.STAsBinary(), 4326)
SELECT GEOGRAPHY::STGeomFromWKB(#point2.STAsBinary(), 4326).STDistance(#polygonGeo2)
Converting between Geometry and Geography using well known binary is extremely fast.
Note that if you do this with point1/polygon1 the result is 0 because the distance in meters is extremely small (~1cm).
Solution 2
Convert your data to Geometry may not be desired if you have other spatial queries you plan to make, such as finding all points within a certain distance in meters. Three ways to handle this,
Add a second column for a geometry version of your points and use solution 1 with that column. The downside to this is that the database ends up being bigger and you end up having to do more work keeping things in sync if a rows point changes location.
Convert the points to geometry on the fly as part of the query with a geometry polygon.
-- TEST CASE2
DECLARE #point2 GEOGRAPHY = GEOGRAPHY::STGeomFromText('POINT (-4.278563 55.833035)', 4326)
DECLARE #polygon2 GEOMETRY = GEOMETRY::STGeomFromText('POLYGON ((
-4.351235 55.833035,
-4.245494 55.833035,
-4.245494 55.879491,
-4.351235 55.879491,
-4.351235 55.833035))', 4326)
SELECT #polygon2.STIntersects(GEOMETRY::STGeomFromWKB(#point2.STAsBinary(), 4326)),
GEOMETRY::STGeomFromWKB(#point2.STAsBinary(), 4326).STIntersects(#polygon2),
GEOMETRY::STGeomFromWKB(#point2.STAsBinary(), 4326).STDistance(#polygon2)
Calculate the geography bounding circle for the points of your bounding box by leveraging EnvelopeAggregate.
DECLARE #point2 GEOGRAPHY = GEOGRAPHY::STGeomFromText('POINT (-4.278563 55.833035)', 4326)
DECLARE #polygon2 GEOGRAPHY = GEOGRAPHY::STGeomFromText('POLYGON ((
-4.351235 55.833035,
-4.245494 55.833035,
-4.245494 55.879491,
-4.351235 55.879491,
-4.351235 55.833035))', 4326)
Declare #env Geography = Geography::EnvelopeAggregate(#polygon2);
SELECT #point2.STIntersects(#env), #point2.STDistance(#env)
This would likely be the easiest and fastest method, but you will want to test this some more as I just came across this solution.

Related

how to use vtkImageReSlice?

I am trying to use vtkImageReSlicer to extract a 2d slice from a 3d
vtkImageData object. But I can't seem to get the recipe right. Am I doing it right?
I am also a bit confused about ResliceAxes Matrix. Does it represent a cutting plane? If
I move the ReSliceAxes origin will it also move the cutting plane? When I
call Update on the vtkImageReSlicer, the program crashes. But when I don't
call it, the output is empty.
Here's what I have so far.
#my input is any vtkactor that contains a closed curve of type vtkPolyData
ShapePolyData = actor.GetMapper().GetInput()
boundingBox = ShapePolyData.GetBounds()
for i in range(0,6,2):
delta = boundingBox[i+1]-boundingBox[i]
newBoundingBox.append(boundingBox[i]-0.5*delta)
newBoundingBox.append(boundingBox[i+1]+0.5*delta)
voxelizer = vtk.vtkVoxelModeller()
voxelizer.SetInputData(ShapePolyData)
voxelizer.SetModelBounds(newBoundingBox)
voxelizer.SetScalarTypeToBit()
voxelizer.SetForegroundValue(1)
voxelizer.SetBackgroundValue(0)
voxelizer.Update()
VoxelModel =voxelizer.GetOutput()
ImageOrigin = VoxelModel.GetOrigin()
slicer = vtk.vtkImageReslice()
#Am I setting the cutting axis here. x axis set at 1,0,0 , y axis at 0,1,0 and z axis at 0,0,1
slicer.SetResliceAxesDirectionCosines(1,0,0,0,1,0,0,0,1)
#if I increase the z value, will the cutting plane move up?
slicer.SetResliceAxesOrigin(ImageOrigin[0],ImageOrigin[1],ImageOrigin[2])
slicer.SetInputData(VoxelModel)
slicer.SetInterpolationModeToLinear()
slicer.SetOutputDimensionality(2)
slicer.Update() #this makes the code crash
voxelSurface = vtk.vtkContourFilter()
voxelSurface.SetInputConnection(slicer.GetOutputPort())
voxelSurface.SetValue(0, .999)
voxelMapper = vtk.vtkPolyDataMapper()
voxelMapper.SetInputConnection(voxelSurface.GetOutputPort())
voxelActor = vtk.vtkActor()
voxelActor.SetMapper(voxelMapper)
Renderer.AddActor(voxelActor)
I have never used vtkImageReslice, but I have used vtkExtractVOI for vtkImageData, which allows you to achieve a similar result, I think. Here is your example modified with the latter, instead:
ImageOrigin = VoxelModel.GetOrigin()
slicer = vtk.vtkExtractVOI()
slicer.SetInputData(VoxelModel)
#With the setVOI method you can define which slice you want to extract
slicer.SetVOI(xmin, xmax, ymin, ymax, zslice, zslice)
slicer.SetSampleRate(1, 1, 1)
slicer.Update()
voxelSurface = vtk.vtkContourFilter()
voxelSurface.SetInputConnection(slicer.GetOutputPort())
voxelSurface.SetValue(0, .999)
voxelMapper = vtk.vtkPolyDataMapper()
voxelMapper.SetInputConnection(voxelSurface.GetOutputPort())
voxelActor = vtk.vtkActor()
voxelActor.SetMapper(voxelMapper)
Renderer.AddActor(voxelActor)

Find rightmost/leftmost point of SVG path

How to find leftmost/rightmost point of SVG C (bezier curve) path segment? I know there is getBoundingClientRect() and getBBox() but none of them apply since they return only single coordinate of the point.
Just to avoid XY problem - I want to split single path composed of bezier curves into several paths each monotonously going from left to right (or right to left). It means that on any single path should be no 2 points having equal X coordinate. I understand that required split point may potentially be inside the bounding box of a segment thus not being leftmost/rightmost, but I'm almost sure that way of finding such point should use same techniques as finding horizontally extreme point.
You would need to iterate through the path length with .getPointAtLength(i) method, and then find the limits. Seemed like a fun thing to do so I made a quick and dirty implementation, this is the important part:
function findLimits(path) {
var boundingPoints = {
minX: {x: dimensions.width, y: dimensions.height},
minY: {x: dimensions.width, y: dimensions.height},
maxX: {x: 0, y: 0},
maxY: {x: 0, y: 0}
}
var l = path.getTotalLength();
for (var p = 0; p < l; p++) {
var coords = path.getPointAtLength(p);
if (coords.x < boundingPoints.minX.x) boundingPoints.minX = coords;
if (coords.y < boundingPoints.minY.y) boundingPoints.minY = coords;
if (coords.x > boundingPoints.maxX.x) boundingPoints.maxX = coords;
if (coords.y > boundingPoints.maxY.y) boundingPoints.maxY = coords;
}
return boundingPoints
}
You can find the implementation here: https://jsfiddle.net/4gus3hks/1/
Paul LeBeau's comment and fancy animation on the wiki inspired me for the solution. It is based mostly on following terms:
Values of parameter t from [0, 1] can be matched to the curve
points.
For any parameter value point on the curve can be constructed
step-by-step by linearly combining pairs of adjacent control points
into intermediate control points of higher "depth". This operation
can be repeated until only single point left - point on the curve
itself.
Coordinates of the intermediate points can be defined by
t-polynoms of degree equal to point "depth". And coefficients of
those polynoms ultimately depend only on coordinates of initial
control points.
Penultimate step of construction gives 2 points that define tangent
to the curve at the final point, and coordinates of those points are
controlled by quadratic polynom.
Having direction of tangent in question as vector allows to
construct quadratic equation against t where curve has required
tangent.
So, in fact, finding required points can be performed in constant O(1) time:
tangentPoints: function(tx, ty){
var ends = this.getPolynoms(2);
var tangent = [ends[1][0].subtractPoly(ends[0][0]),
ends[1][1].subtractPoly(ends[0][1])];
var eq = tangent[0].multiplyScalar(ty).subtractPoly(tangent[1].multiplyScalar(tx));
return solveQuadratic(...eq.values).filter(t => t >= 0 && t <= 1);
}
Full code with assisting Polynom class and visual demo I placed into this repo and fiddle

How to find number of Reference Planes passing through a selected wall.

I need to find out the number of Reference planes and their names which are passing through a selected wall. I can get all the reference planes for a particular document but how shall I do this for a particular wall.
You help would be appreciated!
Thanks.
If the ElementIntersectFilter doesn't work for your needs, you'll have to extract the geometry of the wall and reference plane and work with those directly.
Intersecting the reference planes with the wall solids can work, but there's a simpler answer that will work, if I understand your question correctly. I'm assuming you only want the walls where the green line of the ref plane intersects, rather than treating the reference plane object as an infinite geometric plane. In the screenshot below, I assume you want to find the checkmarks, but not the red X's. I'm also assuming you're looking at this as a plan exercise, and not specifically setting the vertical extents of the reference plane (this is just based on how I've seen most people use Revit). The following function takes as inputs a single wall and a list of ref planes (you mentioned you already have the collection of all ref planes) and will return a list of ref planes which intersect the wall.
public static List<ReferencePlane> getRefPlanesIntersectingWall( Wall wal, List<ReferencePlane> refPlanesIn)
{
//simplify this to a 2D problem, using the location curve of the wall
List<ReferencePlane> refPlanesOut = new List<ReferencePlane>();
LocationCurve wallLocation = wal.Location as LocationCurve;
Curve wallCurve = wallLocation.Curve;
Double wallZ = wallLocation.Curve.GetEndPoint(0).Z;
foreach (ReferencePlane rp in refPlanesIn)
{
XYZ startPt = new XYZ(rp.BubbleEnd.X, rp.BubbleEnd.Y, wallZ);
XYZ endPt = new XYZ(rp.FreeEnd.X, rp.FreeEnd.Y, wallZ);
Line rpLine = Line.CreateBound(startPt, endPt);
SetComparisonResult test = wallCurve.Intersect(rpLine);
if (test == SetComparisonResult.Overlap ||
test == SetComparisonResult.Subset ||
test == SetComparisonResult.Superset ||
test == SetComparisonResult.Equal )
{
refPlanesOut.Add(rp);
}
}
return refPlanesOut;
}
I would start by trying the built-in ElementIntersectFilter. The documentation has a nice example, replace "FamilyInstance" with "referencePlane" and that may do it.
http://www.revitapidocs.com/2017/19276b94-fa39-64bb-bfb8-c16967c83485.htm
If that doesn't work, you'll need to extract the solid of the wall and intersect with the reference plane.

How to check for convexity of a 3d mesh?

Is there a fast way to do this? Searching online shows convexity of functions or single polygons. But I need the ability to check this for the whole model. An object can have convex faces but can be concave as a whole like a torus.
Kneejerk: if you build a leafy BSP tree and end up with all your geometry at one node, the object is convex.
Slightly smarter way to approach the same solution: for each polygon, get the hyperplane. Make sure every vertex in the model is behind that hyperplane.
Equivalently: check the line segment between every pair of vertices; if it doesn't intersect any faces then the object is convex.
I guess you could also get the convex hull, via quickhull or whatever, and compare it to the original object. Or, similarly, get the convex hull and check that every vertex of the original object lies on a face of the hull.
For every face, compute the equation of the plane of support and check that all vertices* yield the same sign when plugged in the plane equation.
Will take time O(F.V), for F faces and V vertices.
*For safety, disregard the vertices of the face being processed.
Alternatively, compute the 3D convex hull, in time O(V.Log(V)). If at any stage in the algorithm a vertex gets discarded, then the polyhedron was not convex.
bool IsConvex(std::vector<vec3> &points, std::vector<int> &triangles, float threshold = 0.001)
{
for (unsigned long i = 0; i < triangles.size() / 3; i++)
{
vec3 Atmp = points[triangles[i * 3 + 0]];
vec3 Btmp = points[triangles[i * 3 + 1]];
vec3 Ctmp = points[triangles[i * 3 + 2]];
btVector3 A(Atmp.x, Atmp.y, Atmp.z);
btVector3 B(Btmp.x, Btmp.y, Btmp.z);
btVector3 C(Ctmp.x, Ctmp.y, Ctmp.z);
B -= A;
C -= A;
btVector3 BCNorm = B.cross(C).normalized();
float checkPoint = btVector3(points[0].x - A.x(), points[0].y - A.y(), points[0].z - A.z()).dot(BCNorm);
for (unsigned long j = 0; j < points.size(); j++)
{
float dist = btVector3(points[j].x - A.x(), points[j].y - A.y(), points[j].z - A.z()).dot(BCNorm);
if((std::abs(checkPoint) > threshold) && (std::abs(dist) > threshold) && (checkPoint * dist < 0))
{
return false;
}
}
}
return true;
}
trimesh is a Python library that can load a 3D mesh and evaluates if mesh is convex or not.
import trimesh
mesh = trimesh.load('my_mesh_file')
print(mesh.is_convex)
Code is given here.
It can be run from a command line with the following instructions:
python -m pip install trimesh
python -c "import trimesh; mesh = trimesh.load('my_mesh_file'); print(mesh.is_convex)"
You can accelerate the plane-vertex tests by adding all vertices to a tree structure first, so you can reject whole leaves if their bounds don't intersect the plane.
The BSP idea should actually be identical to testing all triangle planes, as no BSP leaf will be able to subdivide the set of vertices for a convex object.
You probably want to include an epsilon for your plane tests, as both floating point precision and modelling precision for manually created meshes can result in vertices slightly above a plane.

How to calculate area of intersection of an arbitrary triangle with a square?

So, I've been struggling with a frankly now infuriating problem all day today.
Given a set of verticies of a triangle on a plane (just 3 points, 6 free parameters), I need to calculate the area of intersection of this triangle with the unit square defined by {0,0} and {1,1}. (I choose this because any square in 2D can be transformed to this, and the same transformation can move the 3 vertices).
So, now the problem is simplified down to only 6 parameters, 3 points... which I think is short enough that I'd be willing to code up the full solution / find the full solution.
( I would like this to run on a GPU for literally more than 2 million triangles every <0.5 seconds, if possible. as for the need for simplification / no data structures / libraries)
In terms of my attempt at the solution, I've... got a list of ways I've come up with, none of which seem fast or ... specific to the nice case (too general).
Option 1: Find the enclosed polygon, it can be anything from a triangle up to a 6-gon. Do this by use of some intersection of convex polygon in O(n) time algorithms that I found. Then I would sort these intersection points (new vertices, up to 7 of them O(n log n) ), in either CW or CCw order, so that I can run a simple area algorithm on the points (based on Greens function) (O(n) again). This is the fastest i can come with for an arbitrary convex n-gon intersecting with another m-gon. However... my problem is definitely not that complex, its a special case, so it should have a better solution...
Option 2:
Since I know its a triangle and unit square, i can simply find the list of intersection points in a more brute force way (rather than using some algorithm that is ... frankly a little frustrating to implement, as listed above)
There are only 19 points to check. 4 points are corners of square inside of triangle. 3 points are triangle inside square. And then for each line of the triangle, each will intersect 4 lines from the square (eg. y=0, y=1, x=0, x=1 lines). that is another 12 points. so, 12+3+4 = 19 points to check.
Once I have the, at most 6, at fewest 3, points that do this intersection, i can then follow up with one of two methods that I can think of.
2a: Sort them by increasing x value, and simply decompose the shape into its sub triangle / 4-gon shapes, each with an easy formula based on the limiting top and bottom lines. sum up the areas.
or 2b: Again sort the intersection points in some cyclic way, and then calculate the area based on greens function.
Unfortunately, this still ends up being just as complex as far as I can tell. I can start breaking up all the cases a little more, for finding the intersection points, since i know its just 0s and 1s for the square, which makes the math drop out some terms.. but it's not necessarily simple.
Option 3: Start separating the problem based on various conditions. Eg. 0, 1, 2, or 3 points of triangle inside square. And then for each case, run through all possible number of intersections, and then for each of those cases of polygon shapes, write down the area solution uniquely.
Option 4: some formula with heaviside step functions. This is the one I want the most probably, I suspect it'll be a little... big, but maybe I'm optimistic that it is possible, and that it would be the fastest computationally run time once I have the formula.
--- Overall, I know that it can be solved using some high level library (clipper for instance). I also realize that writing general solutions isn't so hard when using data structures of various kinds (linked list, followed by sorting it). And all those cases would be okay, if I just needed to do this a few times. But, since I need to run it as an image processing step, on the order of >9 * 1024*1024 times per image, and I'm taking images at .. lets say 1 fps (technically I will want to push this speed up as fast as possible, but lower bound is 1 second to calculate 9 million of these triangle intersection area problems). This might not be possible on a CPU, which is fine, I'll probably end up implementing it in Cuda anyways, but I do want to push the limit of speed on this problem.
Edit: So, I ended up going with Option 2b. Since there are only 19 intersections possible, of which at most 6 will define the shape, I first find those 3 to 6 verticies. Then i sort them in a cyclic (CCW) order. And then I find the area by calculating the area of that polygon.
Here is my test code I wrote to do that (it's for Igor, but should be readable as pseudocode) Unfortunately it's a little long winded, but.. I think other than my crappy sorting algorithm (shouldn't be more than 20 swaps though, so not so much overhead for writing better sorting)... other than that sorting, I don't think I can make it any faster. Though, I am open to any suggestions or oversights I might have had in chosing this option.
function calculateAreaUnitSquare(xPos, yPos)
wave xPos
wave yPos
// First, make array of destination. Only 7 possible results at most for this geometry.
Make/o/N=(7) outputVertexX = NaN
Make/o/N=(7) outputVertexY = NaN
variable pointsfound = 0
// Check 4 corners of square
// Do this by checking each corner against the parameterized plane described by basis vectors p2-p0 and p1-p0.
// (eg. project onto point - p0 onto p2-p0 and onto p1-p0. Using appropriate parameterization scaling (not unit).
// Once we have the parameterizations, then it's possible to check if it is inside the triangle, by checking that u and v are bounded by u>0, v>0 1-u-v > 0
variable denom = yPos[0]*xPos[1]-xPos[0]*yPos[1]-yPos[0]*xPos[2]+yPos[1]*xPos[2]+xPos[0]*yPos[2]-xPos[1]*yPos[2]
//variable u00 = yPos[0]*xPos[1]-xPos[0]*yPos[1]-yPos[0]*Xx+yPos[1]*Xx+xPos[0]*Yx-xPos[1]*Yx
//variable v00 = -yPos[2]*Xx+yPos[0]*(Xx-xPos[2])+xPos[0]*(yPos[2]-Yx)+yPos[2]*Yx
variable u00 = (yPos[0]*xPos[1]-xPos[0]*yPos[1])/denom
variable v00 = (yPos[0]*(-xPos[2])+xPos[0]*(yPos[2]))/denom
variable u01 =(yPos[0]*xPos[1]-xPos[0]*yPos[1]+xPos[0]-xPos[1])/denom
variable v01 =(yPos[0]*(-xPos[2])+xPos[0]*(yPos[2]-1)+xPos[2])/denom
variable u11 = (yPos[0]*xPos[1]-xPos[0]*yPos[1]-yPos[0]+yPos[1]+xPos[0]-xPos[1])/denom
variable v11 = (-yPos[2]+yPos[0]*(1-xPos[2])+xPos[0]*(yPos[2]-1)+xPos[2])/denom
variable u10 = (yPos[0]*xPos[1]-xPos[0]*yPos[1]-yPos[0]+yPos[1])/denom
variable v10 = (-yPos[2]+yPos[0]*(1-xPos[2])+xPos[0]*(yPos[2]))/denom
if(u00 >= 0 && v00 >=0 && (1-u00-v00) >=0)
outputVertexX[pointsfound] = 0
outputVertexY[pointsfound] = 0
pointsfound+=1
endif
if(u01 >= 0 && v01 >=0 && (1-u01-v01) >=0)
outputVertexX[pointsfound] = 0
outputVertexY[pointsfound] = 1
pointsfound+=1
endif
if(u10 >= 0 && v10 >=0 && (1-u10-v10) >=0)
outputVertexX[pointsfound] = 1
outputVertexY[pointsfound] = 0
pointsfound+=1
endif
if(u11 >= 0 && v11 >=0 && (1-u11-v11) >=0)
outputVertexX[pointsfound] = 1
outputVertexY[pointsfound] = 1
pointsfound+=1
endif
// Check 3 points for triangle. This is easy, just see if its bounded in the unit square. if it is, add it.
variable i = 0
for(i=0; i<3; i+=1)
if(xPos[i] >= 0 && xPos[i] <= 1 )
if(yPos[i] >=0 && yPos[i] <=1)
if(!((xPos[i] == 0 || xPos[i] == 1) && (yPos[i] == 0 || yPos[i] == 1) ))
outputVertexX[pointsfound] = xPos[i]
outputVertexY[pointsfound] = yPos[i]
pointsfound+=1
endif
endif
endif
endfor
// Check intersections.
// Procedure is: loop over 3 lines of triangle.
// For each line
// Check if vertical
// If not vertical, find y intercept with x=0 and x=1 lines.
// if y intercept is between 0 and 1, then add the point
// Check if horizontal
// if not horizontal, find x intercept with y=0 and y=1 lines
// if x intercept is between 0 and 1, then add the point
for(i=0; i<3; i+=1)
variable iN = mod(i+1,3)
if(xPos[i] != xPos[iN])
variable tx0 = xPos[i]/(xPos[i] - xPos[iN])
variable tx1 = (xPos[i]-1)/(xPos[i] - xPos[iN])
if(tx0 >0 && tx0 < 1)
variable yInt = (yPos[iN]-yPos[i])*tx0+yPos[i]
if(yInt > 0 && yInt <1)
outputVertexX[pointsfound] = 0
outputVertexY[pointsfound] = yInt
pointsfound+=1
endif
endif
if(tx1 >0 && tx1 < 1)
yInt = (yPos[iN]-yPos[i])*tx1+yPos[i]
if(yInt > 0 && yInt <1)
outputVertexX[pointsfound] = 1
outputVertexY[pointsfound] = yInt
pointsfound+=1
endif
endif
endif
if(yPos[i] != yPos[iN])
variable ty0 = yPos[i]/(yPos[i] - yPos[iN])
variable ty1 = (yPos[i]-1)/(yPos[i] - yPos[iN])
if(ty0 >0 && ty0 < 1)
variable xInt = (xPos[iN]-xPos[i])*ty0+xPos[i]
if(xInt > 0 && xInt <1)
outputVertexX[pointsfound] = xInt
outputVertexY[pointsfound] = 0
pointsfound+=1
endif
endif
if(ty1 >0 && ty1 < 1)
xInt = (xPos[iN]-xPos[i])*ty1+xPos[i]
if(xInt > 0 && xInt <1)
outputVertexX[pointsfound] = xInt
outputVertexY[pointsfound] = 1
pointsfound+=1
endif
endif
endif
endfor
// Now we have all 6 verticies that we need. Next step: find the lowest y point of the verticies
// if there are multiple with same low y point, find lowest X of these.
// swap this vertex to be first vertex.
variable lowY = 1
variable lowX = 1
variable m = 0;
for (i=0; i<pointsfound ; i+=1)
if (outputVertexY[i] < lowY)
m=i
lowY = outputVertexY[i]
lowX = outputVertexX[i]
elseif(outputVertexY[i] == lowY)
if(outputVertexX[i] < lowX)
m=i
lowY = outputVertexY[i]
lowX = outputVertexX[i]
endif
endif
endfor
outputVertexX[m] = outputVertexX[0]
outputVertexY[m] = outputVertexY[0]
outputVertexX[0] = lowX
outputVertexY[0] = lowY
// now we have the bottom left corner point, (bottom prefered).
// calculate the cos(theta) of unit x hat vector to the other verticies
make/o/N=(pointsfound) angles = (p!=0)?( (outputVertexX[p]-lowX) / sqrt( (outputVertexX[p]-lowX)^2+(outputVertexY[p]-lowY)^2) ) : 0
// Now sort the remaining verticies based on this angle offset. This will orient the points for a convex polygon in its maximal size / ccw orientation
// (This sort is crappy, but there will be in theory, at most 25 swaps. Which in the grand sceme of operations, isn't so bad.
variable j
for(i=1; i<pointsfound; i+=1)
for(j=i+1; j<pointsfound; j+=1)
if( angles[j] > angles[i] )
variable tempX = outputVertexX[j]
variable tempY = outputVertexY[j]
outputVertexX[j] = outputVertexX[i]
outputVertexY[j] =outputVertexY[i]
outputVertexX[i] = tempX
outputVertexY[i] = tempY
variable tempA = angles[j]
angles[j] = angles[i]
angles[i] = tempA
endif
endfor
endfor
// Now the list is ordered!
// now calculate the area given a list of CCW oriented points on a convex polygon.
// has a simple and easy math formula : http://www.mathwords.com/a/area_convex_polygon.htm
variable totA = 0
for(i = 0; i<pointsfound; i+=1)
totA += outputVertexX[i]*outputVertexY[mod(i+1,pointsfound)] - outputVertexY[i]*outputVertexX[mod(i+1,pointsfound)]
endfor
totA /= 2
return totA
end
I think the Cohen-Sutherland line-clipping algorithm is your friend here.
First off check the bounding box of the triangle against the square to catch the trivial cases (triangle inside square, triangle outside square).
Next check for the case where the square lies completely within the triangle.
Next consider your triangle vertices A, B and C in clockwise order. Clip the line segments AB, BC and CA against the square. They will either be altered such that they lie within the square or are found to lie outside, in which case they can be ignored.
You now have an ordered list of up to three line segments that define the some of the edges intersection polygon. It is easy to work out how to traverse from one edge to the next to find the other edges of the intersection polygon. Consider the endpoint of one line segment (e) against the start of the next (s)
If e is coincident with s, as would be the case when a triangle vertex lies within the square, then no traversal is required.
If e and s differ, then we need to traverse clockwise around the boundary of the square.
Note that this traversal will be in clockwise order, so there is no need to compute the vertices of the intersection shape, sort them into order and then compute the area. The area can be computed as you go without having to store the vertices.
Consider the following examples:
In the first case:
We clip the lines AB, BC and CA against the square, producing the line segments ab>ba and ca>ac
ab>ba forms the first edge of the intersection polygon
To traverse from ba to ca: ba lies on y=1, while ca does not, so the next edge is ca>(1,1)
(1,1) and ca both lie on x=1, so the next edge is (1,1)>ca
The next edge is a line segment we already have, ca>ac
ac and ab are coincident, so no traversal is needed (you might be as well just computing the area for a degenerate edge and avoiding the branch in these cases)
In the second case, clipping the triangle edges against the square gives us ab>ba, bc>cb and ca>ac. Traversal between these segments is trivial as the start and end points lie on the same square edges.
In the third case the traversal from ba to ca goes through two square vertices, but it is still a simple matter of comparing the square edges on which they lie:
ba lies on y=1, ca does not, so next vertex is (1,1)
(1,1) lies on x=1, ca does not, so next vertex is (1,0)
(1,0) lies on y=0, as does ca, so next vertex is ca.
Given the large number of triangles I would recommend scanline algorithm: sort all the points 1st by X and 2nd by Y, then proceed in X direction with a "scan line" that keeps a heap of Y-sorted intersections of all lines with that line. This approach has been widely used for Boolean operations on large collections of polygons: operations such as AND, OR, XOR, INSIDE, OUTSIDE, etc. all take O(n*log(n)).
It should be fairly straightforward to augment Boolean AND operation, implemented with the scanline algorithm to find the areas you need. The complexity will remain O(n*log(n)) on the number of triangles. The algorithm would also apply to intersections with arbitrary collections of arbitrary polygons, in case you would need to extend to that.
On the 2nd thought, if you don't need anything other than the triangle areas, you could do that in O(n), and scanline may be an overkill.
I came to this question late, but I think I've come up with a more fully flushed out solution along the lines of ryanm's answer. I'll give an outline of for others trying to do this problem at least somewhat efficiently.
First you have two trivial cases to check:
1) Triangle lies entirely within the square
2) Square lies entirely within the triangle (Just check if all corners are inside the triangle)
If neither is true, then things get interesting.
First, use either the Cohen-Sutherland or Liang-Barsky algorithm to clip each edge of the triangle to the square. (The linked article contains a nice bit of code that you can essentially just copy-paste if you're using C).
Given a triangle edge, these algorithms will output either a clipped edge or a flag denoting that the edge lies entirely outside the square. If all edges lie outsize the square, then the triangle and the square are disjoint.
Otherwise, we know that the endpoints of the clipped edges constitute at least some of the vertices of the polygon representing the intersection.
We can avoid a tedious case-wise treatment by making a simple observation. All other vertices of the intersection polygon, if any, will be corners of the square that lie inside the triangle.
Simply put, the vertices of the intersection polygon will be the (unique) endpoints of the clipped triangle edges in addition to the corners of the square inside the triangle.
We'll assume that we want to order these vertices in a counter-clockwise fashion. Since the intersection polygon will always be convex, we can compute its centroid (the mean over all vertex positions) which will lie inside the polygon.
Then to each vertex, we can assign an angle using the atan2 function where the inputs are the y- and x- coordinates of the vector obtained by subtracting the centroid from the position of the vertex (i.e. the vector from the centroid to the vertex).
Finally, the vertices can be sorted in ascending order based on the values of the assigned angles, which constitutes a counter-clockwise ordering. Successive pairs of vertices correspond to the polygon edges.

Resources