张世豪
3 天以前 dc0fb19555dc01bf873361c9cb6fc22fbfc9671d
异形无障碍坐标规划优化
已修改8个文件
746 ■■■■ 文件已修改
Obstacledge.properties 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
dikuai.properties 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
set.properties 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shoudongbianjie.properties 6 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/lujing/AoxinglujingNoObstacle.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/lujing/YixinglujingNoObstacle.java 540 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/zhangaiwu/AddDikuai.java 153 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/zhuye/Shouye.java 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Obstacledge.properties
@@ -1,5 +1,5 @@
# 割草机地块障碍物配置文件
# 生成时间:2025-12-19T19:40:57.347052
# 生成时间:2025-12-23T17:37:19.839482400
# 坐标系:WGS84(度分格式)
# ============ 地块基准站配置 ============
dikuai.properties
@@ -1,16 +1,25 @@
#Dikuai Properties
#Tue Dec 23 16:39:12 CST 2025
#Tue Dec 23 17:37:19 CST 2025
LAND1.angleThreshold=-1
LAND1.baseStationCoordinates=3949.89151752,N,11616.79267501,E
LAND1.boundaryCoordinates=42.327,2.469;39.527,1.769;35.235,0.943;33.800,0.591;32.427,0.156;31.148,-0.377;30.259,-1.257;30.032,-2.368;30.124,-3.806;30.592,-6.598;31.331,-10.769
LAND1.boundaryOriginalCoordinates=39.831547,116.280373,49.32;39.831544,116.280357,49.33;39.831541,116.280340,49.29;39.831539,116.280324,49.27;39.831536,116.280307,49.24;39.831534,116.280290,49.25;39.831531,116.280273,49.26;39.831527,116.280257,49.28;39.831522,116.280242,49.21;39.831514,116.280232,49.28;39.831504,116.280229,49.24;39.831491,116.280230,49.33;39.831478,116.280233,49.34;39.831466,116.280236,49.31;39.831454,116.280239,49.31;39.831441,116.280242,49.26;39.831429,116.280244,49.23
LAND1.boundaryOriginalXY=42.323,2.417;40.955,2.083;39.502,1.749;38.134,1.526;36.681,1.192;35.227,0.969;33.774,0.635;32.406,0.190;31.124,-0.366;30.269,-1.257;30.013,-2.370;30.098,-3.817;30.355,-5.265;30.611,-6.600;30.868,-7.936;31.124,-9.383;31.295,-10.719
LAND1.createTime=2025-12-23 16\:39\:12
LAND1.landArea=66.72
LAND1.landName=12123
LAND1.boundaryCoordinates=4.30,87.65;-2.36,-65.51;44.25,-66.72;49.70,-14.05;98.13,-15.87;99.34,-69.75;137.48,-67.93;134.45,90.07;4.30,87.65
LAND1.boundaryOriginalCoordinates=39.831522,116.279873,49.25;39.831524,116.279878,49.25;39.831525,116.279878,49.24;39.831524,116.279912,49.30;39.831524,116.279911,49.29;39.831523,116.279911,49.23;39.831521,116.279915,49.31;39.831517,116.279925,49.34;39.831514,116.279940,49.30;39.831514,116.279957,49.28;39.831516,116.279974,49.28;39.831518,116.279991,49.29;39.831521,116.280008,49.24;39.831524,116.280025,49.30;39.831526,116.280042,49.24;39.831529,116.280059,49.29;39.831529,116.280076,49.26;39.831530,116.280093,49.32;39.831531,116.280110,49.28;39.831533,116.280127,49.28;39.831535,116.280144,49.26;39.831539,116.280161,49.27;39.831544,116.280175,49.25;39.831551,116.280190,49.24;39.831558,116.280204,49.26;39.831566,116.280219,49.26;39.831574,116.280234,49.22;39.831583,116.280248,49.24;39.831591,116.280260,49.24;39.831600,116.280272,49.23;39.831608,116.280285,49.18;39.831615,116.280298,49.12;39.831618,116.280312,49.11;39.831618,116.280328,49.12;39.831615,116.280342,49.15;39.831610,116.280356,49.21;39.831602,116.280369,49.23;39.831592,116.280379,49.25;39.831581,116.280388,49.25;39.831569,116.280394,49.19;39.831559,116.280395,49.23;39.831552,116.280387,49.28;39.831547,116.280373,49.32;39.831544,116.280357,49.33;39.831541,116.280340,49.29;39.831539,116.280324,49.27;39.831536,116.280307,49.24;39.831534,116.280290,49.25;39.831531,116.280273,49.26;39.831527,116.280257,49.28;39.831522,116.280242,49.21;39.831514,116.280232,49.28;39.831504,116.280229,49.24;39.831491,116.280230,49.33;39.831478,116.280233,49.34;39.831466,116.280236,49.31;39.831454,116.280239,49.31;39.831441,116.280242,49.26;39.831429,116.280244,49.23;39.831416,116.280247,49.25;39.831402,116.280250,49.22;39.831389,116.280253,49.25;39.831376,116.280256,49.26;39.831364,116.280258,49.24;39.831351,116.280261,49.25;39.831338,116.280265,49.26;39.831324,116.280268,49.20;39.831311,116.280271,49.16;39.831298,116.280274,49.17;39.831285,116.280277,49.22;39.831271,116.280278,49.16;39.831261,116.280273,49.23
LAND1.boundaryOriginalXY=-1
LAND1.boundaryPointInterval=-1
LAND1.createTime=2025-12-23 17\:08\:09
LAND1.intelligentSceneAnalysis=-1
LAND1.landArea=577.12
LAND1.landName=123
LAND1.landNumber=LAND1
LAND1.mowingBladeWidth=0.50
LAND1.mowingBladeWidth=0.51
LAND1.mowingOverlapDistance=0.06
LAND1.mowingPattern=平行线
LAND1.mowingSafetyDistance=0.53
LAND1.mowingWidth=43.00
LAND1.plannedPath=30.655,-1.967;31.684,-0.728;32.539,-0.371;30.586,-2.723;30.626,-3.348;33.306,-0.122;34.055,0.108;30.685,-3.949;30.779,-4.509;34.757,0.280;35.454,0.445;30.873,-5.069;30.967,-5.629;36.119,0.573;36.784,0.701;31.061,-6.189;31.157,-6.747;37.450,0.829;38.115,0.958;31.255,-7.301;31.353,-7.856;38.780,1.086;39.446,1.214;31.451,-8.411;31.550,-8.965;40.139,1.376;40.845,1.552;31.648,-9.520
LAND1.updateTime=2025-12-23 16\:39\:12
LAND1.mowingTrack=-1
LAND1.mowingWidth=200
LAND1.plannedPath=136.940221,-67.425155;133.930254,89.530244;4.807861,87.129352;-1.807069,-64.994176;43.773311,-66.177447;49.223902,-13.501734;98.648661,-15.359117;99.857663,-69.194695;136.940221,-67.425155;134.941682,-67.520523;131.930599,89.493063;129.930944,89.455881;132.943143,-67.615891;130.944605,-67.711259;127.931289,89.418700;125.931635,89.381519;128.946066,-67.806627;126.947527,-67.901995;123.931980,89.344337;121.932325,89.307156;124.948988,-67.997363;122.950449,-68.092732;119.932671,89.269974;117.933016,89.232793;120.951910,-68.188100;118.953371,-68.283468;115.933361,89.195611;113.933707,89.158430;116.954833,-68.378836;114.956294,-68.474204;111.934052,89.121248;109.934397,89.084067;112.957755,-68.569572;110.959216,-68.664940;107.934743,89.046886;105.935088,89.009704;108.960677,-68.760308;106.962138,-68.855677;103.935433,88.972523;101.935778,88.935341;104.963600,-68.951045;102.965061,-69.046413;99.936124,88.898160;97.936469,88.860978;100.966522,-69.141781;97.934238,-15.332269;95.936814,88.823797;93.937160,88.786615;95.932427,-15.257041;93.930617,-15.181813;91.937505,88.749434;89.937850,88.712253;91.928806,-15.106585;89.926996,-15.031357;87.938196,88.675071;85.938541,88.637890;87.925186,-14.956129;85.923375,-14.880901;83.938886,88.600708;81.939231,88.563527;83.921565,-14.805673;81.919754,-14.730445;79.939577,88.526345;77.939922,88.489164;79.917944,-14.655217;77.916134,-14.579989;75.940267,88.451983;73.940613,88.414801;75.914323,-14.504760;73.912513,-14.429532;71.940958,88.377620;69.941303,88.340438;71.910702,-14.354304;69.908892,-14.279076;67.941649,88.303257;65.941994,88.266075;67.907082,-14.203848;65.905271,-14.128620;63.942339,88.228894;61.942685,88.191712;63.903461,-14.053392;61.901651,-13.978164;59.943030,88.154531;57.943375,88.117350;59.899840,-13.902936;57.898030,-13.827708;55.943720,88.080168;53.944066,88.042987;55.896219,-13.752480;53.894409,-13.677252;51.944411,88.005805;49.944756,87.968624;51.892599,-13.602024;49.890788,-13.526796;47.945102,87.931442;45.945447,87.894261;48.098512,-24.377753;46.410911,-40.687091;43.945792,87.857079;41.946138,87.819898;44.723311,-56.996429;42.898575,-66.154738;39.946483,87.782717;37.946828,87.745535;40.897210,-66.102783;38.895846,-66.050827;35.947173,87.708354;33.947519,87.671172;36.894482,-65.998872;34.893118,-65.946916;31.947864,87.633991;29.948209,87.596809;32.891754,-65.894960;30.890390,-65.843005;27.948555,87.559628;25.948900,87.522447;28.889026,-65.791049;26.887662,-65.739094;23.949245,87.485265;21.949591,87.448084;24.886298,-65.687138;22.884934,-65.635182;19.949936,87.410902;17.950281,87.373721;20.883570,-65.583227;18.882205,-65.531271;15.950627,87.336539;13.950972,87.299358;16.880841,-65.479315;14.879477,-65.427360;11.951317,87.262176;9.951662,87.224995;12.878113,-65.375404;10.876749,-65.323449;7.952008,87.187814;5.952353,87.150632;8.875385,-65.271493;6.874021,-65.219537;4.214206,73.477072;2.826044,41.553502;4.872657,-65.167582;2.871293,-65.115626;1.437881,9.629932;0.049718,-22.293638;0.869929,-65.063671
LAND1.returnPathCoordinates=-1
LAND1.returnPathRawCoordinates=-1
LAND1.returnPointCoordinates=-1
LAND1.updateTime=2025-12-23 17\:37\:19
LAND1.userId=-1
set.properties
@@ -1,5 +1,5 @@
#Mower Configuration Properties - Updated
#Tue Dec 23 16:52:57 CST 2025
#Tue Dec 23 17:49:41 CST 2025
appVersion=-1
boundaryLengthVisible=false
currentWorkLandNumber=LAND1
@@ -8,12 +8,12 @@
handheldMarkerId=1872
idleTrailDurationSeconds=60
manualBoundaryDrawingMode=false
mapScale=24.33
mapScale=0.53
measurementModeEnabled=false
mowerId=860
serialAutoConnect=true
serialBaudRate=115200
serialPortName=COM15
simCardNumber=-1
viewCenterX=-35.75
viewCenterY=3.10
viewCenterX=-76.97
viewCenterY=8.49
shoudongbianjie.properties
@@ -1,11 +1,11 @@
#\u624B\u52A8\u7ED8\u5236\u8FB9\u754C\u5750\u6807 - \u683C\u5F0F: x1,y1;x2,y2;...;xn,yn (\u5355\u4F4D:\u7C73,\u7CBE\u786E\u5230\u5C0F\u6570\u70B9\u540E2\u4F4D)
#Mon Dec 22 13:04:43 CST 2025
boundaryCoordinates=35.56,-10.63;28.61,2.02;34.81,9.97;45.73,-6.54;43.75,-13.48
#Tue Dec 23 17:49:02 CST 2025
boundaryCoordinates=-99.64,193.56;185.77,182.30;61.84,424.89;237.59,415.88;235.34,539.80;-26.03,544.31
email=789
language=zh
lastLoginTime=-1
password=123
pointCount=5
pointCount=6
registrationTime=-1
status=-1
userId=-1
src/lujing/AoxinglujingNoObstacle.java
@@ -40,7 +40,7 @@
     * 坐标点类
     */
    public static class Point {
        double x, y;
        public double x, y;
        public Point(double x, double y) {
            this.x = x;
src/lujing/YixinglujingNoObstacle.java
@@ -1,454 +1,232 @@
package lujing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.*;
/**
 * 异形(无障碍物)草地路径规划类 - 优化版 V2.0
 * * 功能特点:
 * 1. 自动处理凹多边形(通过耳切法分割)
 * 2. 增加“围边”路径,保证边缘割草整洁
 * 3. 自动计算每个子区域的最优扫描角度(减少掉头次数)
 * 4. 智能区域连接(支持双向路径选择)
 * 异形草地路径规划 - 围边+全局扫描版 V4.1
 * 优化:围边终点与弓字形起点自动对齐,实现无缝切换,确保路径不越界
 */
public class YixinglujingNoObstacle {
    // ==========================================
    // 对外接口
    // ==========================================
    /**
     * 规划异形草地割草路径
     *
     * @param coordinates 地块边界坐标字符串,格式:"x1,y1;x2,y2;x3,y3;..."
     * @param widthStr    割草宽度(米),如 "0.34"
     * @param marginStr   安全边距(米),如 "0.2"
     * @return 路径段列表
     */
    public static List<PathSegment> planPath(String coordinates, String widthStr, String marginStr) {
        // 1. 参数解析与预处理
        List<Point> rawPoints = parseCoordinates(coordinates);
        if (rawPoints.size() < 3) {
            throw new IllegalArgumentException("多边形点数不足,无法构成地块");
        }
        // 确保逆时针顺序,方便后续几何计算
        ensureCounterClockwise(rawPoints);
        if (rawPoints.size() < 3) return new ArrayList<>();
        double mowWidth = Double.parseDouble(widthStr);
        double safeMargin = Double.parseDouble(marginStr);
        
        // 1. 预处理:逆时针化
        ensureCounterClockwise(rawPoints);
        // 2. 生成内缩多边形
        List<Point> boundary = getInsetPolygon(rawPoints, safeMargin);
        if (boundary.size() < 3) return new ArrayList<>();
        // 3. 确定最优扫描角度并找到弓字形路径的第一个作业起点
        double bestAngle = findOptimalAngle(boundary);
        Point firstScanStart = getFirstScanPoint(boundary, mowWidth, bestAngle);
        // 4. 对齐围边起点:重新排列围边坐标,使最后一个点靠近(或等于)扫描起点
        List<Point> alignedBoundary = alignBoundaryStart(boundary, firstScanStart);
        List<PathSegment> finalPath = new ArrayList<>();
        // 2. 生成围边路径 (Contour Path)
        // 这一步先规划一圈轮廓,解决异形边缘难处理的问题
        List<Point> contourPoly = getInsetPolygon(rawPoints, safeMargin);
        // 如果内缩后面积太小或点数不足,直接返回空
        if (contourPoly.size() < 3) {
            return new ArrayList<>();
        // 5. 【第一步】生成围边路径
        for (int i = 0; i < alignedBoundary.size(); i++) {
            Point pStart = alignedBoundary.get(i);
            Point pEnd = alignedBoundary.get((i + 1) % alignedBoundary.size());
            finalPath.add(new PathSegment(pStart, pEnd, true));
        }
        // 将围边路径加入结果
        for (int i = 0; i < contourPoly.size(); i++) {
            Point p1 = contourPoly.get(i);
            Point p2 = contourPoly.get((i + 1) % contourPoly.size());
            finalPath.add(new PathSegment(p1, p2, true)); // true = 割草
        }
        // 6. 【第二步】从对齐后的终点开始生成内部扫描路径
        Point lastEdgePos = alignedBoundary.get(0); // 围边闭合回到起点
        List<PathSegment> scanPath = generateGlobalScanPath(boundary, mowWidth, bestAngle, lastEdgePos);
        
        // 记录围边结束后的位置(通常回到围边起点)
        Point endOfContour = contourPoly.get(0);
        // 3. 区域分割 (Decomposition)
        // 使用耳切法将围边后的多边形分割为多个凸多边形(三角形)
        // 这样可以保证覆盖无遗漏
        List<List<Point>> triangles = triangulatePolygon(contourPoly);
        // 4. 对每个区域生成内部填充路径
        List<List<PathSegment>> allRegionPaths = new ArrayList<>();
        for (List<Point> triangle : triangles) {
            // 【优化】寻找最优扫描角度:
            // 遍历三角形的三条边,计算以哪条边为基准扫描时,生成的行数最少(转弯最少)
            List<PathSegment> regionPath = planConvexPathOptimal(triangle, mowWidth);
            if (!regionPath.isEmpty()) {
                allRegionPaths.add(regionPath);
            }
        }
        // 5. 连接所有内部区域 (Greedy Connection)
        // 从围边结束点开始,寻找最近的下一个区域
        List<PathSegment> internalPaths = connectRegions(allRegionPaths, endOfContour);
        finalPath.addAll(internalPaths);
        finalPath.addAll(scanPath);
        return finalPath;
    }
    // ==========================================
    // 核心规划算法
    // ==========================================
    /**
     * 规划凸多边形路径,自动选择最优角度
     * 计算并获取扫描路径的第一行起点
     */
    private static List<PathSegment> planConvexPathOptimal(List<Point> polygon, double width) {
        if (polygon.size() < 3) return new ArrayList<>();
    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 bestAngle = 0;
        double minLines = Double.MAX_VALUE;
        // 遍历多边形的每一条边,尝试以该边角度进行扫描
        for (int i = 0; i < polygon.size(); i++) {
            Point p1 = polygon.get(i);
            Point p2 = polygon.get((i + 1) % polygon.size());
            // 计算边的角度
            double angle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
            // 计算在这个角度下,多边形的垂直投影高度
            // 高度越小,意味着沿此方向扫描的行数越少,效率越高
            double height = calculatePolygonHeight(polygon, -angle);
            if (height < minLines) {
                minLines = height;
                bestAngle = angle;
            }
        }
        // 使用最佳角度生成路径
        return generatePathWithAngle(polygon, width, bestAngle);
    }
    /**
     * 根据指定角度生成弓字形路径
     */
    private static List<PathSegment> generatePathWithAngle(List<Point> polygon, double width, double angle) {
        // 1. 将多边形旋转到水平位置
        List<Point> rotatedPoints = new ArrayList<>();
        for (Point p : polygon) {
            rotatedPoints.add(rotatePoint(p, -angle));
        }
        // 2. 计算Y轴范围
        double minY = Double.MAX_VALUE;
        double maxY = -Double.MAX_VALUE;
        for (Point p : rotatedPoints) {
        for (Point p : rotatedPoly) minY = Math.min(minY, p.y);
        double firstY = minY + width;
        List<Double> xIntersections = getXIntersections(rotatedPoly, firstY);
        if (xIntersections.isEmpty()) return polygon.get(0);
        return rotatePoint(new Point(Collections.min(xIntersections), 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<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);
        }
        List<PathSegment> segments = new ArrayList<>();
        boolean leftToRight = true;
        // 从 minY + width 开始,避开围边已割区域
        for (double y = minY + width; y <= maxY - width/2; y += width) {
            List<Double> xIntersections = getXIntersections(rotatedPoly, y);
            if (xIntersections.size() < 2) continue;
            Collections.sort(xIntersections);
        // 3. 扫描线生成 (从 minY + width/2 开始,保证第一刀切在多边形内)
        for (double y = minY + width / 2; y <= maxY; y += width) {
            List<Double> intersections = new ArrayList<>();
            for (int i = 0; i < rotatedPoints.size(); i++) {
                Point p1 = rotatedPoints.get(i);
                Point p2 = rotatedPoints.get((i + 1) % rotatedPoints.size());
                // 判断扫描线是否穿过边
                if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) {
                    double x = p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y);
                    intersections.add(x);
                }
            }
            Collections.sort(intersections);
            // 成对生成线段
            for (int k = 0; k < intersections.size() - 1; k += 2) {
                double x1 = leftToRight ? intersections.get(k) : intersections.get(k + 1);
                double x2 = leftToRight ? intersections.get(k + 1) : intersections.get(k);
                Point start = new Point(x1, y);
                Point end = new Point(x2, y);
                // 旋转回原始坐标系
                Point originalStart = rotatePoint(start, angle);
                Point originalEnd = rotatePoint(end, angle);
                // 连接逻辑:如果不是第一段,需要从上一段终点连过来
                if (!segments.isEmpty()) {
                    PathSegment prev = segments.get(segments.size() - 1);
                    // 添加连接线(通常算作割草路径的一部分,保持弓字形连续)
                    segments.add(new PathSegment(prev.end, originalStart, true));
            List<PathSegment> lineRows = 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);
                lineRows.add(new PathSegment(pS, pE, true));
                }
                segments.add(new PathSegment(originalStart, originalEnd, true));
            if (!leftToRight) {
                Collections.reverse(lineRows);
                for (PathSegment s : lineRows) {
                    Point t = s.start; s.start = s.end; s.end = t;
            }
            leftToRight = !leftToRight; // 换向
        }
            for (PathSegment s : lineRows) {
                // 如果间距极小,视为无缝衔接
                if (Math.hypot(currentPos.x - s.start.x, currentPos.y - s.start.y) > 0.05) {
                    segments.add(new PathSegment(currentPos, s.start, false));
                }
                segments.add(s);
                currentPos = s.end;
            }
            leftToRight = !leftToRight;
        }
        return segments;
    }
    /**
     * 连接所有分割后的区域 (贪心策略 + 双向优化)
     */
    private static List<PathSegment> connectRegions(List<List<PathSegment>> regions, Point startPoint) {
        List<PathSegment> result = new ArrayList<>();
        if (regions.isEmpty()) return result;
        List<List<PathSegment>> remaining = new ArrayList<>(regions);
        Point currentPos = startPoint;
        while (!remaining.isEmpty()) {
            int bestIndex = -1;
            double minDist = Double.MAX_VALUE;
            boolean needReverse = false;
            // 寻找离当前位置最近的区域起点或终点
            for (int i = 0; i < remaining.size(); i++) {
                List<PathSegment> region = remaining.get(i);
                Point pStart = region.get(0).start;
                Point pEnd = region.get(region.size() - 1).end;
                double dStart = distance(currentPos, pStart);
                double dEnd = distance(currentPos, pEnd);
                // 检查正向进入
                if (dStart < minDist) {
                    minDist = dStart;
                    bestIndex = i;
                    needReverse = false;
                }
                // 检查反向进入(倒着割草如果更近)
                if (dEnd < minDist) {
                    minDist = dEnd;
                    bestIndex = i;
                    needReverse = true;
    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);
                }
            }
            if (bestIndex != -1) {
                List<PathSegment> targetRegion = remaining.remove(bestIndex);
                if (needReverse) {
                    // 反转该区域的所有路径
                    List<PathSegment> reversedRegion = new ArrayList<>();
                    for (int k = targetRegion.size() - 1; k >= 0; k--) {
                        PathSegment seg = targetRegion.get(k);
                        // 交换起点终点
                        reversedRegion.add(new PathSegment(seg.end, seg.start, seg.isMowing));
                    }
                    targetRegion = reversedRegion;
        return xIntersections;
                }
                // 添加过渡路径(抬刀移动,isMowing=false)
                Point nextStart = targetRegion.get(0).start;
                // 只有距离显著才添加移动段
                if (distance(currentPos, nextStart) > 0.01) {
                    result.add(new PathSegment(currentPos, nextStart, false));
    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;
                }
                result.addAll(targetRegion);
                currentPos = targetRegion.get(targetRegion.size() - 1).end;
            } else {
                break; // 防御性代码
            }
        }
        return result;
    }
    // ==========================================
    // 几何运算辅助方法
    // ==========================================
    /**
     * 内缩多边形 (基于角平分线)
     */
    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);
            Point v1 = new Point(pCurr.x - pPrev.x, pCurr.y - pPrev.y);
            Point v2 = new Point(pNext.x - pCurr.x, pNext.y - pCurr.y);
            double len1 = Math.hypot(v1.x, v1.y);
            double len2 = Math.hypot(v2.x, v2.y);
            if (len1 < 1e-6 || len2 < 1e-6) continue;
            // 归一化向量
            Point n1 = new Point(v1.x / len1, v1.y / len1);
            Point n2 = new Point(v2.x / len2, v2.y / len2);
            // 计算平分线方向
            // v1反向 + v2
            Point bisector = new Point(-n1.x + n2.x, -n1.y + n2.y);
            double biLen = Math.hypot(bisector.x, bisector.y);
            // 计算半角 sin(theta/2)
            double cross = n1.x * n2.y - n1.y * n2.x; // 叉积判断转向
            // 默认向左侧内缩 (CCW多边形)
            if (biLen < 1e-6) {
                // 共线,沿法线方向
                bisector = new Point(-n1.y, n1.x);
            } else {
                bisector.x /= biLen;
                bisector.y /= biLen;
            }
            // 计算偏移距离
            double dot = n1.x * n2.x + n1.y * n2.y;
            double angle = Math.acos(Math.max(-1, Math.min(1, dot)));
            double dist = margin / Math.sin(angle / 2.0);
            // 方向修正:确保平分线指向多边形内部(逆时针多边形的左侧)
            Point leftNormal = new Point(-n1.y, n1.x);
            if (bisector.x * leftNormal.x + bisector.y * leftNormal.y < 0) {
                 bisector.x = -bisector.x;
                 bisector.y = -bisector.y;
            }
            // 如果是凹角(cross < 0),平分线指向外部,距离需要反转或者特殊处理
            // 简单处理:对于凹角,偏移点实际上会远离原点,上述逻辑通常能覆盖,
            // 但极端锐角可能导致dist过大。此处做简单截断保护是不够的,
            // 但针对一般草地形状,此逻辑可用。
            result.add(new Point(pCurr.x + bisector.x * dist, pCurr.y + bisector.y * dist));
        }
        return result;
    }
    /**
     * 耳切法分割多边形
     */
    private static List<List<Point>> triangulatePolygon(List<Point> poly) {
        List<List<Point>> triangles = new ArrayList<>();
        List<Point> remaining = new ArrayList<>(poly);
        int maxIter = remaining.size() * 3;
        int iter = 0;
        while (remaining.size() > 3 && iter++ < maxIter) {
            int n = remaining.size();
            boolean earFound = false;
            for (int i = 0; i < n; i++) {
                Point prev = remaining.get((i - 1 + n) % n);
                Point curr = remaining.get(i);
                Point next = remaining.get((i + 1) % n);
                if (isConvex(prev, curr, next)) {
                    boolean hasPoint = false;
                    for (int j = 0; j < n; j++) {
                        if (j == i || j == (i - 1 + n) % n || j == (i + 1) % n) continue;
                        if (isPointInTriangle(remaining.get(j), prev, curr, next)) {
                            hasPoint = true;
                            break;
                        }
                    }
                    if (!hasPoint) {
                        List<Point> tri = new ArrayList<>();
                        tri.add(prev); tri.add(curr); tri.add(next);
                        triangles.add(tri);
                        remaining.remove(i);
                        earFound = true;
                        break;
                    }
                }
            }
            if (!earFound) break;
        }
        if (remaining.size() == 3) {
            triangles.add(remaining);
        }
        return triangles;
    }
    private static double calculatePolygonHeight(List<Point> poly, double angle) {
        double minY = Double.MAX_VALUE;
        double maxY = -Double.MAX_VALUE;
    private static double calculateHeightAtAngle(List<Point> poly, double angle) {
        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
        for (Point p : poly) {
            Point r = rotatePoint(p, angle);
            minY = Math.min(minY, r.y);
            maxY = Math.max(maxY, r.y);
            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);
            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);
        double sin = Math.sin(angle);
        double cos = Math.cos(angle), sin = Math.sin(angle);
        return new Point(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
    }
    private static boolean isConvex(Point a, Point b, Point c) {
        return (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x) >= 0;
    }
    private static boolean isPointInTriangle(Point p, Point a, Point b, Point c) {
        double areaABC = Math.abs((a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y))/2.0);
        double areaPBC = Math.abs((p.x*(b.y-c.y) + b.x*(c.y-p.y) + c.x*(p.y-b.y))/2.0);
        double areaPAC = Math.abs((a.x*(p.y-c.y) + p.x*(c.y-a.y) + c.x*(a.y-p.y))/2.0);
        double areaPAB = Math.abs((a.x*(b.y-p.y) + b.x*(p.y-a.y) + p.x*(a.y-b.y))/2.0);
        return Math.abs(areaABC - (areaPBC + areaPAC + areaPAB)) < 1e-6;
    }
    private static List<Point> parseCoordinates(String coordinates) {
        List<Point> points = new ArrayList<>();
        String cleanStr = coordinates.replaceAll("[()\\[\\]{}]", "").trim();
        String[] pairs = cleanStr.split(";");
        for (String pair : pairs) {
            pair = pair.trim();
            if (pair.isEmpty()) continue;
            String[] xy = pair.split(",");
            if (xy.length == 2) {
                points.add(new Point(Double.parseDouble(xy[0].trim()), Double.parseDouble(xy[1].trim())));
            }
        }
        return points;
    }
    private static void ensureCounterClockwise(List<Point> points) {
        double sum = 0;
        for (int i = 0; i < points.size(); i++) {
            Point p1 = points.get(i);
            Point p2 = points.get((i + 1) % points.size());
            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);
        }
        if (sum > 0) Collections.reverse(points);
    }
    
    private static double distance(Point p1, Point p2) {
        return Math.hypot(p1.x - p2.x, p1.y - p2.y);
    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 String toString() { return String.format("%.2f,%.2f", x, y); }
        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Point)) return false;
            Point p = (Point) o;
            return Math.abs(x - p.x) < 1e-4 && Math.abs(y - p.y) < 1e-4;
        }
    }
    public static class PathSegment {
        public Point start;
        public Point end;
        public Point start, end;
        public boolean isMowing;
        public PathSegment(Point start, Point end, boolean isMowing) {
            this.start = start;
            this.end = end;
            this.isMowing = isMowing;
        }
        @Override
        public String toString() {
            return String.format("[%s -> %s, 割草:%b]", start, end, isMowing);
        }
        public PathSegment(Point s, Point e, boolean m) { this.start = s; this.end = e; this.isMowing = m; }
    }
}
src/zhangaiwu/AddDikuai.java
@@ -24,6 +24,9 @@
import dikuai.Gecaoanquanjuli;
import bianjie.Bianjieyouhuatoxy;
import lujing.Lunjingguihua;
import lujing.Qufenxingzhuang;
import lujing.AoxinglujingNoObstacle;
import lujing.YixinglujingNoObstacle;
import set.Setsys;
import ui.UIConfig;
import zhuye.MowerLocationData;
@@ -1345,15 +1348,34 @@
            showStep(2);
            return;
        }
        Dikuai dikuai = getOrCreatePendingDikuai();
        // 从步骤2的边界坐标文本域获取边界坐标
        String boundaryCoords = null;
        if (boundaryXYTextArea != null) {
            String boundaryText = boundaryXYTextArea.getText();
            if (boundaryText != null && !boundaryText.trim().isEmpty() && !boundaryText.startsWith("ERROR")) {
                boundaryCoords = boundaryText.trim();
            }
        }
        // 如果文本域中没有,尝试从dikuaiData获取
        if (boundaryCoords == null || boundaryCoords.isEmpty()) {
            boundaryCoords = normalizeCoordinateValue(dikuaiData.get("optimizedBoundaryXY"));
        }
        // 如果还是没有,尝试从Dikuai对象获取
        if (boundaryCoords == null || boundaryCoords.isEmpty()) {
            Dikuai dikuai = getOrCreatePendingDikuai();
        if (dikuai != null) {
            boundaryCoords = normalizeCoordinateValue(dikuai.getBoundaryCoordinates());
        }
        if (boundaryCoords == null) {
        }
        // 如果还是没有,从dikuaiData获取boundaryCoordinates
        if (boundaryCoords == null || boundaryCoords.isEmpty()) {
            boundaryCoords = normalizeCoordinateValue(dikuaiData.get("boundaryCoordinates"));
        }
        if (boundaryCoords == null) {
        if (boundaryCoords == null || boundaryCoords.isEmpty()) {
            JOptionPane.showMessageDialog(this, "未找到有效的地块边界坐标,无法生成路径", "提示", JOptionPane.WARNING_MESSAGE);
            dikuaiData.remove("plannedPath");
            showPathGenerationMessage("未找到有效的地块边界坐标,无法生成路径。", false);
@@ -1417,19 +1439,48 @@
            }
        }
        
        // 格式化割草宽度和安全距离(单位:米,保留3位小数)
        String widthMetersStr = String.format(Locale.US, "%.3f", widthMeters);
        String safetyDistanceMetersStr = Double.isNaN(safetyDistanceMeters) ? null : String.format(Locale.US, "%.3f", safetyDistanceMeters);
        String plannerMode = resolvePlannerMode(patternDisplay);
        // 如果没有安全距离,使用默认值
        if (safetyDistanceMetersStr == null) {
            double defaultSafetyDistance = widthMeters / 2.0 + 0.2;
            safetyDistanceMetersStr = String.format(Locale.US, "%.3f", defaultSafetyDistance);
        }
        try {
            // 使用与路径规划页面相同的方法:Lunjingguihua.generatePathFromStrings
            String plannedPath = Lunjingguihua.generatePathFromStrings(
            // 1. 调用Qufenxingzhuang中的judgeGrassType方法计算地块边界的形状
            Qufenxingzhuang shapeJudger = new Qufenxingzhuang();
            int grassType = shapeJudger.judgeGrassType(boundaryCoords);
            // grassType: 0=无法判断, 1=凸形, 2=异形
            String plannedPath = null;
            // 2. 根据计算后的结果决定调用哪个方法生成割草路径
            if (grassType == 1) {
                // 凸形地块 -> 调用AoxinglujingNoObstacle类中的方法
                List<AoxinglujingNoObstacle.PathSegment> segments =
                    AoxinglujingNoObstacle.planPath(boundaryCoords, widthMetersStr, safetyDistanceMetersStr);
                plannedPath = formatAoxingPathSegments(segments);
            } else if (grassType == 2) {
                // 异形地块 -> 调用YixinglujingNoObstacle中的方法
                List<YixinglujingNoObstacle.PathSegment> segments =
                    YixinglujingNoObstacle.planPath(boundaryCoords, widthMetersStr, safetyDistanceMetersStr);
                plannedPath = formatYixingPathSegments(segments);
            } else {
                // 无法判断地块类型,使用默认方法作为后备
                JOptionPane.showMessageDialog(this, "无法判断地块类型,使用默认路径生成方法",
                    "提示", JOptionPane.WARNING_MESSAGE);
                String plannerMode = resolvePlannerMode(patternDisplay);
                plannedPath = Lunjingguihua.generatePathFromStrings(
                boundaryCoords,
                obstacleCoords != null ? obstacleCoords : "",
                widthMetersStr,
                safetyDistanceMetersStr,
                plannerMode
            );
            }
            
            if (!isMeaningfulValue(plannedPath)) {
                JOptionPane.showMessageDialog(this, "生成割草路径失败: 生成结果为空", "错误", JOptionPane.ERROR_MESSAGE);
@@ -1464,6 +1515,96 @@
        }
    }
    /**
     * 格式化 AoxinglujingNoObstacle.PathSegment 列表为坐标字符串
     */
    private String formatAoxingPathSegments(List<AoxinglujingNoObstacle.PathSegment> segments) {
        if (segments == null || segments.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        AoxinglujingNoObstacle.Point last = null;
        for (AoxinglujingNoObstacle.PathSegment segment : segments) {
            // 只添加割草工作段,跳过过渡段
            if (segment.isMowing) {
                // 如果起点与上一个终点不同,添加起点
                if (last == null || !equalsAoxingPoint(last, segment.start)) {
                    appendAoxingPoint(sb, segment.start);
                }
                // 添加终点
                appendAoxingPoint(sb, segment.end);
                last = segment.end;
            }
        }
        return sb.toString();
    }
    /**
     * 格式化 YixinglujingNoObstacle.PathSegment 列表为坐标字符串
     */
    private String formatYixingPathSegments(List<YixinglujingNoObstacle.PathSegment> segments) {
        if (segments == null || segments.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        YixinglujingNoObstacle.Point last = null;
        for (YixinglujingNoObstacle.PathSegment segment : segments) {
            // 只添加割草工作段,跳过过渡段
            if (segment.isMowing) {
                // 如果起点与上一个终点不同,添加起点
                if (last == null || !equalsYixingPoint(last, segment.start)) {
                    appendYixingPoint(sb, segment.start);
                }
                // 添加终点
                appendYixingPoint(sb, segment.end);
                last = segment.end;
            }
        }
        return sb.toString();
    }
    /**
     * 比较两个 AoxinglujingNoObstacle.Point 是否相同(使用小的容差)
     */
    private boolean equalsAoxingPoint(AoxinglujingNoObstacle.Point p1, AoxinglujingNoObstacle.Point p2) {
        if (p1 == null || p2 == null) {
            return p1 == p2;
        }
        double tolerance = 1e-6;
        return Math.abs(p1.x - p2.x) < tolerance && Math.abs(p1.y - p2.y) < tolerance;
    }
    /**
     * 添加 AoxinglujingNoObstacle.Point 到字符串构建器
     */
    private void appendAoxingPoint(StringBuilder sb, AoxinglujingNoObstacle.Point point) {
        if (sb.length() > 0) {
            sb.append(";");
        }
        sb.append(String.format(Locale.US, "%.6f,%.6f", point.x, point.y));
    }
    /**
     * 比较两个 YixinglujingNoObstacle.Point 是否相同(使用小的容差)
     */
    private boolean equalsYixingPoint(YixinglujingNoObstacle.Point p1, YixinglujingNoObstacle.Point p2) {
        if (p1 == null || p2 == null) {
            return p1 == p2;
        }
        double tolerance = 1e-6;
        return Math.abs(p1.x - p2.x) < tolerance && Math.abs(p1.y - p2.y) < tolerance;
    }
    /**
     * 添加 YixinglujingNoObstacle.Point 到字符串构建器
     */
    private void appendYixingPoint(StringBuilder sb, YixinglujingNoObstacle.Point point) {
        if (sb.length() > 0) {
            sb.append(";");
        }
        sb.append(String.format(Locale.US, "%.6f,%.6f", point.x, point.y));
    }
    private void previewMowingPath() {
        if (!hasGeneratedPath()) {
            showPathGenerationMessage("请先生成割草路径后再预览。", false);
src/zhuye/Shouye.java
@@ -577,9 +577,9 @@
                if (setsys.isManualBoundaryDrawingMode()) {
                    setsys.setManualBoundaryDrawingMode(false);
                    setsys.updateProperty("manualBoundaryDrawingMode", "false");
                    // 清空手动绘制的边界点
                    // 关闭MapRenderer中的手动绘制边界模式(这会清除鼠标位置和边界点)
                    if (mapRenderer != null) {
                        mapRenderer.clearManualBoundaryPoints();
                        mapRenderer.setManualBoundaryDrawingMode(false);
                    }
                    modeChanged = true;
                }