From 0803b041d32a284ee8585914618219ecae82b21f Mon Sep 17 00:00:00 2001
From: 张世豪 <979909237@qq.com>
Date: 星期五, 26 十二月 2025 15:25:27 +0800
Subject: [PATCH] 增加了异形有障碍物路径算法

---
 src/lujing/YixinglujingHaveObstacel.java |  358 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 343 insertions(+), 15 deletions(-)

diff --git a/src/lujing/YixinglujingHaveObstacel.java b/src/lujing/YixinglujingHaveObstacel.java
index d46ca08..2a36445 100644
--- a/src/lujing/YixinglujingHaveObstacel.java
+++ b/src/lujing/YixinglujingHaveObstacel.java
@@ -1,23 +1,351 @@
 package lujing;
 
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 
 /**
- * 鏈夐殰纰嶇墿寮傚舰鍦板潡璺緞瑙勫垝绫�
+ * 寮傚舰鑽夊湴璺緞瑙勫垝 - 閬块殰澧炲己鐗� V7.0
+ * 浼樺寲锛氬鍔犱簡澶氳竟褰㈠鎵╃ǔ瀹氭�с�侀殰纰嶇墿纰版挒棰勫垽浠ュ強鍐椾綑璺緞娑堥櫎銆�
  */
 public class YixinglujingHaveObstacel {
-    
-    /**
-     * 鐢熸垚璺緞
-     * @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("YixinglujingHaveObstacel.planPath 灏氭湭瀹炵幇");
+
+    public static List<PathSegment> planPath(String coordinates, String obstaclesStr, String widthStr, String marginStr) {
+        List<Point> rawPoints = parseCoordinates(coordinates);
+        if (rawPoints.size() < 3) return new ArrayList<>();
+
+        double mowWidth = Double.parseDouble(widthStr);
+        double safeMargin = Double.parseDouble(marginStr);
+
+        // 1. 棰勫鐞嗗湴鍧楋紙纭繚閫嗘椂閽堬級
+        ensureCounterClockwise(rawPoints);
+        List<Point> boundary = getOffsetPolygon(rawPoints, -safeMargin); // 鍐呯缉
+        if (boundary.size() < 3) return new ArrayList<>();
+
+        // 2. 瑙勫垝鍩虹璺緞 (鏃犻殰纰嶇墿鐘舵��)
+        double bestAngle = findOptimalAngle(boundary);
+        Point firstScanStart = getFirstScanPoint(boundary, mowWidth, bestAngle);
+        List<Point> alignedBoundary = alignBoundaryStart(boundary, firstScanStart);
+
+        List<PathSegment> baseLines = new ArrayList<>();
+        // 绗竴闃舵锛氬洿杈�
+        for (int i = 0; i < alignedBoundary.size(); i++) {
+            baseLines.add(new PathSegment(alignedBoundary.get(i), alignedBoundary.get((i + 1) % alignedBoundary.size()), true));
+        }
+        // 绗簩闃舵锛氬唴閮ㄦ壂鎻�
+        Point lastEdgePos = alignedBoundary.get(0);
+        baseLines.addAll(generateGlobalScanPath(boundary, mowWidth, bestAngle, lastEdgePos));
+
+        // 3. 澶勭悊闅滅鐗╋細瑙f瀽骞舵墽琛屽鎵� (闅滅鐗╅渶鍚戝鎵� margin)
+        List<Obstacle> obstacles = parseObstacles(obstaclesStr, safeMargin);
+
+        // 4. 璺緞瑁佸壀涓庝紭鍖栬繛鎺�
+        return optimizeAndClipPath(baseLines, obstacles);
     }
-}
+
+    private static List<PathSegment> optimizeAndClipPath(List<PathSegment> originalPath, List<Obstacle> obstacles) {
+        List<PathSegment> result = new ArrayList<>();
+        Point currentPos = null;
+
+        for (PathSegment segment : originalPath) {
+            List<PathSegment> clipped = new ArrayList<>();
+            clipped.add(segment);
+
+            for (Obstacle obs : obstacles) {
+                List<PathSegment> nextIter = new ArrayList<>();
+                for (PathSegment s : clipped) {
+                    nextIter.addAll(obs.clipSegment(s));
+                }
+                clipped = nextIter;
+            }
+
+            for (PathSegment s : clipped) {
+                // 浼樺寲鐐癸細娑堥櫎闀垮害鍑犱箮涓�0鐨勬棤鏁堢嚎娈�
+                if (Math.hypot(s.start.x - s.end.x, s.start.y - s.end.y) < 1e-4) continue;
+
+                if (currentPos != null && Math.hypot(currentPos.x - s.start.x, currentPos.y - s.start.y) > 0.01) {
+                    // 娣诲姞绌鸿浇璺緞
+                    result.add(new PathSegment(currentPos, s.start, false));
+                }
+                result.add(s);
+                currentPos = s.end;
+            }
+        }
+        return result;
+    }
+
+    // --- 闅滅鐗╂ā鍨� ---
+    abstract static class Obstacle {
+        abstract boolean isInside(Point p);
+        abstract List<PathSegment> clipSegment(PathSegment seg);
+    }
+
+    static class PolyObstacle extends Obstacle {
+        List<Point> points;
+        double minX, maxX, minY, maxY;
+
+        public PolyObstacle(List<Point> pts) {
+            this.points = pts;
+            // 棰勮绠� AABB 杈圭晫妗嗘彁鍗囨晥鐜�
+            minX = minY = Double.MAX_VALUE;
+            maxX = maxY = -Double.MAX_VALUE;
+            for (Point p : pts) {
+                minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x);
+                minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y);
+            }
+        }
+
+        @Override
+        boolean isInside(Point p) {
+            if (p.x < minX || p.x > maxX || p.y < minY || p.y > maxY) return false;
+            boolean inside = 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)) {
+                    inside = !inside;
+                }
+            }
+            return inside;
+        }
+
+        @Override
+        List<PathSegment> clipSegment(PathSegment seg) {
+            List<Double> ts = new ArrayList<>(Arrays.asList(0.0, 1.0));
+            for (int i = 0; i < points.size(); i++) {
+                double t = getIntersectionT(seg.start, seg.end, points.get(i), points.get((i + 1) % points.size()));
+                if (t > 0 && t < 1) ts.add(t);
+            }
+            Collections.sort(ts);
+            List<PathSegment> res = new ArrayList<>();
+            for (int i = 0; i < ts.size() - 1; i++) {
+                Point s = interpolate(seg.start, seg.end, ts.get(i));
+                Point e = interpolate(seg.start, seg.end, ts.get(i + 1));
+                if (!isInside(new Point((s.x + e.x) / 2, (s.y + e.y) / 2))) {
+                    res.add(new PathSegment(s, e, seg.isMowing));
+                }
+            }
+            return res;
+        }
+    }
+
+    static class CircleObstacle extends Obstacle {
+        Point center; double radius;
+        public CircleObstacle(Point c, double r) { this.center = c; this.radius = r; }
+
+        @Override
+        boolean isInside(Point p) { return Math.hypot(p.x - center.x, p.y - center.y) < radius - 1e-4; }
+
+        @Override
+        List<PathSegment> clipSegment(PathSegment seg) {
+            List<Double> ts = new ArrayList<>(Arrays.asList(0.0, 1.0));
+            double dx = seg.end.x - seg.start.x, dy = seg.end.y - seg.start.y;
+            double fx = seg.start.x - center.x, fy = seg.start.y - center.y;
+            double a = dx * dx + dy * dy;
+            double b = 2 * (fx * dx + fy * dy);
+            double c = fx * fx + fy * fy - radius * radius;
+            double disc = b * b - 4 * a * c;
+            if (disc >= 0) {
+                disc = Math.sqrt(disc);
+                double t1 = (-b - disc) / (2 * a), t2 = (-b + disc) / (2 * a);
+                if (t1 > 0 && t1 < 1) ts.add(t1);
+                if (t2 > 0 && t2 < 1) ts.add(t2);
+            }
+            Collections.sort(ts);
+            List<PathSegment> res = new ArrayList<>();
+            for (int i = 0; i < ts.size() - 1; i++) {
+                Point s = interpolate(seg.start, seg.end, ts.get(i));
+                Point e = interpolate(seg.start, seg.end, ts.get(i + 1));
+                if (!isInside(new Point((s.x + e.x) / 2, (s.y + e.y) / 2))) res.add(new PathSegment(s, e, seg.isMowing));
+            }
+            return res;
+        }
+    }
+
+    // --- 绠楁硶宸ュ叿绫� ---
+
+    private static List<Obstacle> parseObstacles(String obsStr, double margin) {
+        List<Obstacle> obstacles = new ArrayList<>();
+        if (obsStr == null || obsStr.trim().isEmpty()) return obstacles;
+        for (String group : obsStr.split("\\$")) {
+            List<Point> pts = parseCoordinates(group);
+            if (pts.size() == 2) {
+                double r = Math.hypot(pts.get(0).x - pts.get(1).x, pts.get(0).y - pts.get(1).y);
+                obstacles.add(new CircleObstacle(pts.get(0), r + margin));
+            } else if (pts.size() > 2) {
+                ensureCounterClockwise(pts);
+                // 澶氳竟褰㈠鎵╋細offset 涓烘
+                obstacles.add(new PolyObstacle(getOffsetPolygon(pts, margin)));
+            }
+        }
+        return obstacles;
+    }
+
+    /**
+     * 浼樺寲鍚庣殑澶氳竟褰㈠鎵�/鍐呯缉绠楁硶
+     * @param offset 姝f暟涓哄鎵╋紝璐熸暟涓哄唴缂�
+     */
+    private static List<Point> getOffsetPolygon(List<Point> points, double offset) {
+        List<Point> result = new ArrayList<>();
+        int n = points.size();
+        for (int i = 0; i < n; i++) {
+            Point p1 = points.get((i - 1 + n) % n), p2 = points.get(i), p3 = points.get((i + 1) % n);
+            
+            double v1x = p2.x - p1.x, v1y = p2.y - p1.y;
+            double v2x = p3.x - p2.x, v2y = p3.y - p2.y;
+            double l1 = Math.hypot(v1x, v1y), l2 = Math.hypot(v2x, v2y);
+            
+            if (l1 < 1e-6 || l2 < 1e-6) continue;
+
+            // 娉曞悜閲�
+            double n1x = -v1y / l1, n1y = v1x / l1;
+            double n2x = -v2y / l2, n2y = v2x / l2;
+
+            // 瑙掑钩鍒嗙嚎
+            double bx = n1x + n2x, by = n1y + n2y;
+            double bl = Math.hypot(bx, by);
+            if (bl < 1e-6) { bx = n1x; by = n1y; } else { bx /= bl; by /= bl; }
+
+            // 淇璺濈
+            double sinHalf = n1x * bx + n1y * by;
+            double d = offset / Math.max(sinHalf, 0.1);
+            result.add(new Point(p2.x + bx * d, p2.y + by * d));
+        }
+        return result;
+    }
+
+    private static List<PathSegment> generateGlobalScanPath(List<Point> polygon, double width, double angle, Point currentPos) {
+        List<PathSegment> segments = new ArrayList<>();
+        List<Point> rotated = new ArrayList<>();
+        for (Point p : polygon) rotated.add(rotatePoint(p, -angle));
+        
+        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
+        for (Point p : rotated) { minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y); }
+
+        boolean l2r = true;
+        for (double y = minY + width/2; y <= maxY - width/2; y += width) {
+            List<Double> xInters = getXIntersections(rotated, y);
+            if (xInters.size() < 2) continue;
+            Collections.sort(xInters);
+
+            List<PathSegment> row = new ArrayList<>();
+            for (int i = 0; i < xInters.size() - 1; i += 2) {
+                Point s = rotatePoint(new Point(xInters.get(i), y), angle);
+                Point e = rotatePoint(new Point(xInters.get(i + 1), y), angle);
+                row.add(new PathSegment(s, e, true));
+            }
+            if (!l2r) {
+                Collections.reverse(row);
+                for (PathSegment s : row) { Point t = s.start; s.start = s.end; s.end = t; }
+            }
+            for (PathSegment s : row) {
+                if (Math.hypot(currentPos.x - s.start.x, currentPos.y - s.start.y) > 0.01) {
+                    segments.add(new PathSegment(currentPos, s.start, false));
+                }
+                segments.add(s);
+                currentPos = s.end;
+            }
+            l2r = !l2r;
+        }
+        return segments;
+    }
+
+    // --- 鍩虹鏁板鍑芥暟 ---
+    private static double getIntersectionT(Point a, Point b, Point c, Point d) {
+        double ux = b.x - a.x, uy = b.y - a.y, vx = d.x - c.x, vy = d.y - c.y;
+        double det = vx * uy - vy * ux;
+        if (Math.abs(det) < 1e-6) return -1;
+        return (vx * (c.y - a.y) - vy * (c.x - a.x)) / det;
+    }
+
+    private static Point interpolate(Point a, Point b, double t) {
+        return new Point(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
+    }
+
+    private static Point rotatePoint(Point p, double ang) {
+        return new Point(p.x * Math.cos(ang) - p.y * Math.sin(ang), p.x * Math.sin(ang) + p.y * Math.cos(ang));
+    }
+
+    private static List<Double> getXIntersections(List<Point> poly, double y) {
+        List<Double> res = new ArrayList<>();
+        for (int i = 0; i < poly.size(); i++) {
+            Point p1 = poly.get(i), p2 = poly.get((i + 1) % poly.size());
+            if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) {
+                res.add(p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y));
+            }
+        }
+        return res;
+    }
+
+    private static Point getFirstScanPoint(List<Point> poly, double w, double a) {
+        List<Point> rot = new ArrayList<>();
+        for (Point p : poly) rot.add(rotatePoint(p, -a));
+        double minY = Double.MAX_VALUE;
+        for (Point p : rot) minY = Math.min(minY, p.y);
+        List<Double> xs = getXIntersections(rot, minY + w/2);
+        if (xs.isEmpty()) return poly.get(0);
+        Collections.sort(xs);
+        return rotatePoint(new Point(xs.get(0), minY + w/2), a);
+    }
+
+    private static List<Point> alignBoundaryStart(List<Point> poly, Point target) {
+        int idx = 0; double minD = Double.MAX_VALUE;
+        for (int i = 0; i < poly.size(); i++) {
+            double d = Math.hypot(poly.get(i).x - target.x, poly.get(i).y - target.y);
+            if (d < minD) { minD = d; idx = i; }
+        }
+        List<Point> res = new ArrayList<>();
+        for (int i = 0; i < poly.size(); i++) res.add(poly.get((idx + i) % poly.size()));
+        return res;
+    }
+
+    private static double findOptimalAngle(List<Point> poly) {
+        double bestA = 0, minH = Double.MAX_VALUE;
+        for (int i = 0; i < poly.size(); i++) {
+            Point p1 = poly.get(i), p2 = poly.get((i + 1) % poly.size());
+            double a = Math.atan2(p2.y - p1.y, p2.x - p1.x);
+            double h = 0, miY = Double.MAX_VALUE, maY = -Double.MAX_VALUE;
+            for (Point p : poly) {
+                Point r = rotatePoint(p, -a);
+                miY = Math.min(miY, r.y); maY = Math.max(maY, r.y);
+            }
+            h = maY - miY;
+            if (h < minH) { minH = h; bestA = a; }
+        }
+        return bestA;
+    }
+
+    private static void ensureCounterClockwise(List<Point> pts) {
+        double s = 0;
+        for (int i = 0; i < pts.size(); i++) s += (pts.get((i + 1) % pts.size()).x - pts.get(i).x) * (pts.get((i + 1) % pts.size()).y + pts.get(i).y);
+        if (s > 0) Collections.reverse(pts);
+    }
+
+    private static List<Point> parseCoordinates(String s) {
+        List<Point> pts = new ArrayList<>();
+        if (s == null || s.isEmpty()) return pts;
+        for (String p : s.split(";")) {
+            String[] xy = p.split(",");
+            if (xy.length == 2) pts.add(new Point(Double.parseDouble(xy[0]), Double.parseDouble(xy[1])));
+        }
+        if (pts.size() > 1 && pts.get(0).equals(pts.get(pts.size() - 1))) pts.remove(pts.size() - 1);
+        return pts;
+    }
+
+    public static class Point {
+        public double x, y;
+        public Point(double x, double y) { this.x = x; this.y = 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, end;
+        public boolean isMowing;
+        public PathSegment(Point s, Point e, boolean m) { this.start = s; this.end = e; this.isMowing = m; }
+    }
+}
\ No newline at end of file

--
Gitblit v1.10.0