张世豪
15 小时以前 1c8e32b4a45c1865e2a422e9949c1e996df861a6
src/lujing/AoxinglujingHaveObstacel.java
@@ -1,23 +1,360 @@
package lujing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * 有障碍物凸形地块路径规划类
 * 凸形草地路径规划 (避障优化版)
 * 优化:增加了障碍物区间预处理、路径连接就近原则、以及更稳健的多边形外扩
 */
public class AoxinglujingHaveObstacel {
    /**
     * 生成路径
     * @param boundaryCoordsStr 地块边界坐标字符串 "x1,y1;x2,y2;..."
     * @param obstacleCoordsStr 障碍物坐标字符串
     * @param mowingWidthStr 割草宽度字符串,如 "0.34"
     * @param safetyMarginStr 安全边距字符串,如 "0.2"
     * @return 路径坐标字符串,格式 "x1,y1;x2,y2;..."
     */
    public static String planPath(String boundaryCoordsStr, String obstacleCoordsStr, String mowingWidthStr, String safetyMarginStr) {
        // TODO: 实现凸形地块有障碍物路径规划算法
        // 目前使用默认方法作为临时实现
        throw new UnsupportedOperationException("AoxinglujingHaveObstacel.planPath 尚未实现");
    private static final double EPSILON = 1e-6;
    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("%.6f,%.6f", x, y); }
    }
}
    public static class PathSegment {
        public Point start, end;
        public boolean isMowing;
        public PathSegment(Point start, Point end, boolean isMowing) {
            this.start = start; this.end = end; this.isMowing = isMowing;
        }
    }
    public abstract static class Obstacle {
        public abstract boolean isInside(Point p);
        public abstract List<Double> getIntersectionsX(double y, double angle);
    }
    public static class PolygonObstacle extends Obstacle {
        public List<Point> points;
        public PolygonObstacle(List<Point> points) { this.points = points; }
        @Override
        public boolean isInside(Point p) {
            boolean result = false;
            for (int i = 0, j = points.size() - 1; i < points.size(); j = i++) {
                if ((points.get(i).y > p.y) != (points.get(j).y > p.y) &&
                    (p.x < (points.get(j).x - points.get(i).x) * (p.y - points.get(i).y) / (points.get(j).y - points.get(i).y) + points.get(i).x)) {
                    result = !result;
                }
            }
            return result;
        }
        @Override
        public List<Double> getIntersectionsX(double y, double angle) {
            List<Point> rotated = rotatePolygon(this.points, -angle);
            List<Double> xInts = new ArrayList<>();
            for (int i = 0; i < rotated.size(); i++) {
                Point p1 = rotated.get(i), p2 = rotated.get((i + 1) % rotated.size());
                if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) {
                    xInts.add(p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y));
                }
            }
            return xInts;
        }
    }
    public static class CircleObstacle extends Obstacle {
        public Point center;
        public double radius;
        public CircleObstacle(Point center, double radius) { this.center = center; this.radius = radius; }
        @Override
        public boolean isInside(Point p) {
            return Math.hypot(p.x - center.x, p.y - center.y) <= radius + EPSILON;
        }
        @Override
        public List<Double> getIntersectionsX(double y, double angle) {
            List<Double> xInts = new ArrayList<>();
            Point rCenter = rotatePoint(center, -angle);
            double dy = Math.abs(y - rCenter.y);
            if (dy < radius) {
                double dx = Math.sqrt(radius * radius - dy * dy);
                xInts.add(rCenter.x - dx);
                xInts.add(rCenter.x + dx);
            }
            return xInts;
        }
    }
    public static List<PathSegment> planPath(String boundaryStr, String obstacleStr, String widthStr, String marginStr) {
        List<Point> boundary = parseCoords(boundaryStr);
        double width = Double.parseDouble(widthStr);
        double margin = Double.parseDouble(marginStr);
        List<Obstacle> obstacles = parseObstacles(obstacleStr, margin);
        return planPathCore(boundary, obstacles, width, margin);
    }
    private static List<PathSegment> planPathCore(List<Point> boundary, List<Obstacle> obstacles, double width, double margin) {
        if (boundary.size() < 3) return new ArrayList<>();
        ensureCCW(boundary);
        List<Point> workArea = shrinkPolygon(boundary, margin);
        if (workArea.size() < 3) return new ArrayList<>();
        double bestAngle = findOptimalScanAngle(workArea);
        Point firstScanStart = getFirstScanStartPoint(workArea, bestAngle, width);
        List<Point> alignedWorkArea = alignBoundaryToStart(workArea, firstScanStart);
        List<PathSegment> finalPath = new ArrayList<>();
        // 1. 围边路径
        for (int i = 0; i < alignedWorkArea.size(); i++) {
            finalPath.add(new PathSegment(alignedWorkArea.get(i), alignedWorkArea.get((i + 1) % alignedWorkArea.size()), true));
        }
        // 2. 内部填充
        Point currentPos = alignedWorkArea.get(0);
        List<PathSegment> zigZagLines = generateOptimizedZigZag(workArea, obstacles, bestAngle, width, currentPos);
        finalPath.addAll(zigZagLines);
        return finalPath;
    }
    private static List<PathSegment> generateOptimizedZigZag(List<Point> polygon, List<Obstacle> obstacles, double angle, double width, Point startPoint) {
        List<PathSegment> result = new ArrayList<>();
        List<Point> rotatedPoly = rotatePolygon(polygon, -angle);
        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);
        }
        Point currentPos = startPoint;
        boolean leftToRight = true;
        for (double y = minY + width; y < maxY - width / 2; y += width) {
            List<Double> intersections = getXIntersections(rotatedPoly, y);
            if (intersections.size() < 2) continue;
            Collections.sort(intersections);
            double xBoundaryMin = intersections.get(0);
            double xBoundaryMax = intersections.get(intersections.size() - 1);
            // 收集当前行所有障碍物交点并进行裁剪
            List<Double> splitPoints = new ArrayList<>();
            splitPoints.add(xBoundaryMin);
            for (Obstacle obs : obstacles) {
                List<Double> obsX = obs.getIntersectionsX(y, angle);
                for (double ox : obsX) {
                    if (ox > xBoundaryMin && ox < xBoundaryMax) splitPoints.add(ox);
                }
            }
            Collections.sort(splitPoints);
            // 构建有效段
            List<LineRange> validRanges = new ArrayList<>();
            for (int i = 0; i < splitPoints.size() - 1; i++) {
                double midX = (splitPoints.get(i) + splitPoints.get(i + 1)) / 2.0;
                Point midPoint = rotatePoint(new Point(midX, y), angle);
                boolean insideAnyObstacle = false;
                for (Obstacle obs : obstacles) {
                    if (obs.isInside(midPoint)) {
                        insideAnyObstacle = true;
                        break;
                    }
                }
                if (!insideAnyObstacle) {
                    validRanges.add(new LineRange(splitPoints.get(i), splitPoints.get(i+1)));
                }
            }
            // 根据当前朝向排序有效段
            if (!leftToRight) {
                Collections.reverse(validRanges);
                for (LineRange range : validRanges) {
                    double temp = range.start;
                    range.start = range.end;
                    range.end = temp;
                }
            }
            // 连接路径
            for (LineRange range : validRanges) {
                Point pStart = rotatePoint(new Point(range.start, y), angle);
                Point pEnd = rotatePoint(new Point(range.end, y), angle);
                if (Math.hypot(currentPos.x - pStart.x, currentPos.y - pStart.y) > 0.01) {
                    result.add(new PathSegment(currentPos, pStart, false));
                }
                result.add(new PathSegment(pStart, pEnd, true));
                currentPos = pEnd;
            }
            leftToRight = !leftToRight;
        }
        return result;
    }
    private static class LineRange {
        double start, end;
        LineRange(double s, double e) { this.start = s; this.end = e; }
    }
    // --- 障碍物解析与多边形外扩 ---
    private static List<Obstacle> parseObstacles(String obsStr, double margin) {
        List<Obstacle> list = new ArrayList<>();
        if (obsStr == null || obsStr.trim().isEmpty()) return list;
        for (String part : obsStr.split("\\$")) {
            List<Point> pts = parseCoords(part);
            if (pts.size() == 2) {
                double r = Math.hypot(pts.get(0).x - pts.get(1).x, pts.get(0).y - pts.get(1).y);
                list.add(new CircleObstacle(pts.get(0), r + margin));
            } else if (pts.size() > 2) {
                ensureCCW(pts);
                list.add(new PolygonObstacle(expandPolygon(pts, margin)));
            }
        }
        return list;
    }
    private static List<Point> expandPolygon(List<Point> poly, double margin) {
        List<Point> result = new ArrayList<>();
        int n = poly.size();
        for (int i = 0; i < n; i++) {
            Point pPrev = poly.get((i - 1 + n) % n);
            Point pCurr = poly.get(i);
            Point pNext = poly.get((i + 1) % n);
            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 n1x = d1y / l1, n1y = -d1x / l1;
            double n2x = d2y / l2, n2y = -d2x / l2;
            double bx = n1x + n2x, by = n1y + n2y;
            double bLen = Math.hypot(bx, by);
            if (bLen < EPSILON) { bx = n1x; by = n1y; } else { bx /= bLen; by /= bLen; }
            double cosHalf = n1x * bx + n1y * by;
            double d = margin / Math.max(cosHalf, 0.1);
            // 限制最大外扩,防止尖角畸变
            d = Math.min(d, margin * 3);
            result.add(new Point(pCurr.x + bx * d, pCurr.y + by * d));
        }
        return result;
    }
    // --- 基础工具类方法 ---
    private static List<Point> parseCoords(String s) {
        List<Point> list = new ArrayList<>();
        if(s == null || s.isEmpty()) return list;
        for (String p : s.split(";")) {
            String[] xy = p.split(",");
            if (xy.length >= 2) list.add(new Point(Double.parseDouble(xy[0]), Double.parseDouble(xy[1])));
        }
        return list;
    }
    private static void ensureCCW(List<Point> poly) {
        double s = 0;
        for (int i = 0; i < poly.size(); i++) {
            Point p1 = poly.get(i), p2 = poly.get((i + 1) % poly.size());
            s += (p2.x - p1.x) * (p2.y + p1.y);
        }
        if (s > 0) Collections.reverse(poly);
    }
    private static List<Point> shrinkPolygon(List<Point> polygon, double margin) {
        List<Point> result = new ArrayList<>();
        int n = polygon.size();
        for (int i = 0; i < n; i++) {
            Point pPrev = polygon.get((i - 1 + n) % n);
            Point pCurr = polygon.get(i);
            Point pNext = polygon.get((i + 1) % n);
            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 n1x = -d1y / l1, n1y = d1x / l1;
            double n2x = -d2y / l2, n2y = d2x / l2;
            double bx = n1x + n2x, by = n1y + n2y;
            double bLen = Math.hypot(bx, by);
            if (bLen < EPSILON) { bx = n1x; by = n1y; } else { bx /= bLen; by /= bLen; }
            double cosHalf = n1x * bx + n1y * by;
            double d = margin / Math.max(cosHalf, 0.1);
            result.add(new Point(pCurr.x + bx * d, pCurr.y + by * d));
        }
        return result;
    }
    private static double findOptimalScanAngle(List<Point> polygon) {
        double minH = Double.MAX_VALUE, bestA = 0;
        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 = calculatePolygonHeightAtAngle(polygon, angle);
            if (h < minH) { minH = h; bestA = angle; }
        }
        return bestA;
    }
    private static double calculatePolygonHeightAtAngle(List<Point> poly, double angle) {
        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
        double sin = Math.sin(-angle), cos = Math.cos(-angle);
        for (Point p : poly) {
            double ry = p.x * sin + p.y * cos;
            minY = Math.min(minY, ry); maxY = Math.max(maxY, ry);
        }
        return maxY - minY;
    }
    private static List<Double> getXIntersections(List<Point> rotatedPoly, double y) {
        List<Double> xInts = new ArrayList<>();
        int n = rotatedPoly.size();
        for (int i = 0; i < n; i++) {
            Point p1 = rotatedPoly.get(i), p2 = rotatedPoly.get((i + 1) % n);
            if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) {
                xInts.add(p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y));
            }
        }
        return xInts;
    }
    private static Point getFirstScanStartPoint(List<Point> polygon, double angle, double width) {
        List<Point> rotated = rotatePolygon(polygon, -angle);
        double minY = Double.MAX_VALUE;
        for (Point p : rotated) minY = Math.min(minY, p.y);
        double startY = minY + width + EPSILON;
        List<Double> xInts = getXIntersections(rotated, startY);
        if (xInts.isEmpty()) return polygon.get(0);
        Collections.sort(xInts);
        return rotatePoint(new Point(xInts.get(0), startY), angle);
    }
    private static List<Point> alignBoundaryToStart(List<Point> polygon, Point target) {
        int bestIdx = 0; double minDist = Double.MAX_VALUE;
        for (int i = 0; i < polygon.size(); i++) {
            double d = Math.hypot(polygon.get(i).x - target.x, polygon.get(i).y - target.y);
            if (d < minDist) { minDist = d; bestIdx = i; }
        }
        List<Point> aligned = new ArrayList<>();
        for (int i = 0; i < polygon.size(); i++) aligned.add(polygon.get((bestIdx + i) % polygon.size()));
        return aligned;
    }
    private static Point rotatePoint(Point p, double angle) {
        double c = Math.cos(angle), s = Math.sin(angle);
        return new Point(p.x * c - p.y * s, p.x * s + p.y * c);
    }
    private static List<Point> rotatePolygon(List<Point> poly, double angle) {
        List<Point> res = new ArrayList<>();
        for (Point p : poly) res.add(rotatePoint(p, angle));
        return res;
    }
}