From cbfd1df513c473dd5550d78740c92fc1677b6e9b Mon Sep 17 00:00:00 2001
From: 826220679@qq.com <826220679@qq.com>
Date: 星期六, 27 十二月 2025 13:40:42 +0800
Subject: [PATCH] 异形有障碍物路径规划没完成
---
src/lujing/YixinglujingHaveObstacel.java | 1546 ++++++++++++++++++++---------------------------------------
1 files changed, 528 insertions(+), 1,018 deletions(-)
diff --git a/src/lujing/YixinglujingHaveObstacel.java b/src/lujing/YixinglujingHaveObstacel.java
index 9993c2f..7d3cbce 100644
--- a/src/lujing/YixinglujingHaveObstacel.java
+++ b/src/lujing/YixinglujingHaveObstacel.java
@@ -1,1124 +1,634 @@
package lujing;
-
import java.util.*;
-import java.util.regex.*;
-import java.util.stream.Collectors;
+
/**
- * 寮傚舰鑽夊湴璺緞瑙勫垝 - 浼樺寲瀹屽杽鐗�
- * 閲囩敤鏇村畬鍠勭殑绠楁硶锛�
- * 1. 浣跨敤澶氳竟褰㈣鍓簱璁$畻鏇寸簿纭殑鍐呯缉杈圭晫
- * 2. 浣跨敤鎵弿绾垮~鍏呯畻娉曠敓鎴愭洿浼樺寲鐨勮矾寰�
- * 3. 浣跨敤鍙鍥剧畻娉曞鎵炬渶浼樼粫琛岃矾寰�
- * 4. 浣跨敤璺緞浼樺寲绠楁硶鍑忓皯绌鸿鍜岃浆寮�
+ * 寮傚舰鑽夊湴璺緞瑙勫垝 - 鍚殰纰嶇墿鐗�
+ * 鍔熻兘锛氬湪鍦板潡鍐呴儴閬垮紑闅滅鐗╋紝鐢熸垚杩炵画寮撳瓧褰㈠壊鑽夎矾寰�
*/
public class YixinglujingHaveObstacel {
-
- private static final double EPS = 1e-10;
- private static final double MIN_SEG_LEN = 0.01; // 蹇界暐灏忎簬1cm鐨勭绾�
- private static final double CORNER_THRESHOLD = Math.toRadians(30); // 30搴︿互涓嬬殑瑙掑害鍚堝苟
- public static List<PathSegment> planPath(String coordinates, String obstaclesStr, String widthStr, String marginStr) {
- try {
- // 瑙f瀽杈撳叆鍙傛暟
- double mowWidth = Double.parseDouble(widthStr);
- double safeMargin = Double.parseDouble(marginStr);
-
- // 瑙f瀽澶氳竟褰㈠拰闅滅鐗�
- List<Point> boundary = parseCoordinates(coordinates);
- if (boundary.size() < 3) {
- throw new IllegalArgumentException("鍦板潡杈圭晫鑷冲皯闇�瑕�3涓偣");
- }
-
- // 纭繚澶氳竟褰负閫嗘椂閽堟柟鍚�
- makeCCW(boundary);
-
- // 瑙f瀽闅滅鐗╁苟澶栨墿
- List<Obstacle> obstacles = parseAndExpandObstacles(obstaclesStr, safeMargin);
-
- // 鐢熸垚鍐呯缉浣滀笟杈圭晫锛堣�冭檻闅滅鐗╋級
- List<Point> workingArea = computeWorkingArea(boundary, obstacles, safeMargin);
- if (workingArea.isEmpty()) {
- return new ArrayList<>();
- }
-
- // 鐢熸垚瀹屾暣鐨勫叏瑕嗙洊璺緞锛堜笉鑰冭檻闅滅鐗╋級
- List<PathSegment> fullPath = generateCompleteCoverage(workingArea, mowWidth);
-
- // 鐢ㄩ殰纰嶇墿瑁佸壀璺緞
- List<PathSegment> clippedPath = clipPathWithObstacles(fullPath, obstacles);
-
- // 杩炴帴鍜屼紭鍖栬矾寰勶紙闄愬埗鍦ㄤ綔涓氳竟鐣屽唴锛�
- List<PathSegment> finalPath = connectAndOptimizePath(clippedPath, obstacles, mowWidth, workingArea);
-
- return finalPath;
-
- } catch (Exception e) {
- System.err.println("璺緞瑙勫垝閿欒: " + e.getMessage());
- e.printStackTrace();
- return new ArrayList<>();
+ public static List<PathSegment> planPath(String coordinates, String obstaclesStr,
+ String widthStr, String marginStr) {
+ // 1. 瑙f瀽鍙傛暟
+ List<Point> rawPoints = parseCoordinates(coordinates);
+ if (rawPoints.size() < 3) return new ArrayList<>();
+
+ double mowWidth = Double.parseDouble(widthStr);
+ double safeMargin = Double.parseDouble(marginStr);
+
+ // 瑙f瀽闅滅鐗�
+ List<Obstacle> obstacles = parseObstacles(obstaclesStr);
+
+ // 2. 棰勫鐞嗭細纭繚杈圭晫閫嗘椂閽�
+ ensureCounterClockwise(rawPoints);
+
+ // 3. 鐢熸垚鍐呯缉澶氳竟褰紙瀹夊叏杈圭晫锛�
+ List<Point> boundary = getInsetPolygon(rawPoints, safeMargin);
+ if (boundary.size() < 3) return new ArrayList<>();
+
+ // 4. 澶栨墿闅滅鐗╋紙瀹夊叏杈硅窛锛�
+ List<Obstacle> expandedObstacles = expandObstacles(obstacles, safeMargin);
+
+ // 5. 纭畾鏈�浼樹綔涓氳搴�
+ double bestAngle = findOptimalAngle(boundary);
+
+ // 6. 鑾峰彇棣栦釜浣滀笟鐐癸紝鐢ㄤ簬瀵归綈鍥磋竟璧风偣
+ Point firstScanStart = getFirstScanPoint(boundary, mowWidth, bestAngle);
+
+ // 7. 瀵归綈鍥磋竟
+ List<Point> alignedBoundary = alignBoundaryStart(boundary, firstScanStart);
+
+ // 8. 绗竴闃舵锛氬洿杈硅矾寰�
+ List<PathSegment> finalPath = new ArrayList<>();
+ 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));
}
+
+ // 9. 绗簩闃舵锛氱敓鎴愬唴閮ㄦ壂鎻忚矾寰勶紙鑰冭檻闅滅鐗╋級
+ Point lastEdgePos = alignedBoundary.get(0);
+ List<PathSegment> scanPath = generateGlobalScanPathWithObstacles(
+ boundary, expandedObstacles, mowWidth, bestAngle, lastEdgePos);
+
+ finalPath.addAll(scanPath);
+
+ return finalPath;
}
/**
- * 璁$畻浣滀笟鍖哄煙锛堣�冭檻闅滅鐗╋級
+ * 鐢熸垚甯﹂殰纰嶇墿鐨勬壂鎻忚矾寰�
*/
- private static List<Point> computeWorkingArea(List<Point> boundary, List<Obstacle> obstacles, double margin) {
- // 棣栧厛鐢熸垚鍐呯缉杈圭晫
- List<Point> offsetBoundary = offsetPolygon(boundary, -margin);
+ private static List<PathSegment> generateGlobalScanPathWithObstacles(
+ List<Point> polygon, List<Obstacle> obstacles,
+ double width, double angle, Point startPos) {
- if (obstacles.isEmpty()) {
- return offsetBoundary;
- }
+ // 1. 鐢熸垚鍘熷鎵弿绾匡紙鏃犻殰纰嶇墿锛�
+ List<PathSegment> originalSegments = generateGlobalScanPath(polygon, width, angle, startPos);
- // 濡傛灉瀛樺湪闅滅鐗╋紝浠庡唴缂╄竟鐣屼腑鍑忓幓闅滅鐗╁尯鍩�
- // 绠�鍖栧鐞嗭細宸ヤ綔鍖哄煙浠嶄互鍐呯缉杈圭晫涓轰富锛屽叿浣撹鍓湪璺緞灞傞潰瀹屾垚
- makeCCW(offsetBoundary);
- return offsetBoundary;
- }
-
- /**
- * 鐢熸垚瀹屾暣鐨勫叏瑕嗙洊璺緞
- */
- private static List<PathSegment> generateCompleteCoverage(List<Point> polygon, double width) {
- List<PathSegment> path = new ArrayList<>();
-
- // 1. 鐢熸垚杈圭晫璺緞
- List<PathSegment> borderPath = generateBorderPath(polygon, width);
- path.addAll(borderPath);
-
- // 2. 鐢熸垚鎵弿绾胯矾寰�
- List<PathSegment> scanLines = generateScanLines(polygon, width);
-
- // 3. 杩炴帴鎵弿绾�
- if (!scanLines.isEmpty()) {
- Point currentPos = path.isEmpty() ? scanLines.get(0).start :
- path.get(path.size() - 1).end;
-
- for (PathSegment scanLine : scanLines) {
- // 娣诲姞绌鸿杩炴帴
- if (distance(currentPos, scanLine.start) > MIN_SEG_LEN) {
- path.add(new PathSegment(currentPos, scanLine.start, false));
- }
- path.add(scanLine);
- currentPos = scanLine.end;
- }
-
- // 杩炴帴鍥炶捣鐐�
- if (distance(currentPos, path.get(0).start) > MIN_SEG_LEN) {
- path.add(new PathSegment(currentPos, path.get(0).start, false));
- }
- }
-
- return path;
- }
-
- /**
- * 鐢熸垚杈圭晫璺緞锛堜竴鍦堟垨澶氬湀锛�
- */
- private static List<PathSegment> generateBorderPath(List<Point> polygon, double width) {
- List<PathSegment> border = new ArrayList<>();
-
- // 鏍规嵁瀹藉害纭畾闇�瑕佸灏戝湀杈圭晫
- int borderPasses = 1; // 鑷冲皯涓�鍦�
- if (width < 0.3) {
- borderPasses = 2; // 瀹藉害杈冨皬锛屽鍔犺竟鐣屽湀鏁�
- }
-
- for (int pass = 0; pass < borderPasses; pass++) {
- double offset = pass * width;
- List<Point> offsetPoly = offsetPolygon(polygon, -offset);
-
- if (offsetPoly.size() < 3) break;
-
- for (int i = 0; i < offsetPoly.size(); i++) {
- Point start = offsetPoly.get(i);
- Point end = offsetPoly.get((i + 1) % offsetPoly.size());
- border.add(new PathSegment(start, end, true));
- }
- }
-
- return border;
- }
-
- /**
- * 鐢熸垚鎵弿绾胯矾寰�
- */
- private static List<PathSegment> generateScanLines(List<Point> polygon, double width) {
- List<PathSegment> scanLines = new ArrayList<>();
-
- // 璁$畻鏈�浼樻壂鎻忔柟鍚�
- double optimalAngle = calculateOptimalScanAngle(polygon);
-
- // 鏃嬭浆澶氳竟褰㈠埌鎵弿鏂瑰悜
- List<Point> rotatedPoly = rotatePolygon(polygon, -optimalAngle);
-
- // 璁$畻鍖呭洿鐩�
- Bounds bounds = calculateBounds(rotatedPoly);
-
- // 鐢熸垚鎵弿绾�
- boolean leftToRight = true;
- for (double y = bounds.minY + width / 2; y <= bounds.maxY - width / 2 + EPS; y += width) {
- // 鑾峰彇姘村钩绾夸笌澶氳竟褰㈢殑浜ょ偣
- List<Double> intersections = getHorizontalIntersections(rotatedPoly, y);
-
- if (intersections.size() < 2) continue;
-
- // 浜ょ偣鎺掑簭骞舵垚瀵瑰鐞�
- Collections.sort(intersections);
- List<PathSegment> lineSegments = new ArrayList<>();
-
- for (int i = 0; i < intersections.size(); i += 2) {
- if (i + 1 >= intersections.size()) break;
-
- double x1 = intersections.get(i);
- double x2 = intersections.get(i + 1);
-
- if (x2 - x1 < MIN_SEG_LEN) continue;
-
- // 鏃嬭浆鍥炲師濮嬪潗鏍囩郴
- Point start = rotatePoint(new Point(x1, y), optimalAngle);
- Point end = rotatePoint(new Point(x2, y), optimalAngle);
-
- lineSegments.add(new PathSegment(start, end, true));
- }
-
- // 鏂瑰悜浜ゆ浛
- if (!leftToRight) {
- Collections.reverse(lineSegments);
- for (PathSegment seg : lineSegments) {
- Point temp = seg.start;
- seg.start = seg.end;
- seg.end = temp;
- }
- }
-
- scanLines.addAll(lineSegments);
- leftToRight = !leftToRight;
- }
-
- return scanLines;
- }
-
- /**
- * 鐢ㄩ殰纰嶇墿瑁佸壀璺緞
- */
- private static List<PathSegment> clipPathWithObstacles(List<PathSegment> path, List<Obstacle> obstacles) {
- if (obstacles.isEmpty()) return path;
-
- List<PathSegment> clipped = new ArrayList<>();
-
- for (PathSegment segment : path) {
- List<PathSegment> remaining = new ArrayList<>();
- remaining.add(segment);
-
- // 渚濇鐢ㄦ瘡涓殰纰嶇墿瑁佸壀
- for (Obstacle obstacle : obstacles) {
- List<PathSegment> temp = new ArrayList<>();
- for (PathSegment seg : remaining) {
- temp.addAll(obstacle.clipSegment(seg));
- }
- remaining = temp;
- }
-
- clipped.addAll(remaining);
- }
-
- return clipped;
- }
-
- /**
- * 杩炴帴鍜屼紭鍖栬矾寰�
- */
- private static List<PathSegment> connectAndOptimizePath(List<PathSegment> segments,
- List<Obstacle> obstacles,
- double width,
- List<Point> workingArea) {
- if (segments.isEmpty()) return new ArrayList<>();
-
- // 1. 鍏堟寜绫诲瀷鍒嗙粍锛氬壊鑽夋鍜岃繛鎺ユ
- List<PathSegment> mowingSegments = segments.stream()
- .filter(s -> s.isMowing)
- .collect(Collectors.toList());
-
- // 2. 浣跨敤鏃呰鍟嗛棶棰�(TSP)鐨勮繎浼肩畻娉曡繛鎺ュ壊鑽夋
- List<PathSegment> connectedPath = connectSegmentsTSP(mowingSegments, obstacles, workingArea);
-
- // 3. 浼樺寲璺緞锛氬悎骞跺皬娈点�佸钩婊戣浆瑙�
- connectedPath = optimizePath(connectedPath, width);
-
- return connectedPath;
- }
-
- /**
- * 浣跨敤鏃呰鍟嗛棶棰樿繎浼肩畻娉曡繛鎺ヨ矾寰勬
- */
- private static List<PathSegment> connectSegmentsTSP(List<PathSegment> segments, List<Obstacle> obstacles, List<Point> workingArea) {
- List<PathSegment> connected = new ArrayList<>();
-
- if (segments.isEmpty()) return connected;
-
- // 鏋勫缓鐐归泦锛堟墍鏈夌嚎娈电殑绔偣锛�
- List<Point> points = new ArrayList<>();
- for (PathSegment seg : segments) {
- points.add(seg.start);
- points.add(seg.end);
- }
-
- // 浣跨敤鏈�杩戦偦绠楁硶鏋勫缓璺緞
- boolean[] visited = new boolean[segments.size()];
- Point currentPos = segments.get(0).start;
-
- while (true) {
- int bestIdx = -1;
- double bestDist = Double.MAX_VALUE;
- boolean useStart = true;
-
- // 瀵绘壘鏈�杩戠殑鏈闂嚎娈�
- for (int i = 0; i < segments.size(); i++) {
- if (visited[i]) continue;
-
- PathSegment seg = segments.get(i);
- double distToStart = distance(currentPos, seg.start);
- double distToEnd = distance(currentPos, seg.end);
-
- if (distToStart < bestDist) {
- bestDist = distToStart;
- bestIdx = i;
- useStart = true;
- }
- if (distToEnd < bestDist) {
- bestDist = distToEnd;
- bestIdx = i;
- useStart = false;
- }
- }
-
- if (bestIdx == -1) break;
-
- // 娣诲姞杩炴帴璺緞
- PathSegment bestSeg = segments.get(bestIdx);
- Point targetPoint = useStart ? bestSeg.start : bestSeg.end;
-
- if (distance(currentPos, targetPoint) > MIN_SEG_LEN) {
- // 瀵绘壘瀹夊叏杩炴帴璺緞锛堝彈浣滀笟杈圭晫闄愬埗锛�
- List<PathSegment> detour = findSafePath(currentPos, targetPoint, obstacles, workingArea);
- connected.addAll(detour);
- }
-
- // 娣诲姞鍓茶崏绾挎锛堝彲鑳藉弽杞柟鍚戯級
- PathSegment toAdd = bestSeg;
- if (!useStart) {
- toAdd = new PathSegment(bestSeg.end, bestSeg.start, true);
- }
- connected.add(toAdd);
-
- currentPos = toAdd.end;
- visited[bestIdx] = true;
- }
-
- return connected;
- }
-
- /**
- * 瀵绘壘瀹夊叏璺緞锛圓*绠楁硶锛�
- */
- private static List<PathSegment> findSafePath(Point start, Point end, List<Obstacle> obstacles, List<Point> workingArea) {
- // 濡傛灉鐩寸嚎璺緞瀹夊叏锛岀洿鎺ヤ娇鐢�
- if (isLineSafe(start, end, obstacles, workingArea)) {
- List<PathSegment> direct = new ArrayList<>();
- direct.add(new PathSegment(start, end, false));
- return direct;
- }
-
- // 鍚﹀垯浣跨敤A*绠楁硶瀵绘壘缁曡璺緞
- return aStarPathFinding(start, end, obstacles, workingArea);
- }
-
- /**
- * A*绠楁硶璺緞瀵绘壘
- */
- private static List<PathSegment> aStarPathFinding(Point start, Point end, List<Obstacle> obstacles, List<Point> workingArea) {
- // 绠�鍖栫殑A*绠楁硶瀹炵幇
- // 杩欓噷鎴戜滑浣跨敤闅滅鐗╄竟鐣屼笂鐨勫叧閿偣浣滀负璺緞鑺傜偣
-
- List<Point> nodes = new ArrayList<>();
- nodes.add(start);
- nodes.add(end);
-
- // 娣诲姞闅滅鐗╃殑椤剁偣浣滀负鍊欓�夎妭鐐�
- for (Obstacle obs : obstacles) {
- nodes.addAll(obs.getKeyPoints());
- }
- // 娣诲姞浣滀笟杈圭晫椤剁偣锛屽厑璁歌创杈圭粫琛�
- if (workingArea != null && workingArea.size() >= 3) {
- nodes.addAll(workingArea);
- }
-
- // 鏋勫缓鍥�
- Map<Point, Map<Point, Double>> graph = new HashMap<>();
- for (Point p1 : nodes) {
- graph.put(p1, new HashMap<>());
- for (Point p2 : nodes) {
- if (p1 == p2) continue;
- if (isLineSafe(p1, p2, obstacles, workingArea)) {
- graph.get(p1).put(p2, distance(p1, p2));
- }
- }
- }
-
- // A*鎼滅储
- Map<Point, Double> gScore = new HashMap<>();
- Map<Point, Double> fScore = new HashMap<>();
- Map<Point, Point> cameFrom = new HashMap<>();
- PriorityQueue<Point> openSet = new PriorityQueue<>(
- Comparator.comparingDouble(p -> fScore.getOrDefault(p, Double.MAX_VALUE))
- );
-
- gScore.put(start, 0.0);
- fScore.put(start, heuristic(start, end));
- openSet.add(start);
-
- while (!openSet.isEmpty()) {
- Point current = openSet.poll();
-
- if (current.equals(end)) {
- return reconstructPath(cameFrom, current);
- }
-
- for (Map.Entry<Point, Double> neighborEntry : graph.getOrDefault(current, new HashMap<>()).entrySet()) {
- Point neighbor = neighborEntry.getKey();
- double tentativeGScore = gScore.get(current) + neighborEntry.getValue();
-
- if (tentativeGScore < gScore.getOrDefault(neighbor, Double.MAX_VALUE)) {
- cameFrom.put(neighbor, current);
- gScore.put(neighbor, tentativeGScore);
- fScore.put(neighbor, tentativeGScore + heuristic(neighbor, end));
-
- if (!openSet.contains(neighbor)) {
- openSet.add(neighbor);
- }
- }
- }
- }
-
- // 濡傛灉娌℃湁鎵惧埌璺緞锛屼笉鍋氫笉瀹夊叏鐨勮繛鎺�
- return new ArrayList<>();
- }
-
- /**
- * 閲嶆瀯璺緞
- */
- private static List<PathSegment> reconstructPath(Map<Point, Point> cameFrom, Point current) {
- List<Point> pathPoints = new ArrayList<>();
- while (current != null) {
- pathPoints.add(current);
- current = cameFrom.get(current);
- }
- Collections.reverse(pathPoints);
-
- List<PathSegment> path = new ArrayList<>();
- for (int i = 0; i < pathPoints.size() - 1; i++) {
- path.add(new PathSegment(pathPoints.get(i), pathPoints.get(i + 1), false));
- }
- return path;
- }
-
- /**
- * 鍚彂鍑芥暟
- */
- private static double heuristic(Point a, Point b) {
- return distance(a, b);
- }
-
- /**
- * 浼樺寲璺緞
- */
- private static List<PathSegment> optimizePath(List<PathSegment> path, double width) {
- if (path.size() <= 1) return path;
-
- List<PathSegment> optimized = new ArrayList<>();
- PathSegment current = path.get(0);
-
- for (int i = 1; i < path.size(); i++) {
- PathSegment next = path.get(i);
-
- // 妫�鏌ユ槸鍚﹀彲浠ュ悎骞跺綋鍓嶇嚎娈靛拰涓嬩竴绾挎
- if (canMergeSegments(current, next, width)) {
- // 鍚堝苟绾挎
- current = mergeSegments(current, next);
- } else {
- // 娣诲姞褰撳墠绾挎锛屽紑濮嬫柊鐨勫悎骞�
- optimized.add(current);
- current = next;
- }
- }
-
- optimized.add(current);
-
- // 骞虫粦杞
- optimized = smoothCorners(optimized, width);
-
- return optimized;
- }
-
- /**
- * 妫�鏌ユ槸鍚﹀彲浠ュ悎骞朵袱涓嚎娈�
- */
- private static boolean canMergeSegments(PathSegment a, PathSegment b, double width) {
- if (!a.isMowing || !b.isMowing) return false;
-
- // 妫�鏌ョ鐐规槸鍚﹂噸鍚�
- if (!a.end.equals(b.start) && !a.end.equals(b.end)) return false;
-
- // 妫�鏌ユ柟鍚戞槸鍚︿竴鑷�
- Point dir1 = new Point(a.end.x - a.start.x, a.end.y - a.start.y);
- Point dir2;
- if (a.end.equals(b.start)) {
- dir2 = new Point(b.end.x - b.start.x, b.end.y - b.start.y);
- } else {
- dir2 = new Point(b.start.x - b.end.x, b.start.y - b.end.y);
- }
-
- double angle = angleBetween(dir1, dir2);
- return angle < Math.toRadians(10); // 瑙掑害灏忎簬10搴﹀彲浠ュ悎骞�
- }
-
- /**
- * 鍚堝苟涓や釜绾挎
- */
- private static PathSegment mergeSegments(PathSegment a, PathSegment b) {
- Point newEnd = a.end.equals(b.start) ? b.end : b.start;
- return new PathSegment(a.start, newEnd, true);
- }
-
- /**
- * 骞虫粦杞
- */
- private static List<PathSegment> smoothCorners(List<PathSegment> path, double width) {
- if (path.size() < 3) return path;
-
- List<PathSegment> smoothed = new ArrayList<>();
- smoothed.add(path.get(0));
-
- for (int i = 1; i < path.size() - 1; i++) {
- PathSegment prev = path.get(i - 1);
- PathSegment curr = path.get(i);
- PathSegment next = path.get(i + 1);
-
- if (!prev.isMowing || !curr.isMowing || !next.isMowing) {
- smoothed.add(curr);
+ // 2. 绉婚櫎鍦ㄩ殰纰嶇墿鍐呴儴鐨勭嚎娈�
+ List<PathSegment> remainingSegments = new ArrayList<>();
+ for (PathSegment seg : originalSegments) {
+ if (!seg.isMowing) {
+ // 绌鸿蛋娈电洿鎺ヤ繚鐣�
+ remainingSegments.add(seg);
continue;
}
- // 璁$畻杞
- Point inVec = new Point(curr.start.x - prev.end.x, curr.start.y - prev.end.y);
- Point outVec = new Point(next.start.x - curr.end.x, next.start.y - curr.end.y);
+ // 灏嗗壊鑽夋涓庢墍鏈夐殰纰嶇墿杩涜瑁佸壀
+ List<PathSegment> clippedSegments = new ArrayList<>();
+ clippedSegments.add(seg);
- double angle = angleBetween(inVec, outVec);
+ for (Obstacle obs : obstacles) {
+ List<PathSegment> newSegments = new ArrayList<>();
+ for (PathSegment s : clippedSegments) {
+ newSegments.addAll(clipSegmentWithObstacle(s, obs));
+ }
+ clippedSegments = newSegments;
+ }
- if (angle < CORNER_THRESHOLD) {
- // 灏忚搴︼紝鍙互鐩存帴杩炴帴
- PathSegment direct = new PathSegment(prev.end, next.start, true);
- smoothed.remove(smoothed.size() - 1); // 绉婚櫎涓婁竴涓嚎娈�
- smoothed.add(direct);
- i++; // 璺宠繃涓嬩竴涓嚎娈�
+ remainingSegments.addAll(clippedSegments);
+ }
+
+ // 3. 閲嶆柊杩炴帴璺緞娈碉紙寮撳瓧褰㈣繛鎺ワ級
+ return reconnectSegments(remainingSegments);
+ }
+
+ /**
+ * 灏嗙嚎娈典笌闅滅鐗╄繘琛岃鍓�
+ * 杩斿洖涓嶅湪闅滅鐗╁唴閮ㄧ殑瀛愮嚎娈�
+ */
+ private static List<PathSegment> clipSegmentWithObstacle(PathSegment segment, Obstacle obstacle) {
+ List<PathSegment> result = new ArrayList<>();
+
+ // 妫�鏌ョ嚎娈垫槸鍚﹀畬鍏ㄥ湪闅滅鐗╁閮�
+ boolean startInside = obstacle.contains(segment.start);
+ boolean endInside = obstacle.contains(segment.end);
+
+ if (!startInside && !endInside) {
+ // 绾挎涓ょ閮藉湪澶栭儴锛屾鏌ユ槸鍚︾┛杩囬殰纰嶇墿
+ List<Point> intersections = obstacle.getIntersections(segment);
+ if (intersections.isEmpty()) {
+ // 瀹屽叏鍦ㄥ閮�
+ result.add(segment);
} else {
- smoothed.add(curr);
- }
- }
-
- if (path.size() > 1) {
- smoothed.add(path.get(path.size() - 1));
- }
-
- return smoothed;
- }
-
- // ==================== 鍑犱綍璁$畻宸ュ叿 ====================
-
- /**
- * 澶氳竟褰㈠亸绉荤畻娉�
- */
- private static List<Point> offsetPolygon(List<Point> polygon, double d) {
- // 鍩轰簬鈥滃亸绉昏竟鐩寸嚎浜ょ偣鈥濈殑杈冪ǔ鍋ュ疄鐜般�傜害瀹歱olygon涓篊CW锛屽乏娉曞悜閲忎负澶栦晶銆�
- if (polygon == null || polygon.size() < 3) return new ArrayList<>();
- List<Point> poly = new ArrayList<>(polygon);
- makeCCW(poly);
- int n = poly.size();
- List<Point> out = new ArrayList<>(n);
-
- for (int i = 0; i < n; i++) {
- Point A = poly.get((i - 1 + n) % n);
- Point B = poly.get(i);
- Point C = poly.get((i + 1) % n);
-
- Point e1 = normalize(subtract(B, A));
- Point e2 = normalize(subtract(C, B));
- Point n1 = new Point(-e1.y, e1.x);
- Point n2 = new Point(-e2.y, e2.x);
-
- Point p1 = add(B, multiply(n1, d));
- Point p2 = add(B, multiply(n2, d));
-
- Point dir1 = e1;
- Point dir2 = e2;
-
- Point inter = intersectLines(p1, dir1, p2, dir2);
- if (inter == null) {
- // 骞宠鎴栨暟鍊间笉绋冲畾鏃堕��鍖�
- Point avgN = add(n1, n2);
- if (magnitude(avgN) < EPS) avgN = n1;
- else avgN = normalize(avgN);
- inter = add(B, multiply(avgN, d));
- }
- out.add(inter);
- }
- return out;
- }
-
- // 璁$畻涓ゆ潯鍙傛暟鐩寸嚎鐨勪氦鐐� p=p0+t*v, q=q0+s*w
- private static Point intersectLines(Point p0, Point v, Point q0, Point w) {
- double det = v.x * w.y - v.y * w.x;
- if (Math.abs(det) < EPS) return null;
- double t = ((q0.x - p0.x) * w.y - (q0.y - p0.y) * w.x) / det;
- return new Point(p0.x + t * v.x, p0.y + t * v.y);
- }
-
- /**
- * 璁$畻鏈�浼樻壂鎻忚搴�
- */
- private static double calculateOptimalScanAngle(List<Point> polygon) {
- double bestAngle = 0;
- double minSpan = Double.MAX_VALUE;
-
- // 灏濊瘯澶氫釜瑙掑害
- for (int i = 0; i < 180; i += 5) {
- double angle = Math.toRadians(i);
- List<Point> rotated = rotatePolygon(polygon, angle);
-
- Bounds bounds = calculateBounds(rotated);
- double span = bounds.maxY - bounds.minY;
-
- if (span < minSpan) {
- minSpan = span;
- bestAngle = angle;
- }
- }
-
- return bestAngle;
- }
-
- /**
- * 鑾峰彇姘村钩绾夸笌澶氳竟褰㈢殑浜ょ偣
- */
- private static List<Double> getHorizontalIntersections(List<Point> polygon, double y) {
- List<Double> intersections = new ArrayList<>();
- int n = polygon.size();
-
- for (int i = 0; i < n; i++) {
- Point p1 = polygon.get(i);
- Point p2 = polygon.get((i + 1) % n);
-
- // 妫�鏌ヨ竟鏄惁涓庢按骞崇嚎鐩镐氦
- if ((p1.y <= y && p2.y >= y) || (p1.y >= y && p2.y <= y)) {
- if (Math.abs(p2.y - p1.y) < EPS) {
- // 姘村钩杈癸紝璺宠繃
- continue;
- }
+ // 绌胯繃闅滅鐗╋紝鍒嗗壊绾挎
+ intersections.sort(Comparator.comparingDouble(p ->
+ distance(segment.start, p)));
- double t = (y - p1.y) / (p2.y - p1.y);
- if (t >= -EPS && t <= 1 + EPS) {
- double x = p1.x + t * (p2.x - p1.x);
- intersections.add(x);
+ Point prevPoint = segment.start;
+ for (Point inter : intersections) {
+ result.add(new PathSegment(prevPoint, inter, true));
+ prevPoint = inter;
+ }
+ result.add(new PathSegment(prevPoint, segment.end, true));
+
+ // 绉婚櫎鍦ㄩ殰纰嶇墿鍐呴儴鐨勬锛堝鏁扮储寮曠殑娈碉級
+ List<PathSegment> filtered = new ArrayList<>();
+ for (int i = 0; i < result.size(); i++) {
+ PathSegment s = result.get(i);
+ Point midPoint = new Point(
+ (s.start.x + s.end.x) / 2,
+ (s.start.y + s.end.y) / 2
+ );
+ if (!obstacle.contains(midPoint)) {
+ filtered.add(s);
+ }
+ }
+ return filtered;
+ }
+ } else if (startInside && endInside) {
+ // 瀹屽叏鍦ㄥ唴閮紝涓㈠純
+ return result;
+ } else {
+ // 涓�绔湪鍐呴儴锛屼竴绔湪澶栭儴
+ Point insidePoint = startInside ? segment.start : segment.end;
+ Point outsidePoint = startInside ? segment.end : segment.start;
+
+ List<Point> intersections = obstacle.getIntersections(segment);
+ if (!intersections.isEmpty()) {
+ // 鍙栫澶栭儴鐐规渶杩戠殑浜ょ偣
+ intersections.sort(Comparator.comparingDouble(p ->
+ distance(outsidePoint, p)));
+ Point inter = intersections.get(0);
+
+ // 鍙繚鐣欏閮ㄩ儴鍒�
+ if (startInside) {
+ result.add(new PathSegment(inter, outsidePoint, true));
+ } else {
+ result.add(new PathSegment(outsidePoint, inter, true));
}
}
}
- // 鍘婚噸骞舵帓搴�
- intersections = intersections.stream()
- .distinct()
- .sorted()
- .collect(Collectors.toList());
-
- return intersections;
+ return result;
}
/**
- * 鍒ゆ柇鐩寸嚎鏄惁瀹夊叏
+ * 閲嶆柊杩炴帴璺緞娈碉紝褰㈡垚杩炵画寮撳瓧褰㈣矾寰�
*/
- private static boolean isLineSafe(Point p1, Point p2, List<Obstacle> obstacles, List<Point> workingArea) {
- // 蹇呴』瀹屽叏鍦ㄤ綔涓氬唴缂╄竟鐣屽唴
- if (workingArea != null && !isSegmentInsidePolygon(p1, p2, workingArea)) {
- return false;
- }
- for (Obstacle obs : obstacles) {
- if (obs.doesSegmentIntersect(p1, p2)) {
- return false;
- }
- }
- return true;
- }
-
- // 鍒ゆ柇绾挎鏄惁浣嶄簬澶氳竟褰㈠唴閮紙涓嶈秺鐣岋級
- private static boolean isSegmentInsidePolygon(Point a, Point b, List<Point> polygon) {
- if (polygon == null || polygon.size() < 3) return true;
- // 涓偣鍦ㄥ唴
- Point mid = new Point((a.x + b.x) / 2.0, (a.y + b.y) / 2.0);
- if (!pointInPolygon(mid, polygon)) return false;
- // 涓嶄笌杈圭晫鐩镐氦锛堝厑璁哥鐐规帴瑙︼級
- int n = polygon.size();
- for (int i = 0; i < n; i++) {
- Point p1 = polygon.get(i);
- Point p2 = polygon.get((i + 1) % n);
- if (lineSegmentIntersection(a, b, p1, p2)) {
- // 蹇界暐浠呭湪绔偣澶勭殑灏忔帴瑙�
- if (distance(a, p1) < EPS || distance(a, p2) < EPS || distance(b, p1) < EPS || distance(b, p2) < EPS) {
- continue;
+ private static List<PathSegment> reconnectSegments(List<PathSegment> segments) {
+ if (segments.isEmpty()) return new ArrayList<>();
+
+ List<PathSegment> reconnected = new ArrayList<>();
+ Point currentPos = segments.get(0).start;
+
+ for (PathSegment seg : segments) {
+ if (seg.isMowing) {
+ // 鍓茶崏娈碉細妫�鏌ユ槸鍚﹂渶瑕佹坊鍔犵┖璧版
+ if (distance(currentPos, seg.start) > 0.01) {
+ reconnected.add(new PathSegment(currentPos, seg.start, false));
}
- return false;
+ reconnected.add(seg);
+ currentPos = seg.end;
+ } else {
+ // 绌鸿蛋娈电洿鎺ユ坊鍔�
+ reconnected.add(seg);
+ currentPos = seg.end;
}
}
- return true;
- }
-
- private static boolean pointInPolygon(Point p, List<Point> poly) {
- boolean inside = false;
- for (int i = 0, j = poly.size() - 1; i < poly.size(); j = i++) {
- Point pi = poly.get(i), pj = poly.get(j);
- boolean intersect = ((pi.y > p.y) != (pj.y > p.y)) &&
- (p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y + EPS) + pi.x);
- if (intersect) inside = !inside;
- }
- return inside;
- }
-
- // ==================== 鍚戦噺杩愮畻宸ュ叿 ====================
-
- private static Point add(Point a, Point b) {
- return new Point(a.x + b.x, a.y + b.y);
- }
-
- private static Point subtract(Point a, Point b) {
- return new Point(a.x - b.x, a.y - b.y);
- }
-
- private static Point multiply(Point p, double scalar) {
- return new Point(p.x * scalar, p.y * scalar);
- }
-
- private static Point normalize(Point p) {
- double mag = magnitude(p);
- if (mag < EPS) return p;
- return new Point(p.x / mag, p.y / mag);
- }
-
- private static double magnitude(Point p) {
- return Math.sqrt(p.x * p.x + p.y * p.y);
- }
-
- private static double dot(Point a, Point b) {
- return a.x * b.x + a.y * b.y;
- }
-
- private static double angleBetween(Point a, Point b) {
- double dotProd = dot(a, b);
- double magA = magnitude(a);
- double magB = magnitude(b);
- if (magA < EPS || magB < EPS) return 0;
+ return reconnected;
+ }
+
+ /**
+ * 鐢熸垚鍘熷鎵弿璺緞锛堟棤闅滅鐗╃増鏈級
+ */
+ private static List<PathSegment> generateGlobalScanPath(
+ List<Point> polygon, double width, double angle, Point currentPos) {
- double cosAngle = dotProd / (magA * magB);
- cosAngle = Math.max(-1, Math.min(1, cosAngle));
- return Math.acos(cosAngle);
- }
-
- private static double distance(Point a, Point b) {
- return magnitude(subtract(a, b));
- }
-
- private static Point rotatePoint(Point p, double angle) {
- double cos = Math.cos(angle);
- double sin = Math.sin(angle);
- return new Point(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
- }
-
- private static List<Point> rotatePolygon(List<Point> polygon, double angle) {
- return polygon.stream()
- .map(p -> rotatePoint(p, angle))
- .collect(Collectors.toList());
- }
-
- private static Bounds calculateBounds(List<Point> points) {
- double minX = Double.MAX_VALUE, maxX = -Double.MAX_VALUE;
+ 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 : points) {
- minX = Math.min(minX, p.x);
- maxX = Math.max(maxX, p.x);
+ for (Point p : rotatedPoly) {
minY = Math.min(minY, p.y);
maxY = Math.max(maxY, p.y);
}
- return new Bounds(minX, maxX, minY, maxY);
- }
-
- private static void makeCCW(List<Point> polygon) {
- double area = 0;
- int n = polygon.size();
-
- for (int i = 0; i < n; i++) {
- Point p1 = polygon.get(i);
- Point p2 = polygon.get((i + 1) % n);
- area += (p2.x - p1.x) * (p2.y + p1.y);
+ boolean leftToRight = true;
+ 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));
+ }
+
+ 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 (distance(currentPos, s.start) > 0.01) {
+ segments.add(new PathSegment(currentPos, s.start, false));
+ }
+ segments.add(s);
+ currentPos = s.end;
+ }
+ leftToRight = !leftToRight;
}
- if (area > 0) {
- Collections.reverse(polygon);
- }
+ return segments;
}
- // ==================== 闅滅鐗╁鐞� ====================
-
- private static List<Obstacle> parseAndExpandObstacles(String obstaclesStr, double margin) {
+ /**
+ * 瑙f瀽闅滅鐗╁瓧绗︿覆
+ * 鏍煎紡锛�"(x1,y1;x2,y2)(x1,y1;x2,y2;x3,y3)"
+ */
+ private static List<Obstacle> parseObstacles(String obstaclesStr) {
List<Obstacle> obstacles = new ArrayList<>();
-
if (obstaclesStr == null || obstaclesStr.trim().isEmpty()) {
return obstacles;
}
- // 瑙f瀽闅滅鐗╁瓧绗︿覆
- Pattern pattern = Pattern.compile("\\(([^)]+)\\)");
- Matcher matcher = pattern.matcher(obstaclesStr);
+ String trimmed = obstaclesStr.trim();
+ List<String> obstacleStrs = new ArrayList<>();
- while (matcher.find()) {
- String coords = matcher.group(1);
- List<Point> points = parseCoordinates(coords);
+ // 鍒嗗壊姣忎釜闅滅鐗╋紙鐢ㄦ嫭鍙峰垎闅旓級
+ int start = trimmed.indexOf('(');
+ while (start != -1) {
+ int end = trimmed.indexOf(')', start);
+ if (end == -1) break;
+
+ String obsStr = trimmed.substring(start + 1, end);
+ obstacleStrs.add(obsStr);
+ start = trimmed.indexOf('(', end);
+ }
+
+ // 瑙f瀽姣忎釜闅滅鐗�
+ for (String obsStr : obstacleStrs) {
+ List<Point> points = new ArrayList<>();
+ String[] pairs = obsStr.split(";");
+
+ for (String pair : pairs) {
+ String[] xy = pair.split(",");
+ if (xy.length == 2) {
+ points.add(new Point(
+ Double.parseDouble(xy[0].trim()),
+ Double.parseDouble(xy[1].trim())
+ ));
+ }
+ }
if (points.size() == 2) {
- // 鍦嗗舰闅滅鐗�
+ // 鍦嗗舰闅滅鐗╋細绗竴涓偣涓哄渾蹇冿紝绗簩涓偣涓哄渾涓婁竴鐐�
Point center = points.get(0);
- double radius = distance(center, points.get(1)) + margin;
- obstacles.add(new CircularObstacle(center, radius));
- } else if (points.size() >= 3) {
+ Point onCircle = points.get(1);
+ double radius = distance(center, onCircle);
+ obstacles.add(new Obstacle(center, radius));
+ } else if (points.size() > 2) {
// 澶氳竟褰㈤殰纰嶇墿
- makeCCW(points);
- List<Point> expanded = offsetPolygon(points, margin);
- obstacles.add(new PolygonalObstacle(expanded));
+ obstacles.add(new Obstacle(points));
}
}
return obstacles;
}
- private static List<Point> parseCoordinates(String str) {
- List<Point> points = new ArrayList<>();
+ /**
+ * 澶栨墿闅滅鐗╋紙澧炲姞瀹夊叏杈硅窛锛�
+ */
+ private static List<Obstacle> expandObstacles(List<Obstacle> obstacles, double margin) {
+ List<Obstacle> expanded = new ArrayList<>();
- if (str == null || str.trim().isEmpty()) {
- return points;
- }
-
- String[] tokens = str.split(";");
- for (String token : tokens) {
- token = token.trim();
- if (token.isEmpty()) continue;
-
- String[] xy = token.split(",");
- if (xy.length == 2) {
- try {
- double x = Double.parseDouble(xy[0].trim());
- double y = Double.parseDouble(xy[1].trim());
- points.add(new Point(x, y));
- } catch (NumberFormatException e) {
- System.err.println("鏃犳晥鍧愭爣: " + token);
- }
+ for (Obstacle obs : obstacles) {
+ if (obs.isCircle()) {
+ // 鍦嗗舰锛氬崐寰勫鍔犲畨鍏ㄨ竟璺�
+ expanded.add(new Obstacle(obs.center, obs.radius + margin));
+ } else {
+ // 澶氳竟褰細鍚戝鍋忕Щ锛堜笌杈圭晫鍐呯缉鏂瑰悜鐩稿弽锛�
+ List<Point> expandedPoints = getOutsetPolygon(obs.points, margin);
+ expanded.add(new Obstacle(expandedPoints));
}
}
- return points;
- }
-
- // ==================== 鍐呴儴绫诲畾涔� ====================
-
- /**
- * 闅滅鐗╁熀绫�
- */
- abstract static class Obstacle {
- abstract List<PathSegment> clipSegment(PathSegment seg);
- abstract boolean doesSegmentIntersect(Point p1, Point p2);
- abstract boolean containsPoint(Point p);
- abstract List<Point> getKeyPoints();
+ return expanded;
}
/**
- * 澶氳竟褰㈤殰纰嶇墿
+ * 澶氳竟褰㈠鎵╋紙涓庡唴缂╂柟鍚戠浉鍙嶏級
*/
- static class PolygonalObstacle extends Obstacle {
- List<Point> vertices;
+ private static List<Point> getOutsetPolygon(List<Point> points, double margin) {
+ // 杩欓噷浣跨敤绠�鍖栫殑澶栨墿鏂规硶锛氭部娉曠嚎鍚戝绉诲姩
+ List<Point> outset = new ArrayList<>();
+ int n = points.size();
- PolygonalObstacle(List<Point> vertices) {
- this.vertices = vertices;
- }
-
- @Override
- List<PathSegment> clipSegment(PathSegment seg) {
- List<Double> tValues = new ArrayList<>();
- tValues.add(0.0);
- tValues.add(1.0);
+ 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);
- // 鏀堕泦鎵�鏈変氦鐐�
- for (int i = 0; i < vertices.size(); i++) {
- Point p1 = vertices.get(i);
- Point p2 = vertices.get((i + 1) % vertices.size());
-
- Double t = lineIntersection(seg.start, seg.end, p1, p2);
- if (t != null) {
- tValues.add(t);
- }
+ // 璁$畻涓や釜杈圭殑鍚戦噺
+ double v1x = pCurr.x - pPrev.x, v1y = pCurr.y - pPrev.y;
+ double v2x = pNext.x - pCurr.x, v2y = pNext.y - pCurr.y;
+
+ // 璁$畻娉曠嚎锛堢‘淇濆悜澶栵級
+ double nx1 = -v1y, ny1 = v1x;
+ double nx2 = -v2y, ny2 = v2x;
+
+ // 褰掍竴鍖�
+ double len1 = Math.hypot(nx1, ny1);
+ double len2 = Math.hypot(nx2, ny2);
+ if (len1 > 1e-6) { nx1 /= len1; ny1 /= len1; }
+ if (len2 > 1e-6) { nx2 /= len2; ny2 /= len2; }
+
+ // 璁$畻骞冲潎娉曠嚎鏂瑰悜
+ double nx = (nx1 + nx2) / 2;
+ double ny = (ny1 + ny2) / 2;
+ double len = Math.hypot(nx, ny);
+ if (len > 1e-6) {
+ nx /= len;
+ ny /= len;
}
- Collections.sort(tValues);
- List<PathSegment> result = new ArrayList<>();
-
- // 鐢熸垚涓嶅湪闅滅鐗╁唴閮ㄧ殑绾挎娈�
- for (int i = 0; i < tValues.size() - 1; i++) {
- double t1 = tValues.get(i);
- double t2 = tValues.get(i + 1);
- double tMid = (t1 + t2) / 2;
-
- Point midPoint = interpolate(seg.start, seg.end, tMid);
- if (!containsPoint(midPoint)) {
- Point start = interpolate(seg.start, seg.end, t1);
- Point end = interpolate(seg.start, seg.end, t2);
- result.add(new PathSegment(start, end, seg.isMowing));
- }
- }
-
- return result;
+ // 鍚戝绉诲姩
+ outset.add(new Point(
+ pCurr.x + nx * margin,
+ pCurr.y + ny * margin
+ ));
}
- @Override
- boolean doesSegmentIntersect(Point p1, Point p2) {
- for (int i = 0; i < vertices.size(); i++) {
- Point v1 = vertices.get(i);
- Point v2 = vertices.get((i + 1) % vertices.size());
-
- if (lineSegmentIntersection(p1, p2, v1, v2)) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- boolean containsPoint(Point p) {
- int crossings = 0;
-
- for (int i = 0; i < vertices.size(); i++) {
- Point v1 = vertices.get(i);
- Point v2 = vertices.get((i + 1) % vertices.size());
-
- if (((v1.y <= p.y && p.y < v2.y) || (v2.y <= p.y && p.y < v1.y)) &&
- (p.x < (v2.x - v1.x) * (p.y - v1.y) / (v2.y - v1.y) + v1.x)) {
- crossings++;
- }
- }
-
- return (crossings % 2) == 1;
- }
-
- @Override
- List<Point> getKeyPoints() {
- return new ArrayList<>(vertices);
- }
+ return outset;
}
/**
- * 鍦嗗舰闅滅鐗�
+ * 闅滅鐗╃被
*/
- static class CircularObstacle extends Obstacle {
- Point center;
- double radius;
+ private static class Obstacle {
+ List<Point> points; // 澶氳竟褰㈤《鐐癸紙瀵瑰渾褰负绌猴級
+ Point center; // 鍦嗗績锛堜粎瀵瑰渾褰㈡湁鏁堬級
+ double radius; // 鍗婂緞锛堜粎瀵瑰渾褰㈡湁鏁堬級
+ boolean isCircle;
- CircularObstacle(Point center, double radius) {
- this.center = center;
+ // 澶氳竟褰㈡瀯閫犲嚱鏁�
+ Obstacle(List<Point> points) {
+ this.points = new ArrayList<>(points);
+ this.isCircle = false;
+ ensureCounterClockwise(this.points); // 纭繚椤烘椂閽堬紙瀵归殰纰嶇墿鏄唴閮ㄥ尯鍩燂級
+ }
+
+ // 鍦嗗舰鏋勯�犲嚱鏁�
+ Obstacle(Point center, double radius) {
+ this.center = new Point(center.x, center.y);
this.radius = radius;
+ this.isCircle = true;
+ this.points = new ArrayList<>();
}
- @Override
- List<PathSegment> clipSegment(PathSegment seg) {
- double dx = seg.end.x - seg.start.x;
- double dy = seg.end.y - seg.start.y;
- double fx = seg.start.x - center.x;
- double 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;
-
- List<Double> tValues = new ArrayList<>();
- tValues.add(0.0);
- tValues.add(1.0);
-
- double discriminant = b * b - 4 * a * c;
- if (discriminant > 0) {
- double sqrtDisc = Math.sqrt(discriminant);
- double t1 = (-b - sqrtDisc) / (2 * a);
- double t2 = (-b + sqrtDisc) / (2 * a);
-
- if (t1 > EPS && t1 < 1 - EPS) tValues.add(t1);
- if (t2 > EPS && t2 < 1 - EPS) tValues.add(t2);
+ // 鍒ゆ柇鐐规槸鍚﹀湪闅滅鐗╁唴閮�
+ boolean contains(Point p) {
+ if (isCircle) {
+ return distance(p, center) <= radius;
+ } else {
+ return isPointInPolygon(p, points);
}
+ }
+
+ // 鑾峰彇绾挎涓庨殰纰嶇墿鐨勪氦鐐�
+ List<Point> getIntersections(PathSegment segment) {
+ List<Point> intersections = new ArrayList<>();
- Collections.sort(tValues);
- List<PathSegment> result = new ArrayList<>();
-
- for (int i = 0; i < tValues.size() - 1; i++) {
- double t1 = tValues.get(i);
- double t2 = tValues.get(i + 1);
- double tMid = (t1 + t2) / 2;
+ if (isCircle) {
+ // 绾挎涓庡渾鐨勪氦鐐�
+ double dx = segment.end.x - segment.start.x;
+ double dy = segment.end.y - segment.start.y;
+ double a = dx * dx + dy * dy;
+ double b = 2 * (dx * (segment.start.x - center.x) +
+ dy * (segment.start.y - center.y));
+ double c = (segment.start.x - center.x) * (segment.start.x - center.x) +
+ (segment.start.y - center.y) * (segment.start.y - center.y) -
+ radius * radius;
- Point midPoint = interpolate(seg.start, seg.end, tMid);
- if (!containsPoint(midPoint)) {
- Point start = interpolate(seg.start, seg.end, t1);
- Point end = interpolate(seg.start, seg.end, t2);
- result.add(new PathSegment(start, end, seg.isMowing));
+ double discriminant = b * b - 4 * a * c;
+ if (discriminant >= 0) {
+ discriminant = Math.sqrt(discriminant);
+ for (int sign = -1; sign <= 1; sign += 2) {
+ double t = (-b + sign * discriminant) / (2 * a);
+ if (t >= 0 && t <= 1) {
+ intersections.add(new Point(
+ segment.start.x + t * dx,
+ segment.start.y + t * dy
+ ));
+ }
+ }
+ }
+ } else {
+ // 绾挎涓庡杈瑰舰鐨勪氦鐐�
+ for (int i = 0; i < points.size(); i++) {
+ Point p1 = points.get(i);
+ Point p2 = points.get((i + 1) % points.size());
+
+ Point inter = getLineIntersection(
+ segment.start, segment.end, p1, p2);
+ if (inter != null) {
+ intersections.add(inter);
+ }
}
}
- return result;
+ return intersections;
}
- @Override
- boolean doesSegmentIntersect(Point p1, Point p2) {
- Point closest = closestPointOnSegment(center, p1, p2);
- // 灏嗕笌鍦嗙殑鐩稿垏涔熻涓虹浉浜わ紝閬垮厤璺緞鎿﹁竟
- return distance(center, closest) <= radius + EPS;
+ boolean isCircle() {
+ return isCircle;
}
-
- @Override
- boolean containsPoint(Point p) {
- return distance(center, p) < radius - EPS;
- }
-
- @Override
- List<Point> getKeyPoints() {
- List<Point> points = new ArrayList<>();
- int numPoints = 8; // 鍏竟褰㈣繎浼�
+ }
+
+ /**
+ * 鍒ゆ柇鐐规槸鍚﹀湪澶氳竟褰㈠唴閮紙灏勭嚎娉曪級
+ */
+ private static boolean isPointInPolygon(Point p, List<Point> polygon) {
+ boolean inside = false;
+ for (int i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) {
+ Point pi = polygon.get(i);
+ Point pj = polygon.get(j);
- for (int i = 0; i < numPoints; i++) {
- double angle = 2 * Math.PI * i / numPoints;
- points.add(new Point(
- center.x + radius * Math.cos(angle),
- center.y + radius * Math.sin(angle)
- ));
+ if (((pi.y > p.y) != (pj.y > p.y)) &&
+ (p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y) + pi.x)) {
+ inside = !inside;
}
-
- return points;
}
+ return inside;
}
/**
- * 璺緞娈�
+ * 璁$畻涓ゆ潯绾挎鐨勪氦鐐�
*/
- public static class PathSegment {
- public Point start, end;
- public boolean isMowing;
+ private static Point getLineIntersection(Point p1, Point p2, Point p3, Point p4) {
+ double denom = (p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x);
+ if (Math.abs(denom) < 1e-6) return null; // 骞宠
- public PathSegment(Point start, Point end, boolean isMowing) {
- this.start = start;
- this.end = end;
- this.isMowing = isMowing;
+ double t = ((p1.x - p3.x) * (p3.y - p4.y) - (p1.y - p3.y) * (p3.x - p4.x)) / denom;
+ double u = -((p1.x - p2.x) * (p1.y - p3.y) - (p1.y - p2.y) * (p1.x - p3.x)) / denom;
+
+ if (t >= 0 && t <= 1 && u >= 0 && u <= 1) {
+ return new Point(
+ p1.x + t * (p2.x - p1.x),
+ p1.y + t * (p2.y - p1.y)
+ );
}
-
- @Override
- public String toString() {
- return String.format("%s -> %s [%s]", start, end, isMowing ? "MOW" : "MOVE");
- }
- }
-
- /**
- * 鐐圭被
- */
- 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 obj) {
- if (this == obj) return true;
- if (!(obj instanceof Point)) return false;
- Point other = (Point) obj;
- return Math.abs(x - other.x) < EPS && Math.abs(y - other.y) < EPS;
- }
-
- @Override
- public int hashCode() {
- return Double.hashCode(x) * 31 + Double.hashCode(y);
- }
-
- @Override
- public String toString() {
- return String.format("(%.2f, %.2f)", x, y);
- }
- }
-
- /**
- * 杈圭晫妗�
- */
- private static class Bounds {
- double minX, maxX, minY, maxY;
-
- Bounds(double minX, double maxX, double minY, double maxY) {
- this.minX = minX;
- this.maxX = maxX;
- this.minY = minY;
- this.maxY = maxY;
- }
- }
-
- // ==================== 鍑犱綍宸ュ叿鍑芥暟 ====================
-
- private static Double lineIntersection(Point a1, Point a2, Point b1, Point b2) {
- double det = (a2.x - a1.x) * (b2.y - b1.y) - (a2.y - a1.y) * (b2.x - b1.x);
-
- if (Math.abs(det) < EPS) return null;
-
- double t = ((b1.x - a1.x) * (b2.y - b1.y) - (b1.y - a1.y) * (b2.x - b1.x)) / det;
- double u = ((a1.x - b1.x) * (a2.y - a1.y) - (a1.y - b1.y) * (a2.x - a1.x)) / (-det);
-
- if (t >= -EPS && t <= 1 + EPS && u >= -EPS && u <= 1 + EPS) {
- return Math.max(0, Math.min(1, t));
- }
-
return null;
}
- private static boolean lineSegmentIntersection(Point a1, Point a2, Point b1, Point b2) {
- Double t = lineIntersection(a1, a2, b1, b2);
- return t != null;
+ /**
+ * 璁$畻涓ょ偣璺濈
+ */
+ private static double distance(Point p1, Point p2) {
+ return Math.hypot(p1.x - p2.x, p1.y - p2.y);
}
- 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);
+ // ============ 浠ヤ笅鏄粠A浠g爜澶嶇敤鐨勬柟娉� ============
+
+ 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 Point closestPointOnSegment(Point p, Point a, Point b) {
- double ax = b.x - a.x;
- double ay = b.y - a.y;
- double bx = p.x - a.x;
- double by = p.y - a.y;
-
- double dot = ax * bx + ay * by;
- double lenSq = ax * ax + ay * ay;
-
- double t = (lenSq > EPS) ? Math.max(0, Math.min(1, dot / lenSq)) : 0;
-
- return new Point(a.x + t * ax, a.y + t * ay);
- }
-
-}
\ No newline at end of file
+ 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<>();
+ for (int i = 0; i < rotatedPoly.size(); i++) {
+ Point p1 = rotatedPoly.get(i);
+ Point p2 = rotatedPoly.get((i + 1) % rotatedPoly.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);
+ 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;
+ }
+
+ private 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 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);
+ }
+
+ private 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;
+ public PathSegment(Point s, Point e, boolean m) {
+ this.start = s;
+ this.end = e;
+ this.isMowing = m;
+ }
+ }
+}
+
--
Gitblit v1.10.0