| library graphlib.layout.charted.intersect.polygon; |
| |
| import "dart:math" as Math; |
| import "line.dart"; |
| |
| /// Returns the point ({x, y}) at which the point argument intersects with the |
| /// node argument assuming that it has the shape specified by polygon. |
| intersectPolygon(node, polyPoints, point) { |
| var x1 = node.x; |
| var y1 = node.y; |
| |
| var intersections = []; |
| |
| var minX = double.INFINITY, |
| minY = double.INFINITY; |
| polyPoints.forEach((entry) { |
| minX = Math.min(minX, entry.x); |
| minY = Math.min(minY, entry.y); |
| }); |
| |
| var left = x1 - node.width / 2 - minX; |
| var top = y1 - node.height / 2 - minY; |
| |
| for (var i = 0; i < polyPoints.length; i++) { |
| var p1 = polyPoints[i]; |
| var p2 = polyPoints[i < polyPoints.length - 1 ? i + 1 : 0]; |
| var intersect = intersectLine(node, point, |
| {"x": left + p1.x, "y": top + p1.y}, {"x": left + p2.x, "y": top + p2.y}); |
| if (intersect) { |
| intersections.push(intersect); |
| } |
| } |
| |
| if (!intersections.length) { |
| print("NO INTERSECTION FOUND, RETURN NODE CENTER: $node"); |
| return node; |
| } |
| |
| if (intersections.length > 1) { |
| // More intersections, find the one nearest to edge end point |
| intersections.sort((p, q) { |
| var pdx = p.x - point.x, |
| pdy = p.y - point.y, |
| distp = Math.sqrt(pdx * pdx + pdy * pdy), |
| |
| qdx = q.x - point.x, |
| qdy = q.y - point.y, |
| distq = Math.sqrt(qdx * qdx + qdy * qdy); |
| |
| return (distp < distq) ? -1 : (distp == distq ? 0 : 1); |
| }); |
| } |
| return intersections[0]; |
| } |