From 9d7822ada88392e1b1a612e9b4f680fe6b09aedf Mon Sep 17 00:00:00 2001
From: 826220679@qq.com <826220679@qq.com>
Date: 星期六, 27 十二月 2025 22:25:38 +0800
Subject: [PATCH] 优化了路径规划

---
 src/lujing/YixinglujingNoObstacle.java |  398 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 382 insertions(+), 16 deletions(-)

diff --git a/src/lujing/YixinglujingNoObstacle.java b/src/lujing/YixinglujingNoObstacle.java
index 1919731..304a3bc 100644
--- a/src/lujing/YixinglujingNoObstacle.java
+++ b/src/lujing/YixinglujingNoObstacle.java
@@ -1,23 +1,389 @@
 package lujing;
 
-import java.util.List;
-import java.util.ArrayList;
+import java.util.*;
 
 /**
- * 鏃犻殰纰嶇墿寮傚舰鍦板潡璺緞瑙勫垝绫�
+ * 寮傚舰鑽夊湴璺緞瑙勫垝 - 鍑瑰杈瑰舰鍏煎浼樺寲鐗� V5.0
+ * 淇锛氳В鍐冲嚬澶氳竟褰㈡壂鎻忕嚎璺ㄨ秺杈圭晫鐨勯棶棰橈紝浼樺寲璺緞瀵归綈
  */
 public class YixinglujingNoObstacle {
-    
-    /**
-     * 鐢熸垚璺緞
-     * @param boundaryCoordsStr 鍦板潡杈圭晫鍧愭爣瀛楃涓� "x1,y1;x2,y2;..."
-     * @param mowingWidthStr 鍓茶崏瀹藉害瀛楃涓诧紝濡� "0.34"
-     * @param safetyMarginStr 瀹夊叏杈硅窛瀛楃涓诧紝濡� "0.2"
-     * @return 璺緞鍧愭爣瀛楃涓诧紝鏍煎紡 "x1,y1;x2,y2;..."
-     */
-    public static String planPath(String boundaryCoordsStr, String mowingWidthStr, String safetyMarginStr) {
-        // TODO: 瀹炵幇寮傚舰鍦板潡鏃犻殰纰嶇墿璺緞瑙勫垝绠楁硶
-        // 鐩墠浣跨敤榛樿鏂规硶浣滀负涓存椂瀹炵幇
-        throw new UnsupportedOperationException("YixinglujingNoObstacle.planPath 灏氭湭瀹炵幇");
+    // 鐢ㄦ硶璇存槑锛堟棤闅滅鐗╄矾寰勮鍒掞級锛�
+    // - 鏂规硶鐢ㄩ�旓細鏍规嵁鍦板潡杈圭晫銆佸壊鑽夊搴︿笌瀹夊叏杈硅窛锛岀敓鎴愯鐩栧叏鍖哄煙鐨勫壊鑽夎矾寰勩��
+    // - 鍙傛暟锛�
+    //   coordinates锛氬湴鍧楄竟鐣屽潗鏍囧瓧绗︿覆锛屾牸寮� "x1,y1;x2,y2;..."锛岃嚦灏�3涓偣锛屽崟浣嶄负绫炽��
+    //   widthStr锛氬壊鑽夊搴︼紙瀛楃涓诧紝鍗曚綅绫筹級锛岀敤浜庣‘瀹氭壂鎻忕嚎闂磋窛銆�
+    //   marginStr锛氬畨鍏ㄨ竟璺濓紙瀛楃涓诧紝鍗曚綅绫筹級锛岀敤浜庡皢鍦板潡杈圭晫鍚戝唴鏀剁缉锛岄伩鍏嶈创杈逛綔涓氥��
+    // - 杩斿洖鍊硷細List<PathSegment>锛屽叾涓� PathSegment.start/end 涓哄潗鏍囩偣锛宨sMowing 涓� 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) {
+        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);
+        
+        // 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<>();
+
+        // 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));
+        }
+
+        // 7. 绗簩闃舵锛氱敓鎴愬唴閮ㄦ壂鎻忚矾寰勶紙淇鍑归儴绌鸿秺闂锛�
+        Point lastEdgePos = alignedBoundary.get(0); 
+        List<PathSegment> scanPath = generateGlobalScanPath(boundary, mowWidth, bestAngle, lastEdgePos);
+        
+        finalPath.addAll(scanPath);
+
+        // 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;
+        }
+
+        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));
+
+        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);
+        }
+
+        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);
+
+            // 澶勭悊鍑瑰杈瑰舰锛氭瘡涓や釜鐐圭粍鎴愪竴涓湁鏁堜綔涓氭
+            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;
+                }
+            }
+
+            // 灏嗕綔涓氭杩炴帴鍒版�昏矾寰�
+            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(s);
+                currentPos = s.end;
+            }
+            leftToRight = !leftToRight;
+        }
+        return segments;
+    }
+
+    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<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);
+
+            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);
+
+            if (l1 < 1e-6 || l2 < 1e-6) continue;
+
+            // 鍗曚綅娉曞悜閲�
+            double n1x = -d1y / l1, n1y = d1x / l1;
+            double n2x = -d2y / l2, n2y = d2x / l2;
+
+            // 瑙掑钩鍒嗙嚎鏂瑰悜
+            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; }
+
+            double cosHalfAngle = n1x * bisectorX + n1y * bisectorY;
+            double dist = margin / Math.max(cosHalfAngle, 0.1); 
+            
+            // 闄愬埗鏈�澶т綅绉婚噺锛岄槻姝㈡瀬灏栬鐣稿彉
+            dist = Math.min(dist, margin * 5); 
+
+            result.add(new Point(pCurr.x + bisectorX * dist, pCurr.y + bisectorY * dist));
+        }
+        return result;
+    }
+
+    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));
+            }
+        }
+    }
+
+    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 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), sin = Math.sin(angle);
+        return new Point(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
+    }
+
+    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[] pairs = coordinates.split(";");
+        for (String pair : pairs) {
+            String[] xy = pair.split(",");
+            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;
+    }
+
+    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; // true: 鍓茶崏涓�, false: 绌鸿浇绉诲姩
+        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