| | |
| | | package lujing; |
| | | |
| | | import java.util.ArrayList; |
| | | import java.util.Collections; |
| | | import java.util.List; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * 异形(无障碍物)草地路径规划类 - 优化版 V2.0 |
| | | * * 功能特点: |
| | | * 1. 自动处理凹多边形(通过耳切法分割) |
| | | * 2. 增加“围边”路径,保证边缘割草整洁 |
| | | * 3. 自动计算每个子区域的最优扫描角度(减少掉头次数) |
| | | * 4. 智能区域连接(支持双向路径选择) |
| | | * 异形草地路径规划 - 凹多边形兼容优化版 V5.0 |
| | | * 修复:解决凹多边形扫描线跨越边界的问题,优化路径对齐 |
| | | */ |
| | | public class YixinglujingNoObstacle { |
| | | |
| | | // ========================================== |
| | | // 对外接口 |
| | | // ========================================== |
| | | |
| | | /** |
| | | * 规划异形草地割草路径 |
| | | * |
| | | * @param coordinates 地块边界坐标字符串,格式:"x1,y1;x2,y2;x3,y3;..." |
| | | * @param widthStr 割草宽度(米),如 "0.34" |
| | | * @param marginStr 安全边距(米),如 "0.2" |
| | | * @return 路径段列表 |
| | | */ |
| | | // 用法说明(无障碍物路径规划): |
| | | // - 方法用途:根据地块边界、割草宽度与安全边距,生成覆盖全区域的割草路径。 |
| | | // - 参数: |
| | | // coordinates:地块边界坐标字符串,格式 "x1,y1;x2,y2;...",至少3个点,单位为米。 |
| | | // widthStr:割草宽度(字符串,单位米),用于确定扫描线间距。 |
| | | // marginStr:安全边距(字符串,单位米),用于将地块边界向内收缩,避免贴边作业。 |
| | | // - 返回值:List<PathSegment>,其中 PathSegment.start/end 为坐标点,isMowing 为 true 表示割草段,false 表示空走段。 |
| | | // - 失败情况:当边界点不足或内缩后区域过小,返回空列表。 |
| | | // - 使用示例: |
| | | // String boundary = "0,0;20,0;20,15;0,15"; |
| | | // String width = "0.3"; |
| | | // String margin = "0.5"; |
| | | // List<YixinglujingNoObstacle.PathSegment> path = |
| | | // YixinglujingNoObstacle.planPath(boundary, width, margin); |
| | | public static List<PathSegment> planPath(String coordinates, String widthStr, String marginStr) { |
| | | // 1. 参数解析与预处理 |
| | | List<Point> rawPoints = parseCoordinates(coordinates); |
| | | if (rawPoints.size() < 3) { |
| | | throw new IllegalArgumentException("多边形点数不足,无法构成地块"); |
| | | } |
| | | // 确保逆时针顺序,方便后续几何计算 |
| | | ensureCounterClockwise(rawPoints); |
| | | if (rawPoints.size() < 3) return new ArrayList<>(); |
| | | |
| | | double mowWidth = Double.parseDouble(widthStr); |
| | | double safeMargin = Double.parseDouble(marginStr); |
| | | |
| | | // 1. 预处理:确保逆时针顺序 |
| | | ensureCounterClockwise(rawPoints); |
| | | |
| | | // 2. 生成内缩多边形(安全边界) |
| | | List<Point> boundary = getInsetPolygon(rawPoints, safeMargin); |
| | | if (boundary.size() < 3) return new ArrayList<>(); |
| | | |
| | | // 3. 确定最优作业角度 |
| | | double bestAngle = findOptimalAngle(boundary); |
| | | |
| | | // 4. 获取首个作业点,用于对齐围边起点 |
| | | Point firstScanStart = getFirstScanPoint(boundary, mowWidth, bestAngle); |
| | | |
| | | // 5. 对齐围边:使围边最后结束于靠近扫描起点的位置 |
| | | List<Point> alignedBoundary = alignBoundaryStart(boundary, firstScanStart); |
| | | |
| | | List<PathSegment> finalPath = new ArrayList<>(); |
| | | |
| | | // 2. 生成围边路径 (Contour Path) |
| | | // 这一步先规划一圈轮廓,解决异形边缘难处理的问题 |
| | | List<Point> contourPoly = getInsetPolygon(rawPoints, safeMargin); |
| | | |
| | | // 如果内缩后面积太小或点数不足,直接返回空 |
| | | if (contourPoly.size() < 3) { |
| | | return new ArrayList<>(); |
| | | // 6. 第一阶段:围边路径 |
| | | for (int i = 0; i < alignedBoundary.size(); i++) { |
| | | Point pStart = alignedBoundary.get(i); |
| | | Point pEnd = alignedBoundary.get((i + 1) % alignedBoundary.size()); |
| | | finalPath.add(new PathSegment(pStart, pEnd, true)); |
| | | } |
| | | |
| | | // 将围边路径加入结果 |
| | | for (int i = 0; i < contourPoly.size(); i++) { |
| | | Point p1 = contourPoly.get(i); |
| | | Point p2 = contourPoly.get((i + 1) % contourPoly.size()); |
| | | finalPath.add(new PathSegment(p1, p2, true)); // true = 割草 |
| | | } |
| | | // 7. 第二阶段:生成内部扫描路径(修复凹部空越问题) |
| | | Point lastEdgePos = alignedBoundary.get(0); |
| | | List<PathSegment> scanPath = generateGlobalScanPath(boundary, mowWidth, bestAngle, lastEdgePos); |
| | | |
| | | // 记录围边结束后的位置(通常回到围边起点) |
| | | Point endOfContour = contourPoly.get(0); |
| | | finalPath.addAll(scanPath); |
| | | |
| | | // 3. 区域分割 (Decomposition) |
| | | // 使用耳切法将围边后的多边形分割为多个凸多边形(三角形) |
| | | // 这样可以保证覆盖无遗漏 |
| | | List<List<Point>> triangles = triangulatePolygon(contourPoly); |
| | | |
| | | // 4. 对每个区域生成内部填充路径 |
| | | List<List<PathSegment>> allRegionPaths = new ArrayList<>(); |
| | | |
| | | for (List<Point> triangle : triangles) { |
| | | // 【优化】寻找最优扫描角度: |
| | | // 遍历三角形的三条边,计算以哪条边为基准扫描时,生成的行数最少(转弯最少) |
| | | List<PathSegment> regionPath = planConvexPathOptimal(triangle, mowWidth); |
| | | if (!regionPath.isEmpty()) { |
| | | allRegionPaths.add(regionPath); |
| | | } |
| | | // 8. 格式化坐标:保留两位小数 |
| | | for (PathSegment segment : finalPath) { |
| | | segment.start.x = Math.round(segment.start.x * 100.0) / 100.0; |
| | | segment.start.y = Math.round(segment.start.y * 100.0) / 100.0; |
| | | segment.end.x = Math.round(segment.end.x * 100.0) / 100.0; |
| | | segment.end.y = Math.round(segment.end.y * 100.0) / 100.0; |
| | | } |
| | | |
| | | // 5. 连接所有内部区域 (Greedy Connection) |
| | | // 从围边结束点开始,寻找最近的下一个区域 |
| | | List<PathSegment> internalPaths = connectRegions(allRegionPaths, endOfContour); |
| | | finalPath.addAll(internalPaths); |
| | | |
| | | return finalPath; |
| | | } |
| | | |
| | | // ========================================== |
| | | // 核心规划算法 |
| | | // ========================================== |
| | | private static List<PathSegment> generateGlobalScanPath(List<Point> polygon, double width, double angle, Point currentPos) { |
| | | List<PathSegment> segments = new ArrayList<>(); |
| | | List<Point> rotatedPoly = new ArrayList<>(); |
| | | for (Point p : polygon) rotatedPoly.add(rotatePoint(p, -angle)); |
| | | |
| | | /** |
| | | * 规划凸多边形路径,自动选择最优角度 |
| | | */ |
| | | private static List<PathSegment> planConvexPathOptimal(List<Point> polygon, double width) { |
| | | if (polygon.size() < 3) return new ArrayList<>(); |
| | | |
| | | double bestAngle = 0; |
| | | double minLines = Double.MAX_VALUE; |
| | | |
| | | // 遍历多边形的每一条边,尝试以该边角度进行扫描 |
| | | for (int i = 0; i < polygon.size(); i++) { |
| | | Point p1 = polygon.get(i); |
| | | Point p2 = polygon.get((i + 1) % polygon.size()); |
| | | |
| | | // 计算边的角度 |
| | | double angle = Math.atan2(p2.y - p1.y, p2.x - p1.x); |
| | | |
| | | // 计算在这个角度下,多边形的垂直投影高度 |
| | | // 高度越小,意味着沿此方向扫描的行数越少,效率越高 |
| | | double height = calculatePolygonHeight(polygon, -angle); |
| | | |
| | | if (height < minLines) { |
| | | minLines = height; |
| | | bestAngle = angle; |
| | | } |
| | | } |
| | | |
| | | // 使用最佳角度生成路径 |
| | | return generatePathWithAngle(polygon, width, bestAngle); |
| | | } |
| | | |
| | | /** |
| | | * 根据指定角度生成弓字形路径 |
| | | */ |
| | | private static List<PathSegment> generatePathWithAngle(List<Point> polygon, double width, double angle) { |
| | | // 1. 将多边形旋转到水平位置 |
| | | List<Point> rotatedPoints = new ArrayList<>(); |
| | | for (Point p : polygon) { |
| | | rotatedPoints.add(rotatePoint(p, -angle)); |
| | | } |
| | | |
| | | // 2. 计算Y轴范围 |
| | | double minY = Double.MAX_VALUE; |
| | | double maxY = -Double.MAX_VALUE; |
| | | for (Point p : rotatedPoints) { |
| | | double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE; |
| | | for (Point p : rotatedPoly) { |
| | | minY = Math.min(minY, p.y); |
| | | maxY = Math.max(maxY, p.y); |
| | | } |
| | | |
| | | List<PathSegment> segments = new ArrayList<>(); |
| | | boolean leftToRight = true; |
| | | // 步长 y 从最小到最大扫描 |
| | | for (double y = minY + width/2; y <= maxY - width/2; y += width) { |
| | | List<Double> xIntersections = getXIntersections(rotatedPoly, y); |
| | | if (xIntersections.size() < 2) continue; |
| | | Collections.sort(xIntersections); |
| | | |
| | | // 3. 扫描线生成 (从 minY + width/2 开始,保证第一刀切在多边形内) |
| | | for (double y = minY + width / 2; y <= maxY; y += width) { |
| | | List<Double> intersections = new ArrayList<>(); |
| | | for (int i = 0; i < rotatedPoints.size(); i++) { |
| | | Point p1 = rotatedPoints.get(i); |
| | | Point p2 = rotatedPoints.get((i + 1) % rotatedPoints.size()); |
| | | |
| | | // 判断扫描线是否穿过边 |
| | | if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) { |
| | | double x = p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y); |
| | | intersections.add(x); |
| | | // 处理凹多边形:每两个点组成一个有效作业段 |
| | | List<PathSegment> lineSegmentsInRow = new ArrayList<>(); |
| | | for (int i = 0; i < xIntersections.size() - 1; i += 2) { |
| | | Point pS = rotatePoint(new Point(xIntersections.get(i), y), angle); |
| | | Point pE = rotatePoint(new Point(xIntersections.get(i + 1), y), angle); |
| | | lineSegmentsInRow.add(new PathSegment(pS, pE, true)); |
| | | } |
| | | |
| | | // 根据当前S型方向排序作业段 |
| | | if (!leftToRight) { |
| | | Collections.reverse(lineSegmentsInRow); |
| | | for (PathSegment s : lineSegmentsInRow) { |
| | | Point temp = s.start; s.start = s.end; s.end = temp; |
| | | } |
| | | } |
| | | Collections.sort(intersections); |
| | | |
| | | // 成对生成线段 |
| | | for (int k = 0; k < intersections.size() - 1; k += 2) { |
| | | double x1 = leftToRight ? intersections.get(k) : intersections.get(k + 1); |
| | | double x2 = leftToRight ? intersections.get(k + 1) : intersections.get(k); |
| | | |
| | | Point start = new Point(x1, y); |
| | | Point end = new Point(x2, y); |
| | | |
| | | // 旋转回原始坐标系 |
| | | Point originalStart = rotatePoint(start, angle); |
| | | Point originalEnd = rotatePoint(end, angle); |
| | | |
| | | // 连接逻辑:如果不是第一段,需要从上一段终点连过来 |
| | | if (!segments.isEmpty()) { |
| | | PathSegment prev = segments.get(segments.size() - 1); |
| | | // 添加连接线(通常算作割草路径的一部分,保持弓字形连续) |
| | | segments.add(new PathSegment(prev.end, originalStart, true)); |
| | | // 将作业段连接到总路径 |
| | | for (PathSegment s : lineSegmentsInRow) { |
| | | if (Math.hypot(currentPos.x - s.start.x, currentPos.y - s.start.y) > 0.01) { |
| | | // 如果间距大于1cm,添加空走路径 |
| | | addSafeConnection(segments, currentPos, s.start, polygon); |
| | | } |
| | | |
| | | segments.add(new PathSegment(originalStart, originalEnd, true)); |
| | | segments.add(s); |
| | | currentPos = s.end; |
| | | } |
| | | leftToRight = !leftToRight; // 换向 |
| | | leftToRight = !leftToRight; |
| | | } |
| | | |
| | | return segments; |
| | | } |
| | | |
| | | /** |
| | | * 连接所有分割后的区域 (贪心策略 + 双向优化) |
| | | */ |
| | | private static List<PathSegment> connectRegions(List<List<PathSegment>> regions, Point startPoint) { |
| | | List<PathSegment> result = new ArrayList<>(); |
| | | if (regions.isEmpty()) return result; |
| | | |
| | | List<List<PathSegment>> remaining = new ArrayList<>(regions); |
| | | Point currentPos = startPoint; |
| | | |
| | | while (!remaining.isEmpty()) { |
| | | int bestIndex = -1; |
| | | double minDist = Double.MAX_VALUE; |
| | | boolean needReverse = false; |
| | | |
| | | // 寻找离当前位置最近的区域起点或终点 |
| | | for (int i = 0; i < remaining.size(); i++) { |
| | | List<PathSegment> region = remaining.get(i); |
| | | Point pStart = region.get(0).start; |
| | | Point pEnd = region.get(region.size() - 1).end; |
| | | |
| | | double dStart = distance(currentPos, pStart); |
| | | double dEnd = distance(currentPos, pEnd); |
| | | |
| | | // 检查正向进入 |
| | | if (dStart < minDist) { |
| | | minDist = dStart; |
| | | bestIndex = i; |
| | | needReverse = false; |
| | | } |
| | | // 检查反向进入(倒着割草如果更近) |
| | | if (dEnd < minDist) { |
| | | minDist = dEnd; |
| | | bestIndex = i; |
| | | needReverse = true; |
| | | } |
| | | } |
| | | |
| | | if (bestIndex != -1) { |
| | | List<PathSegment> targetRegion = remaining.remove(bestIndex); |
| | | |
| | | if (needReverse) { |
| | | // 反转该区域的所有路径 |
| | | List<PathSegment> reversedRegion = new ArrayList<>(); |
| | | for (int k = targetRegion.size() - 1; k >= 0; k--) { |
| | | PathSegment seg = targetRegion.get(k); |
| | | // 交换起点终点 |
| | | reversedRegion.add(new PathSegment(seg.end, seg.start, seg.isMowing)); |
| | | } |
| | | targetRegion = reversedRegion; |
| | | } |
| | | |
| | | // 添加过渡路径(抬刀移动,isMowing=false) |
| | | Point nextStart = targetRegion.get(0).start; |
| | | // 只有距离显著才添加移动段 |
| | | if (distance(currentPos, nextStart) > 0.01) { |
| | | result.add(new PathSegment(currentPos, nextStart, false)); |
| | | } |
| | | |
| | | result.addAll(targetRegion); |
| | | currentPos = targetRegion.get(targetRegion.size() - 1).end; |
| | | } else { |
| | | break; // 防御性代码 |
| | | } |
| | | } |
| | | return result; |
| | | private static Point getFirstScanPoint(List<Point> polygon, double width, double angle) { |
| | | List<Point> rotatedPoly = new ArrayList<>(); |
| | | for (Point p : polygon) rotatedPoly.add(rotatePoint(p, -angle)); |
| | | double minY = Double.MAX_VALUE; |
| | | for (Point p : rotatedPoly) minY = Math.min(minY, p.y); |
| | | |
| | | double firstY = minY + width/2; |
| | | List<Double> xInter = getXIntersections(rotatedPoly, firstY); |
| | | if (xInter.isEmpty()) return polygon.get(0); |
| | | Collections.sort(xInter); |
| | | return rotatePoint(new Point(xInter.get(0), firstY), angle); |
| | | } |
| | | |
| | | // ========================================== |
| | | // 几何运算辅助方法 |
| | | // ========================================== |
| | | private static List<Point> alignBoundaryStart(List<Point> boundary, Point targetStart) { |
| | | int bestIdx = 0; |
| | | double minDist = Double.MAX_VALUE; |
| | | for (int i = 0; i < boundary.size(); i++) { |
| | | double d = Math.hypot(boundary.get(i).x - targetStart.x, boundary.get(i).y - targetStart.y); |
| | | if (d < minDist) { minDist = d; bestIdx = i; } |
| | | } |
| | | List<Point> aligned = new ArrayList<>(); |
| | | for (int i = 0; i < boundary.size(); i++) { |
| | | aligned.add(boundary.get((bestIdx + i) % boundary.size())); |
| | | } |
| | | return aligned; |
| | | } |
| | | |
| | | /** |
| | | * 内缩多边形 (基于角平分线) |
| | | */ |
| | | private static List<Point> getInsetPolygon(List<Point> points, double margin) { |
| | | private static List<Double> getXIntersections(List<Point> rotatedPoly, double y) { |
| | | List<Double> xIntersections = new ArrayList<>(); |
| | | double tolerance = 1e-6; |
| | | |
| | | for (int i = 0; i < rotatedPoly.size(); i++) { |
| | | Point p1 = rotatedPoly.get(i); |
| | | Point p2 = rotatedPoly.get((i + 1) % rotatedPoly.size()); |
| | | |
| | | // 跳过水平边(避免与扫描线重合时的特殊情况) |
| | | if (Math.abs(p1.y - p2.y) < tolerance) { |
| | | continue; |
| | | } |
| | | |
| | | // 检查是否相交(使用严格不等式避免顶点重复) |
| | | if ((p1.y < y && p2.y >= y) || (p2.y < y && p1.y >= y)) { |
| | | double x = p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y); |
| | | // 简单去重:检查是否已存在相近的点 |
| | | boolean isDuplicate = false; |
| | | for (double existingX : xIntersections) { |
| | | if (Math.abs(x - existingX) < tolerance) { |
| | | isDuplicate = true; |
| | | break; |
| | | } |
| | | } |
| | | if (!isDuplicate) { |
| | | xIntersections.add(x); |
| | | } |
| | | } |
| | | } |
| | | return xIntersections; |
| | | } |
| | | |
| | | private static double findOptimalAngle(List<Point> polygon) { |
| | | double bestAngle = 0; |
| | | double minHeight = Double.MAX_VALUE; |
| | | for (int i = 0; i < polygon.size(); i++) { |
| | | Point p1 = polygon.get(i), p2 = polygon.get((i + 1) % polygon.size()); |
| | | double angle = Math.atan2(p2.y - p1.y, p2.x - p1.x); |
| | | double h = calculateHeightAtAngle(polygon, angle); |
| | | if (h < minHeight) { minHeight = h; bestAngle = angle; } |
| | | } |
| | | return bestAngle; |
| | | } |
| | | |
| | | private static double calculateHeightAtAngle(List<Point> poly, double angle) { |
| | | double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE; |
| | | for (Point p : poly) { |
| | | Point rp = rotatePoint(p, -angle); |
| | | minY = Math.min(minY, rp.y); maxY = Math.max(maxY, rp.y); |
| | | } |
| | | return maxY - minY; |
| | | } |
| | | |
| | | public static List<Point> getInsetPolygon(List<Point> points, double margin) { |
| | | List<Point> result = new ArrayList<>(); |
| | | int n = points.size(); |
| | | |
| | | for (int i = 0; i < n; i++) { |
| | | Point pPrev = points.get((i - 1 + n) % n); |
| | | Point pCurr = points.get(i); |
| | | Point pNext = points.get((i + 1) % n); |
| | | |
| | | Point v1 = new Point(pCurr.x - pPrev.x, pCurr.y - pPrev.y); |
| | | Point v2 = new Point(pNext.x - pCurr.x, pNext.y - pCurr.y); |
| | | double d1x = pCurr.x - pPrev.x, d1y = pCurr.y - pPrev.y; |
| | | double l1 = Math.hypot(d1x, d1y); |
| | | double d2x = pNext.x - pCurr.x, d2y = pNext.y - pCurr.y; |
| | | double l2 = Math.hypot(d2x, d2y); |
| | | |
| | | double len1 = Math.hypot(v1.x, v1.y); |
| | | double len2 = Math.hypot(v2.x, v2.y); |
| | | if (l1 < 1e-6 || l2 < 1e-6) continue; |
| | | |
| | | if (len1 < 1e-6 || len2 < 1e-6) continue; |
| | | // 单位法向量 |
| | | double n1x = -d1y / l1, n1y = d1x / l1; |
| | | double n2x = -d2y / l2, n2y = d2x / l2; |
| | | |
| | | // 归一化向量 |
| | | Point n1 = new Point(v1.x / len1, v1.y / len1); |
| | | Point n2 = new Point(v2.x / len2, v2.y / len2); |
| | | // 角平分线方向 |
| | | double bisectorX = n1x + n2x, bisectorY = n1y + n2y; |
| | | double bLen = Math.hypot(bisectorX, bisectorY); |
| | | if (bLen < 1e-6) { bisectorX = n1x; bisectorY = n1y; } |
| | | else { bisectorX /= bLen; bisectorY /= bLen; } |
| | | |
| | | // 计算平分线方向 |
| | | // v1反向 + v2 |
| | | Point bisector = new Point(-n1.x + n2.x, -n1.y + n2.y); |
| | | double biLen = Math.hypot(bisector.x, bisector.y); |
| | | double cosHalfAngle = n1x * bisectorX + n1y * bisectorY; |
| | | double dist = margin / Math.max(cosHalfAngle, 0.1); |
| | | |
| | | // 计算半角 sin(theta/2) |
| | | double cross = n1.x * n2.y - n1.y * n2.x; // 叉积判断转向 |
| | | |
| | | // 默认向左侧内缩 (CCW多边形) |
| | | if (biLen < 1e-6) { |
| | | // 共线,沿法线方向 |
| | | bisector = new Point(-n1.y, n1.x); |
| | | } else { |
| | | bisector.x /= biLen; |
| | | bisector.y /= biLen; |
| | | } |
| | | // 限制最大位移量,防止极尖角畸变 |
| | | dist = Math.min(dist, margin * 5); |
| | | |
| | | // 计算偏移距离 |
| | | double dot = n1.x * n2.x + n1.y * n2.y; |
| | | double angle = Math.acos(Math.max(-1, Math.min(1, dot))); |
| | | double dist = margin / Math.sin(angle / 2.0); |
| | | |
| | | // 方向修正:确保平分线指向多边形内部(逆时针多边形的左侧) |
| | | Point leftNormal = new Point(-n1.y, n1.x); |
| | | if (bisector.x * leftNormal.x + bisector.y * leftNormal.y < 0) { |
| | | bisector.x = -bisector.x; |
| | | bisector.y = -bisector.y; |
| | | } |
| | | |
| | | // 如果是凹角(cross < 0),平分线指向外部,距离需要反转或者特殊处理 |
| | | // 简单处理:对于凹角,偏移点实际上会远离原点,上述逻辑通常能覆盖, |
| | | // 但极端锐角可能导致dist过大。此处做简单截断保护是不够的, |
| | | // 但针对一般草地形状,此逻辑可用。 |
| | | |
| | | result.add(new Point(pCurr.x + bisector.x * dist, pCurr.y + bisector.y * dist)); |
| | | result.add(new Point(pCurr.x + bisectorX * dist, pCurr.y + bisectorY * dist)); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | /** |
| | | * 耳切法分割多边形 |
| | | */ |
| | | private static List<List<Point>> triangulatePolygon(List<Point> poly) { |
| | | List<List<Point>> triangles = new ArrayList<>(); |
| | | List<Point> remaining = new ArrayList<>(poly); |
| | | |
| | | int maxIter = remaining.size() * 3; |
| | | int iter = 0; |
| | | |
| | | while (remaining.size() > 3 && iter++ < maxIter) { |
| | | int n = remaining.size(); |
| | | boolean earFound = false; |
| | | |
| | | for (int i = 0; i < n; i++) { |
| | | Point prev = remaining.get((i - 1 + n) % n); |
| | | Point curr = remaining.get(i); |
| | | Point next = remaining.get((i + 1) % n); |
| | | |
| | | if (isConvex(prev, curr, next)) { |
| | | boolean hasPoint = false; |
| | | for (int j = 0; j < n; j++) { |
| | | if (j == i || j == (i - 1 + n) % n || j == (i + 1) % n) continue; |
| | | if (isPointInTriangle(remaining.get(j), prev, curr, next)) { |
| | | hasPoint = true; |
| | | break; |
| | | } |
| | | } |
| | | |
| | | if (!hasPoint) { |
| | | List<Point> tri = new ArrayList<>(); |
| | | tri.add(prev); tri.add(curr); tri.add(next); |
| | | triangles.add(tri); |
| | | remaining.remove(i); |
| | | earFound = true; |
| | | break; |
| | | } |
| | | } |
| | | private static void addSafeConnection(List<PathSegment> segments, Point start, Point end, List<Point> polygon) { |
| | | if (isSegmentSafe(start, end, polygon)) { |
| | | segments.add(new PathSegment(start, end, false)); |
| | | } else { |
| | | List<Point> path = getBoundaryPath(start, end, polygon); |
| | | for (int i = 0; i < path.size() - 1; i++) { |
| | | segments.add(new PathSegment(path.get(i), path.get(i+1), false)); |
| | | } |
| | | if (!earFound) break; |
| | | } |
| | | |
| | | if (remaining.size() == 3) { |
| | | triangles.add(remaining); |
| | | } |
| | | return triangles; |
| | | } |
| | | |
| | | private static double calculatePolygonHeight(List<Point> poly, double angle) { |
| | | double minY = Double.MAX_VALUE; |
| | | double maxY = -Double.MAX_VALUE; |
| | | for (Point p : poly) { |
| | | Point r = rotatePoint(p, angle); |
| | | minY = Math.min(minY, r.y); |
| | | maxY = Math.max(maxY, r.y); |
| | | private static boolean isSegmentSafe(Point p1, Point p2, List<Point> polygon) { |
| | | Point mid = new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2); |
| | | if (!isPointInPolygon(mid, polygon)) return false; |
| | | |
| | | for (int i = 0; i < polygon.size(); i++) { |
| | | Point a = polygon.get(i); |
| | | Point b = polygon.get((i + 1) % polygon.size()); |
| | | if (isSamePoint(p1, a) || isSamePoint(p1, b) || isSamePoint(p2, a) || isSamePoint(p2, b)) continue; |
| | | if (segmentsIntersect(p1, p2, a, b)) return false; |
| | | } |
| | | return maxY - minY; |
| | | return true; |
| | | } |
| | | |
| | | private static boolean isSamePoint(Point a, Point b) { |
| | | return Math.abs(a.x - b.x) < 1e-4 && Math.abs(a.y - b.y) < 1e-4; |
| | | } |
| | | |
| | | private static boolean segmentsIntersect(Point a, Point b, Point c, Point d) { |
| | | return ccw(a, c, d) != ccw(b, c, d) && ccw(a, b, c) != ccw(a, b, d); |
| | | } |
| | | |
| | | private static boolean ccw(Point a, Point b, Point c) { |
| | | return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); |
| | | } |
| | | |
| | | private static boolean isPointInPolygon(Point p, List<Point> polygon) { |
| | | boolean result = false; |
| | | for (int i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) { |
| | | if ((polygon.get(i).y > p.y) != (polygon.get(j).y > p.y) && |
| | | (p.x < (polygon.get(j).x - polygon.get(i).x) * (p.y - polygon.get(i).y) / (polygon.get(j).y - polygon.get(i).y) + polygon.get(i).x)) { |
| | | result = !result; |
| | | } |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | private static List<Point> getBoundaryPath(Point start, Point end, List<Point> polygon) { |
| | | int idx1 = getEdgeIndex(start, polygon); |
| | | int idx2 = getEdgeIndex(end, polygon); |
| | | |
| | | if (idx1 == -1 || idx2 == -1 || idx1 == idx2) { |
| | | return Arrays.asList(start, end); |
| | | } |
| | | |
| | | List<Point> path1 = new ArrayList<>(); |
| | | path1.add(start); |
| | | int curr = idx1; |
| | | while (curr != idx2) { |
| | | path1.add(polygon.get((curr + 1) % polygon.size())); |
| | | curr = (curr + 1) % polygon.size(); |
| | | } |
| | | path1.add(end); |
| | | |
| | | List<Point> pathRev = new ArrayList<>(); |
| | | pathRev.add(start); |
| | | curr = idx1; |
| | | while (curr != idx2) { |
| | | pathRev.add(polygon.get(curr)); |
| | | curr = (curr - 1 + polygon.size()) % polygon.size(); |
| | | } |
| | | pathRev.add(polygon.get((idx2 + 1) % polygon.size())); |
| | | pathRev.add(end); |
| | | |
| | | return getPathLength(path1) < getPathLength(pathRev) ? path1 : pathRev; |
| | | } |
| | | |
| | | private static double getPathLength(List<Point> path) { |
| | | double len = 0; |
| | | for (int i = 0; i < path.size() - 1; i++) { |
| | | len += Math.hypot(path.get(i).x - path.get(i+1).x, path.get(i).y - path.get(i+1).y); |
| | | } |
| | | return len; |
| | | } |
| | | |
| | | private static int getEdgeIndex(Point p, List<Point> poly) { |
| | | int bestIdx = -1; |
| | | double minD = Double.MAX_VALUE; |
| | | for (int i = 0; i < poly.size(); i++) { |
| | | Point p1 = poly.get(i); |
| | | Point p2 = poly.get((i + 1) % poly.size()); |
| | | double d = distToSegment(p, p1, p2); |
| | | if (d < minD) { |
| | | minD = d; |
| | | bestIdx = i; |
| | | } |
| | | } |
| | | // 只要找到最近的边即可,放宽阈值以应对浮点误差和旋转变形 |
| | | // 如果距离过大(例如超过1米),可能确实不在边界上,但在路径规划上下文中, |
| | | // 这些点是由扫描线生成的,理论上一定在边界上,所以强制吸附是安全的。 |
| | | return minD < 1.0 ? bestIdx : -1; |
| | | } |
| | | |
| | | private static double distToSegment(Point p, Point s, Point e) { |
| | | double l2 = (s.x - e.x)*(s.x - e.x) + (s.y - e.y)*(s.y - e.y); |
| | | if (l2 == 0) return Math.hypot(p.x - s.x, p.y - s.y); |
| | | double t = ((p.x - s.x) * (e.x - s.x) + (p.y - s.y) * (e.y - s.y)) / l2; |
| | | t = Math.max(0, Math.min(1, t)); |
| | | return Math.hypot(p.x - (s.x + t * (e.x - s.x)), p.y - (s.y + t * (e.y - s.y))); |
| | | } |
| | | |
| | | private static Point rotatePoint(Point p, double angle) { |
| | | double cos = Math.cos(angle); |
| | | double sin = Math.sin(angle); |
| | | double cos = Math.cos(angle), sin = Math.sin(angle); |
| | | return new Point(p.x * cos - p.y * sin, p.x * sin + p.y * cos); |
| | | } |
| | | |
| | | private static boolean isConvex(Point a, Point b, Point c) { |
| | | return (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x) >= 0; |
| | | } |
| | | |
| | | private static boolean isPointInTriangle(Point p, Point a, Point b, Point c) { |
| | | double areaABC = Math.abs((a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y))/2.0); |
| | | double areaPBC = Math.abs((p.x*(b.y-c.y) + b.x*(c.y-p.y) + c.x*(p.y-b.y))/2.0); |
| | | double areaPAC = Math.abs((a.x*(p.y-c.y) + p.x*(c.y-a.y) + c.x*(a.y-p.y))/2.0); |
| | | double areaPAB = Math.abs((a.x*(b.y-p.y) + b.x*(p.y-a.y) + p.x*(a.y-b.y))/2.0); |
| | | return Math.abs(areaABC - (areaPBC + areaPAC + areaPAB)) < 1e-6; |
| | | public static void ensureCounterClockwise(List<Point> points) { |
| | | double sum = 0; |
| | | for (int i = 0; i < points.size(); i++) { |
| | | Point p1 = points.get(i), p2 = points.get((i + 1) % points.size()); |
| | | sum += (p2.x - p1.x) * (p2.y + p1.y); |
| | | } |
| | | if (sum > 0) Collections.reverse(points); |
| | | } |
| | | |
| | | private static List<Point> parseCoordinates(String coordinates) { |
| | | List<Point> points = new ArrayList<>(); |
| | | String cleanStr = coordinates.replaceAll("[()\\[\\]{}]", "").trim(); |
| | | String[] pairs = cleanStr.split(";"); |
| | | String[] pairs = coordinates.split(";"); |
| | | for (String pair : pairs) { |
| | | pair = pair.trim(); |
| | | if (pair.isEmpty()) continue; |
| | | String[] xy = pair.split(","); |
| | | if (xy.length == 2) { |
| | | points.add(new Point(Double.parseDouble(xy[0].trim()), Double.parseDouble(xy[1].trim()))); |
| | | } |
| | | if (xy.length == 2) points.add(new Point(Double.parseDouble(xy[0]), Double.parseDouble(xy[1]))); |
| | | } |
| | | if (points.size() > 1 && points.get(0).equals(points.get(points.size()-1))) points.remove(points.size()-1); |
| | | return points; |
| | | } |
| | | |
| | | private static void ensureCounterClockwise(List<Point> points) { |
| | | double sum = 0; |
| | | for (int i = 0; i < points.size(); i++) { |
| | | Point p1 = points.get(i); |
| | | Point p2 = points.get((i + 1) % points.size()); |
| | | sum += (p2.x - p1.x) * (p2.y + p1.y); |
| | | } |
| | | if (sum > 0) { |
| | | Collections.reverse(points); |
| | | } |
| | | } |
| | | |
| | | private static double distance(Point p1, Point p2) { |
| | | return Math.hypot(p1.x - p2.x, p1.y - p2.y); |
| | | } |
| | | |
| | | // ========================================== |
| | | // 内部数据结构 |
| | | // ========================================== |
| | | |
| | | public static class Point { |
| | | public double x, y; |
| | | public Point(double x, double y) { this.x = x; this.y = y; } |
| | | @Override public String toString() { return String.format("%.2f,%.2f", x, y); } |
| | | @Override |
| | | public boolean equals(Object o) { |
| | | if (!(o instanceof Point)) return false; |
| | | Point p = (Point) o; |
| | | return Math.abs(x - p.x) < 1e-4 && Math.abs(y - p.y) < 1e-4; |
| | | } |
| | | } |
| | | |
| | | public static class PathSegment { |
| | | public Point start; |
| | | public Point end; |
| | | public boolean isMowing; |
| | | |
| | | public PathSegment(Point start, Point end, boolean isMowing) { |
| | | this.start = start; |
| | | this.end = end; |
| | | this.isMowing = isMowing; |
| | | } |
| | | |
| | | @Override |
| | | public String toString() { |
| | | return String.format("[%s -> %s, 割草:%b]", start, end, isMowing); |
| | | } |
| | | public Point start, end; |
| | | public boolean isMowing; // true: 割草中, false: 空载移动 |
| | | public PathSegment(Point s, Point e, boolean m) { this.start = s; this.end = e; this.isMowing = m; } |
| | | } |
| | | } |