张世豪
3 天以前 f38ba0a0bf5cbe96c9300247923f6979a5059529
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
package zhuye;
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.FontMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.math.BigDecimal;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.io.File;
import set.Setsys;
import gecaoji.Device;
import gecaoji.Gecaoji;
import gecaoji.GecaojiMeg;
import gecaoji.gecaolunjing;
import gecaoji.lujingdraw;
import dikuai.Dikuaiguanli;
import dikuai.Dikuai;
import zhangaiwu.Obstacledraw;
import zhangaiwu.Obstacledge;
import zhangaiwu.yulanzhangaiwu;
import yaokong.Control03;
import bianjie.shudongdraw;
 
/**
 * 地图渲染器 - 负责坐标系绘制、视图变换等功能
 */
public class MapRenderer {
    // 视图变换参数
    private static final double DEFAULT_SCALE = 20.0; // 默认缩放比例
    private double scale = DEFAULT_SCALE;
    private double translateX = 0.0;
    private double translateY = 0.0;
    private Point lastDragPoint;
    private static final double MIN_SCALE = 0.05d;
    private static final double MAX_SCALE = 50.0d;
    private static final double SCALE_EPSILON = 1e-6d;
    private static final String MAP_SCALE_PROPERTY = "mapScale"; // 属性文件中的键名
    
    // 主题颜色
    private final Color THEME_COLOR = new Color(46, 139, 87);
    private final Color BACKGROUND_COLOR = new Color(250, 250, 250);
    private static final Color GRASS_FILL_COLOR = new Color(144, 238, 144, 120);
    private static final Color GRASS_BORDER_COLOR = new Color(60, 179, 113);
    private static final Color BOUNDARY_POINT_COLOR = new Color(128, 0, 128);
    private static final Color OBSTACLE_POINT_COLOR = new Color(255, 140, 0); // 橙色,用于区分障碍物点
    private static final Color CIRCLE_SAMPLE_COLOR = new Color(220, 20, 60, 230);
    private static final double CIRCLE_SAMPLE_SIZE = 0.54d;
    private static final double BOUNDARY_POINT_MERGE_THRESHOLD = 0.05;
    private static final double BOUNDARY_CONTAINS_TOLERANCE = 0.05;
    private static final double PREVIEW_BOUNDARY_MARKER_SCALE = 0.25d;
    
    // 组件引用
    private JPanel visualizationPanel;
    private List<Point2D.Double> currentBoundary;
    private Rectangle2D.Double boundaryBounds;
    private Path2D.Double currentBoundaryPath;
    private List<Point2D.Double> currentPlannedPath;
    private Rectangle2D.Double plannedPathBounds;
    private List<Obstacledge.Obstacle> currentObstacles;
    private Rectangle2D.Double obstacleBounds;
    private String selectedObstacleName;
    private String currentObstacleLandNumber;
    private String boundaryName;
    private boolean boundaryPointsVisible;
    private boolean obstaclePointsVisible;
    private boolean boundaryLengthVisible = false;  // 是否显示边界距离,默认关闭
    private double boundaryPointSizeScale = 1.0d;
    private boolean previewSizingEnabled;
    private String currentBoundaryLandNumber;
    private boolean dragInProgress;
    private final Gecaoji mower;
    private final Timer mowerUpdateTimer;
    private final GecaojiMeg mowerInfoManager;
    private CircleCaptureOverlay circleCaptureOverlay;
    private final List<double[]> circleSampleMarkers = new ArrayList<>();
    private final List<Point2D.Double> realtimeMowingTrack = new ArrayList<>();
    private final List<Point2D.Double> navigationPreviewTrack = new ArrayList<>(); // 导航预览轨迹
    private final Deque<tuowei.TrailSample> idleMowerTrail = new ArrayDeque<>();
    private final List<Point2D.Double> handheldBoundaryPreview = new ArrayList<>();
    private double boundaryPreviewMarkerScale = 1.0d;
    private boolean realtimeTrackRecording;
    private String realtimeTrackLandNumber;
    private double mowerEffectiveWidthMeters;
    private double defaultMowerWidthMeters;
    private double totalLandAreaSqMeters;
    private double trackLengthMeters;
    private double completedMowingAreaSqMeters;
    private double mowingCompletionRatio;
    private long lastTrackPersistTimeMillis;
    private boolean trackDirty;
    private boolean measurementModeActive = false;  // 测量模式是否激活
    private boolean handheldBoundaryPreviewActive;
    private boolean pendingTrackBreak = true;
    private bianjie.shudongdraw manualBoundaryDrawer = new bianjie.shudongdraw();  // 手动绘制边界绘制器
    private boolean idleTrailSuppressed;
    private Path2D.Double realtimeBoundaryPathCache;
    private String realtimeBoundaryPathLand;
    private WangfanDraw returnPathDrawer;  // 往返路径绘制管理器
    private List<Point2D.Double> currentReturnPath; // 当前地块的往返路径(用于显示)
    private List<Point2D.Double> previewReturnPath; // 预览的往返路径
    private List<Point2D.Double> previewOriginalBoundary; // 预览的原始边界(紫色)
    private List<Point2D.Double> previewOptimizedBoundary; // 预览的优化后边界
    private boolean showOnlyOriginalBoundary = false; // 是否只显示原始边界
    private boolean boundaryPreviewActive; // 是否处于边界预览模式
 
    private static final double TRACK_SAMPLE_MIN_DISTANCE_METERS = 0.2d;
    private static final double TRACK_DUPLICATE_TOLERANCE_METERS = 1e-3d;
    private static final long TRACK_PERSIST_INTERVAL_MS = 5_000L;
    public static final int DEFAULT_IDLE_TRAIL_DURATION_SECONDS = 60;
    private static final double IDLE_TRAIL_SAMPLE_DISTANCE_METERS = 0.05d;
    private long idleTrailDurationMs = DEFAULT_IDLE_TRAIL_DURATION_SECONDS * 1_000L;
    private static final double ZOOM_STEP_FACTOR = 1.2d;
    
    public MapRenderer(JPanel visualizationPanel) {
        this.visualizationPanel = visualizationPanel;
        this.mower = new Gecaoji();
        this.mowerUpdateTimer = createMowerTimer();
        this.mowerInfoManager = new GecaojiMeg(visualizationPanel, mower);
        setupMouseListeners();
        // 从配置文件读取上次保存的缩放比例和视图中心坐标
        loadViewSettingsFromProperties();
    }
    
    /**
     * 从配置文件读取缩放比例和视图中心坐标
     */
    private void loadViewSettingsFromProperties() {
        // 加载缩放比例
        String scaleValue = Setsys.getPropertyValue(MAP_SCALE_PROPERTY);
        if (scaleValue != null && !scaleValue.trim().isEmpty()) {
            try {
                double savedScale = Double.parseDouble(scaleValue.trim());
                // 验证缩放比例是否在有效范围内
                if (savedScale >= MIN_SCALE && savedScale <= MAX_SCALE) {
                    scale = savedScale;
                } else {
                    scale = DEFAULT_SCALE;
                }
            } catch (NumberFormatException e) {
                // 如果解析失败,使用默认值
                scale = DEFAULT_SCALE;
            }
        } else {
            // 如果没有保存的值,使用默认值
            scale = DEFAULT_SCALE;
        }
        
        // 加载视图中心坐标
        String viewCenterXValue = Setsys.getPropertyValue("viewCenterX");
        String viewCenterYValue = Setsys.getPropertyValue("viewCenterY");
        if (viewCenterXValue != null && !viewCenterXValue.trim().isEmpty()) {
            try {
                translateX = Double.parseDouble(viewCenterXValue.trim());
            } catch (NumberFormatException e) {
                translateX = 0.0;
            }
        } else {
            translateX = 0.0;
        }
        if (viewCenterYValue != null && !viewCenterYValue.trim().isEmpty()) {
            try {
                translateY = Double.parseDouble(viewCenterYValue.trim());
            } catch (NumberFormatException e) {
                translateY = 0.0;
            }
        } else {
            translateY = 0.0;
        }
    }
    
    /**
     * 保存缩放比例到配置文件
     */
    private void saveScaleToProperties() {
        Setsys setsys = new Setsys();
        // 保留2位小数
        setsys.updateProperty(MAP_SCALE_PROPERTY, String.format("%.2f", scale));
    }
    
    /**
     * 设置鼠标监听器
     */
    private void setupMouseListeners() {
        // 鼠标滚轮缩放
        visualizationPanel.addMouseWheelListener(e -> {
            Point referencePoint = e.getPoint();
            int notches = e.getWheelRotation();
            double zoomFactor = notches < 0 ? ZOOM_STEP_FACTOR : 1 / ZOOM_STEP_FACTOR;
            zoomAtPoint(referencePoint, zoomFactor);
        });
        
        // 鼠标拖拽移动
        visualizationPanel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    resetView();
                } else {
                    dragInProgress = false;
                    lastDragPoint = e.getPoint();
                }
            }
            
            public void mouseReleased(MouseEvent e) {
                lastDragPoint = null;
                dragInProgress = false;
            }
            
            public void mouseExited(MouseEvent e) {
                // 鼠标离开面板时,清除鼠标位置显示
                if (manualBoundaryDrawer.isManualBoundaryDrawingMode()) {
                    manualBoundaryDrawer.clearMousePosition();
                    visualizationPanel.repaint();
                }
            }
 
            public void mouseClicked(MouseEvent e) {
                if (dragInProgress) {
                    dragInProgress = false;
                    return;
                }
                if (!SwingUtilities.isLeftMouseButton(e) || e.getClickCount() != 1) {
                    return;
                }
                // 优先处理手动绘制边界模式点击
                if (manualBoundaryDrawer.isManualBoundaryDrawingMode()) {
                    Point2D.Double worldPoint = screenToWorld(e.getPoint());
                    if (manualBoundaryDrawer.handleClick(worldPoint)) {
                        visualizationPanel.repaint();
                        return;
                    }
                }
                // 优先处理测量模式点击
                if (measurementModeActive && handleMeasurementClick(e.getPoint())) {
                    return;
                }
                if (handleMowerClick(e.getPoint())) {
                    return;
                }
                // 优先处理优化后边界坐标点点击(边界预览模式下)
                if (boundaryPreviewActive && handleOptimizedBoundaryPointClick(e.getPoint())) {
                    return;
                }
                // 优先处理障碍物边界点点击(如果可见)
                if (obstaclePointsVisible && handleObstaclePointClick(e.getPoint())) {
                    return;
                }
                // 然后处理地块边界点点击
                if (boundaryPointsVisible) {
                    handleBoundaryPointClick(e.getPoint());
                }
            }
        });
        
        visualizationPanel.addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e) {
                if (lastDragPoint != null && !SwingUtilities.isRightMouseButton(e)) {
                    int dx = e.getX() - lastDragPoint.x;
                    int dy = e.getY() - lastDragPoint.y;
                    
                    translateX += dx / scale;
                    translateY += dy / scale;
                    
                    lastDragPoint = e.getPoint();
                    dragInProgress = true;
                    visualizationPanel.repaint();
                }
            }
            
            public void mouseMoved(MouseEvent e) {
                // 在手动绘制边界模式时,更新鼠标位置
                if (manualBoundaryDrawer.isManualBoundaryDrawingMode()) {
                    Point2D.Double worldPoint = screenToWorld(e.getPoint());
                    manualBoundaryDrawer.updateMousePosition(worldPoint);
                    visualizationPanel.repaint();
                } else {
                    manualBoundaryDrawer.clearMousePosition();
                }
            }
        });
    }
 
    private Timer createMowerTimer() {
        Timer timer = new Timer(300, e -> {
            mower.refreshFromDevice();
            updateIdleMowerTrail();
            if (realtimeTrackRecording) {
                captureRealtimeTrackPoint();
            }
            if (visualizationPanel != null) {
                visualizationPanel.repaint();
            }
        });
        timer.setInitialDelay(0);
        timer.setRepeats(true);
        timer.start();
        return timer;
    }
 
    /**
     * 基于鼠标位置的缩放
     */
    private void zoomAtPoint(Point referencePoint, double zoomFactor) {
        if (visualizationPanel == null) {
            return;
        }
        if (referencePoint == null) {
            referencePoint = new Point(visualizationPanel.getWidth() / 2, visualizationPanel.getHeight() / 2);
        }
 
        double panelCenterX = visualizationPanel.getWidth() / 2.0;
        double panelCenterY = visualizationPanel.getHeight() / 2.0;
 
        double worldX = (referencePoint.x - panelCenterX) / scale - translateX;
        double worldY = (referencePoint.y - panelCenterY) / scale - translateY;
 
    scale *= zoomFactor;
    scale = Math.max(MIN_SCALE, Math.min(scale, MAX_SCALE)); // 限制缩放范围,允许最多缩小至原始的1/20
 
        double newWorldX = (referencePoint.x - panelCenterX) / scale - translateX;
        double newWorldY = (referencePoint.y - panelCenterY) / scale - translateY;
 
        translateX += (newWorldX - worldX);
        translateY += (newWorldY - worldY);
 
        // 保存缩放比例到配置文件
        saveScaleToProperties();
        visualizationPanel.repaint();
    }
 
    public void zoomInFromCenter() {
        zoomAtPoint(null, ZOOM_STEP_FACTOR);
    }
 
    public void zoomOutFromCenter() {
        zoomAtPoint(null, 1 / ZOOM_STEP_FACTOR);
    }
    
    public boolean canZoomIn() {
        return scale < MAX_SCALE - SCALE_EPSILON;
    }
 
    public boolean canZoomOut() {
        return scale > MIN_SCALE + SCALE_EPSILON;
    }
 
    public double getScale() {
        return scale;
    }
 
    public double getMaxScale() {
        return MAX_SCALE;
    }
 
    public double getMinScale() {
        return MIN_SCALE;
    }
    
    /**
     * 重置视图
     */
    public void resetView() {
        scale = DEFAULT_SCALE;
        translateX = 0.0;
        translateY = 0.0;
        // 保存缩放比例到配置文件
        saveScaleToProperties();
        visualizationPanel.repaint();
    }
    
    /**
     * 绘制地图内容
     */
    public void renderMap(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        
        // 保存原始变换
        AffineTransform originalTransform = g2d.getTransform();
        
        // 应用视图变换
        g2d.translate(visualizationPanel.getWidth()/2, visualizationPanel.getHeight()/2);
        g2d.scale(scale, scale);
        g2d.translate(translateX, translateY);
        
        // 绘制坐标系内容
        drawCoordinateSystem(g2d);
 
        boolean hasBoundary = currentBoundary != null && currentBoundary.size() >= 2;
        boolean hasPlannedPath = currentPlannedPath != null && currentPlannedPath.size() >= 2;
        boolean hasObstacles = currentObstacles != null && !currentObstacles.isEmpty();
 
        // 绘制地块边界(底层)
        if (hasBoundary) {
            drawCurrentBoundary(g2d);
        }
        
        // 绘制边界预览(原始边界-紫色,优化后边界)
        if (boundaryPreviewActive) {
            drawBoundaryPreview(g2d);
        }
 
        yulanzhangaiwu.renderPreview(g2d, scale);
 
        if (!circleSampleMarkers.isEmpty()) {
            drawCircleSampleMarkers(g2d, circleSampleMarkers, scale);
        }
 
        if (circleCaptureOverlay != null) {
            drawCircleCaptureOverlay(g2d, circleCaptureOverlay, scale);
        }
 
    adddikuaiyulan.drawPreview(g2d, handheldBoundaryPreview, scale, handheldBoundaryPreviewActive, boundaryPreviewMarkerScale);
 
        // 绘制手动绘制的边界
        manualBoundaryDrawer.drawBoundary(g2d, scale);
        
        // 绘制鼠标实时位置(手动绘制边界模式时)
        manualBoundaryDrawer.drawMousePosition(g2d, scale);
 
        // 绘制导航路径(中层)- 边界预览模式下不显示导航路径
        if (hasPlannedPath && !boundaryPreviewActive) {
            drawCurrentPlannedPath(g2d);
        }
 
        // 绘制障碍物(顶层,显示在地块和导航路径上方)
        if (hasObstacles) {
            Obstacledraw.drawObstacles(g2d, currentObstacles, scale, selectedObstacleName);
        }
 
        // 显示边界点(如果边界点可见,或者边界距离可见)
        if ((boundaryPointsVisible || boundaryLengthVisible) && hasBoundary) {
            // 预览模式下显示序号
            if (previewSizingEnabled) {
                drawBoundaryPointsWithNumbers(g2d, currentBoundary, scale);
            } else {
                double markerScale = boundaryPointSizeScale;
                pointandnumber.drawBoundaryPoints(
                    g2d,
                    currentBoundary,
                    scale,
                    BOUNDARY_POINT_MERGE_THRESHOLD,
                    BOUNDARY_POINT_COLOR,
                    markerScale
                );
            }
        }
        
        // 绘制障碍物坐标点(带序号)
        if (obstaclePointsVisible && hasObstacles) {
            drawObstaclePointsWithNumbers(g2d, currentObstacles, scale);
        }
 
        if (shouldRenderIdleTrail()) {
            tuowei.draw(g2d, idleMowerTrail, scale);
        }
 
        if (!realtimeMowingTrack.isEmpty()) {
            drawRealtimeMowingCoverage(g2d);
        }
        
        // 绘制导航预览已割区域
        if (!navigationPreviewTrack.isEmpty()) {
            drawNavigationPreviewCoverage(g2d);
        }
 
        // 先画往返路径(线+点),保证割草机图标在其上方
        if (returnPathDrawer != null && returnPathDrawer.isActive()) {
            returnPathDrawer.draw(g2d, scale);
        } else if (previewReturnPath != null && !previewReturnPath.isEmpty()) {
            // 绘制预览的往返路径(铁线路图风格)
            WangfanDraw.drawRailwayPath(g2d, previewReturnPath, scale);
        } else if (currentReturnPath != null && !currentReturnPath.isEmpty()) {
            // 绘制保存的往返路径(铁线路图风格)
            WangfanDraw.drawRailwayPath(g2d, currentReturnPath, scale);
        }
 
        drawMower(g2d);
        
        // 绘制导航预览速度(如果正在导航预览)
        if (navigationPreviewSpeed > 0 && mower != null && mower.hasValidPosition()) {
            drawNavigationPreviewSpeed(g2d, scale);
        }
        
        // 绘制测量模式(如果激活)
        if (measurementModeActive) {
            drawMeasurementMode(g2d, scale);
        }
        
        // 保存当前变换(包含视图变换)用于坐标转换
        AffineTransform currentTransformForLength = g2d.getTransform();
        
        // 恢复原始变换
        g2d.setTransform(originalTransform);
        
        // 绘制边界长度(如果启用)- 在恢复原始变换后绘制
        if (boundaryLengthVisible && hasBoundary) {
            bianjie.BoundaryLengthDrawer.drawBoundaryLengths(g2d, currentBoundary, scale, 
                visualizationPanel.getWidth(), visualizationPanel.getHeight(), translateX, translateY);
        }
        
        // 绘制视图信息
        drawViewInfo(g2d);
    }
    
    /**
     * 绘制坐标系
     */
    private void drawCoordinateSystem(Graphics2D g2d) {
        // 绘制原点 - 红色实心小圆圈
        g2d.setColor(Color.RED);
        g2d.fill(new Ellipse2D.Double(-0.5d, -0.5d, 1d, 1d));
    }
    
    
    
    /**
     * 绘制割草机
     */
    private void drawMower(Graphics2D g2d) {
        mower.draw(g2d, scale);
    }
    
    /**
     * 绘制导航预览速度(在割草机图标上方)
     */
    private void drawNavigationPreviewSpeed(Graphics2D g2d, double scale) {
        if (mower == null || !mower.hasValidPosition()) {
            return;
        }
        
        Point2D.Double mowerPos = mower.getPosition();
        if (mowerPos == null) {
            return;
        }
        
        // 将速度从米/秒转换为KM/h
        double speedKmh = navigationPreviewSpeed * 3.6;
        String speedText = String.format("%.1f km/h", speedKmh);
        
        // 保存原始变换
        AffineTransform originalTransform = g2d.getTransform();
        
        // 将世界坐标转换为屏幕坐标
        Point2D.Double screenPos = worldToScreen(mowerPos);
        
        // 恢复原始变换以绘制文字(固定大小,不随缩放变化)
        g2d.setTransform(new AffineTransform());
        
        // 设置字体(与缩放文字大小一致,11号字体)
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 11);
        g2d.setFont(labelFont);
        FontMetrics metrics = g2d.getFontMetrics(labelFont);
        
        // 计算文字位置(在割草机图标上方)
        int textWidth = metrics.stringWidth(speedText);
        int textHeight = metrics.getHeight();
        int textX = (int)Math.round(screenPos.x - textWidth / 2.0);
        // 在割草机图标上方,留出一定间距
        // 图标在世界坐标系中的大小约为 48 * 0.8 / scale 米
        // 转换为屏幕像素:图标高度(像素)= (48 * 0.8 / scale) * scale = 48 * 0.8 = 38.4 像素
        double iconSizePixels = 48.0 * 0.8; // 图标在屏幕上的大小(像素)
        int spacing = 8; // 间距(像素)
        int textY = (int)Math.round(screenPos.y - iconSizePixels / 2.0 - spacing - textHeight);
        
        // 绘制文字背景(半透明白色,增强可读性)
        g2d.setColor(new Color(255, 255, 255, 200));
        g2d.fillRoundRect(textX - 4, textY - metrics.getAscent() - 2, textWidth + 8, textHeight + 4, 4, 4);
        
        // 绘制文字
        g2d.setColor(new Color(46, 139, 87)); // 使用主题绿色
        g2d.drawString(speedText, textX, textY);
        
        // 恢复变换
        g2d.setTransform(originalTransform);
    }
 
    private void drawRealtimeMowingCoverage(Graphics2D g2d) {
        if (realtimeMowingTrack == null || realtimeMowingTrack.size() < 2) {
            return;
        }
 
        Path2D.Double boundaryPath = getRealtimeBoundaryPath();
        double effectiveWidth = getEffectiveMowerWidthMeters();
        gecaolunjing.draw(g2d, realtimeMowingTrack, effectiveWidth, boundaryPath);
    }
    
    /**
     * 绘制导航预览已割区域
     */
    private void drawNavigationPreviewCoverage(Graphics2D g2d) {
        if (navigationPreviewTrack == null || navigationPreviewTrack.size() < 2) {
            return;
        }
        
        Path2D.Double boundaryPath = currentBoundaryPath;
        // 获取导航预览的割草宽度(从daohangyulan获取)
        double previewWidth = getNavigationPreviewWidth();
        if (previewWidth <= 0) {
            previewWidth = 0.5; // 默认50厘米
        }
        gecaolunjing.draw(g2d, navigationPreviewTrack, previewWidth, boundaryPath);
    }
    
    /**
     * 设置导航预览轨迹
     */
    public void setNavigationPreviewTrack(List<Point2D.Double> track) {
        if (track == null) {
            navigationPreviewTrack.clear();
        } else {
            navigationPreviewTrack.clear();
            navigationPreviewTrack.addAll(track);
        }
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 添加导航预览轨迹点
     */
    public void addNavigationPreviewTrackPoint(Point2D.Double point) {
        if (point != null && Double.isFinite(point.x) && Double.isFinite(point.y)) {
            navigationPreviewTrack.add(new Point2D.Double(point.x, point.y));
            if (visualizationPanel != null) {
                visualizationPanel.repaint();
            }
        }
    }
    
    /**
     * 清除导航预览轨迹
     */
    public void clearNavigationPreviewTrack() {
        navigationPreviewTrack.clear();
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    private double navigationPreviewWidth = 0.5; // 导航预览的割草宽度(米)
    private double navigationPreviewSpeed = 0.0; // 导航预览的割草机速度(米/秒)
    
    /**
     * 设置导航预览的割草宽度
     */
    public void setNavigationPreviewWidth(double widthMeters) {
        navigationPreviewWidth = widthMeters > 0 ? widthMeters : 0.5;
    }
    
    /**
     * 获取导航预览的割草宽度
     */
    private double getNavigationPreviewWidth() {
        return navigationPreviewWidth;
    }
    
    /**
     * 设置导航预览的割草机速度(米/秒)
     */
    public void setNavigationPreviewSpeed(double speedMetersPerSecond) {
        navigationPreviewSpeed = speedMetersPerSecond >= 0 ? speedMetersPerSecond : 0.0;
    }
    
    /**
     * 获取导航预览的割草机速度(米/秒)
     */
    private double getNavigationPreviewSpeed() {
        return navigationPreviewSpeed;
    }
 
    private Path2D.Double getRealtimeBoundaryPath() {
        if (realtimeTrackLandNumber == null) {
            return null;
        }
 
        if (currentBoundaryLandNumber != null && realtimeTrackLandNumber.equals(currentBoundaryLandNumber)) {
            if (currentBoundaryPath == null) {
                currentBoundaryPath = buildBoundaryPath(currentBoundary);
            }
            return currentBoundaryPath;
        }
 
        if (realtimeBoundaryPathCache != null && realtimeTrackLandNumber.equals(realtimeBoundaryPathLand)) {
            return realtimeBoundaryPathCache;
        }
 
        Dikuai dikuai = Dikuai.getDikuai(realtimeTrackLandNumber);
        if (dikuai == null) {
            realtimeBoundaryPathCache = null;
            realtimeBoundaryPathLand = null;
            return null;
        }
 
        String normalized = normalizeValue(dikuai.getBoundaryCoordinates());
        if (normalized == null) {
            realtimeBoundaryPathCache = null;
            realtimeBoundaryPathLand = null;
            return null;
        }
 
        List<Point2D.Double> parsed = parseBoundary(normalized);
        if (parsed.size() < 3) {
            realtimeBoundaryPathCache = null;
            realtimeBoundaryPathLand = null;
            return null;
        }
 
        realtimeBoundaryPathCache = buildBoundaryPath(parsed);
        realtimeBoundaryPathLand = realtimeTrackLandNumber;
        return realtimeBoundaryPathCache;
    }
 
    private boolean shouldRenderIdleTrail() {
        return !idleTrailSuppressed
            && !realtimeTrackRecording
            && !handheldBoundaryPreviewActive
            && idleMowerTrail.size() >= 2;
    }
 
    private void captureRealtimeTrackPoint() {
        if (!realtimeTrackRecording) {
            return;
        }
        if (realtimeTrackLandNumber == null || visualizationPanel == null) {
            pendingTrackBreak = true;
            return;
        }
        Device device = Device.getGecaoji();
        if (device == null) {
            pendingTrackBreak = true;
            return;
        }
 
        String fixQuality = device.getPositioningStatus();
        if (!isHighPrecisionFix(fixQuality)) {
            pendingTrackBreak = true;
            return;
        }
        Point2D.Double position = mower.getPosition();
        if (position == null || !Double.isFinite(position.x) || !Double.isFinite(position.y)) {
            pendingTrackBreak = true;
            return;
        }
 
        if (!isPointInsideActiveBoundary(position)) {
            pendingTrackBreak = true;
            return;
        }
 
        Point2D.Double candidate = new Point2D.Double(position.x, position.y);
        Point2D.Double lastPoint = realtimeMowingTrack.isEmpty() ? null : realtimeMowingTrack.get(realtimeMowingTrack.size() - 1);
        double distance = Double.NaN;
        if (lastPoint != null) {
            double dx = candidate.x - lastPoint.x;
            double dy = candidate.y - lastPoint.y;
            distance = Math.hypot(dx, dy);
            if (distance <= TRACK_DUPLICATE_TOLERANCE_METERS) {
                return;
            }
            if (distance < TRACK_SAMPLE_MIN_DISTANCE_METERS) {
                return;
            }
        }
 
        realtimeMowingTrack.add(candidate);
        if (!pendingTrackBreak && lastPoint != null && Double.isFinite(distance)) {
            trackLengthMeters += distance;
        }
 
        updateCompletionMetrics();
        trackDirty = true;
        maybePersistRealtimeTrack(false);
    pendingTrackBreak = false;
    }
 
    private void updateIdleMowerTrail() {
        long now = System.currentTimeMillis();
        pruneIdleMowerTrail(now);
 
        if (idleTrailSuppressed || realtimeTrackRecording) {
            if (!idleMowerTrail.isEmpty()) {
                clearIdleMowerTrail();
            }
            return;
        }
 
        Device device = Device.getGecaoji();
        if (device == null) {
            return;
        }
        // 使用更宽松的定位状态判断,允许状态1和4显示拖尾
        if (!isValidFixForTrail(device.getPositioningStatus())) {
            return;
        }
 
        Point2D.Double position = mower.getPosition();
        if (position == null || !Double.isFinite(position.x) || !Double.isFinite(position.y)) {
            return;
        }
 
        tuowei.TrailSample lastSample = idleMowerTrail.peekLast();
        if (lastSample != null) {
            Point2D.Double lastPoint = lastSample.getPoint();
            double dx = position.x - lastPoint.x;
            double dy = position.y - lastPoint.y;
            if (Math.hypot(dx, dy) < IDLE_TRAIL_SAMPLE_DISTANCE_METERS) {
                return;
            }
        }
 
        idleMowerTrail.addLast(new tuowei.TrailSample(now, new Point2D.Double(position.x, position.y)));
        pruneIdleMowerTrail(now);
    }
    
    /**
     * 强制更新拖尾(用于收到$GNGGA数据时立即更新)
     * 这个方法会刷新mower位置并立即添加到拖尾
     */
    public void forceUpdateIdleMowerTrail() {
        long now = System.currentTimeMillis();
        pruneIdleMowerTrail(now);
 
        if (idleTrailSuppressed || realtimeTrackRecording) {
            if (!idleMowerTrail.isEmpty()) {
                clearIdleMowerTrail();
            }
            return;
        }
 
        Device device = Device.getGecaoji();
        if (device == null) {
            return;
        }
        // 使用更宽松的定位状态判断,允许状态1和4显示拖尾
        if (!isValidFixForTrail(device.getPositioningStatus())) {
            return;
        }
 
        // 刷新mower位置,使用最新的Device数据
        mower.refreshFromDevice();
        Point2D.Double position = mower.getPosition();
        if (position == null || !Double.isFinite(position.x) || !Double.isFinite(position.y)) {
            return;
        }
 
        tuowei.TrailSample lastSample = idleMowerTrail.peekLast();
        if (lastSample != null) {
            Point2D.Double lastPoint = lastSample.getPoint();
            double dx = position.x - lastPoint.x;
            double dy = position.y - lastPoint.y;
            if (Math.hypot(dx, dy) < IDLE_TRAIL_SAMPLE_DISTANCE_METERS) {
                return;
            }
        }
 
        idleMowerTrail.addLast(new tuowei.TrailSample(now, new Point2D.Double(position.x, position.y)));
        pruneIdleMowerTrail(now);
        
        // 立即重绘,确保拖尾及时显示
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
 
    private void pruneIdleMowerTrail(long now) {
        if (idleMowerTrail.isEmpty()) {
            return;
        }
    long cutoff = now - idleTrailDurationMs;
        boolean modified = false;
        while (!idleMowerTrail.isEmpty() && idleMowerTrail.peekFirst().getTimestamp() < cutoff) {
            idleMowerTrail.removeFirst();
            modified = true;
        }
        if (modified && visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
 
    private void clearIdleMowerTrail() {
        if (idleMowerTrail.isEmpty()) {
            return;
        }
        idleMowerTrail.clear();
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
 
    private void updateCompletionMetrics() {
        double widthMeters = getEffectiveMowerWidthMeters();
        if (widthMeters > 0 && trackLengthMeters > 0) {
            completedMowingAreaSqMeters = trackLengthMeters * widthMeters;
        } else {
            completedMowingAreaSqMeters = 0.0;
        }
 
        if (totalLandAreaSqMeters > 0 && completedMowingAreaSqMeters >= 0) {
            mowingCompletionRatio = Math.max(0.0, Math.min(1.0, completedMowingAreaSqMeters / totalLandAreaSqMeters));
        } else {
            mowingCompletionRatio = 0.0;
        }
    }
 
    private void maybePersistRealtimeTrack(boolean force) {
        if (!trackDirty) {
            return;
        }
        long now = System.currentTimeMillis();
        if (!force && (now - lastTrackPersistTimeMillis) < TRACK_PERSIST_INTERVAL_MS) {
            return;
        }
        persistRealtimeTrack();
    }
 
    private void persistRealtimeTrack() {
        if (realtimeTrackLandNumber == null) {
            trackDirty = false;
            return;
        }
        String serialized = serializeRealtimeTrack();
        String storedValue = (serialized == null || serialized.isEmpty()) ? "-1" : serialized;
        boolean updated = Dikuai.updateField(realtimeTrackLandNumber, "mowingTrack", storedValue);
        if (updated) {
            Dikuai dikuai = Dikuai.getDikuai(realtimeTrackLandNumber);
            if (dikuai != null) {
                dikuai.setMowingTrack(storedValue);
            }
            Dikuai.saveToProperties();
            trackDirty = false;
            lastTrackPersistTimeMillis = System.currentTimeMillis();
        }
    }
 
    private String serializeRealtimeTrack() {
        if (realtimeMowingTrack.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (Point2D.Double point : realtimeMowingTrack) {
            if (point == null) {
                continue;
            }
            if (builder.length() > 0) {
                builder.append(';');
            }
            builder.append(formatTrackCoordinate(point.x)).append(',').append(formatTrackCoordinate(point.y));
        }
        return builder.toString();
    }
 
    private String formatTrackCoordinate(double value) {
        if (!Double.isFinite(value)) {
            return "0";
        }
        return String.format(Locale.US, "%.3f", value);
    }
 
    private double getEffectiveMowerWidthMeters() {
        if (mowerEffectiveWidthMeters > 0) {
            return mowerEffectiveWidthMeters;
        }
        if (defaultMowerWidthMeters > 0) {
            return defaultMowerWidthMeters;
        }
        return 0.0;
    }
 
    public void applyLandMetadata(Dikuai dikuai) {
        String landNumber = normalizeValue(dikuai != null ? dikuai.getLandNumber() : null);
        totalLandAreaSqMeters = parseLandAreaSqMeters(dikuai != null ? dikuai.getLandArea() : null);
        defaultMowerWidthMeters = parseMowerWidthMeters(dikuai != null ? dikuai.getMowingWidth() : null);
 
        // 若当前未录制或切换地块,则更新有效割草宽度
        if (!realtimeTrackRecording || !equalsLand(landNumber, realtimeTrackLandNumber)) {
            mowerEffectiveWidthMeters = defaultMowerWidthMeters;
        }
 
        // 加载往返路径
        String returnPathStr = dikuai != null ? dikuai.getReturnPathCoordinates() : null;
        if (returnPathStr != null && !returnPathStr.isEmpty() && !"-1".equals(returnPathStr)) {
            currentReturnPath = lujingdraw.parsePlannedPath(returnPathStr);
        } else {
            currentReturnPath = null;
        }
 
        loadRealtimeTrack(landNumber, dikuai != null ? dikuai.getMowingTrack() : null);
        visualizationPanel.repaint();
    }
 
    public void startRealtimeTrackRecording(String landNumber, double widthMeters) {
        String normalizedLand = normalizeValue(landNumber);
        if (normalizedLand == null) {
            return;
        }
 
        if (!equalsLand(normalizedLand, realtimeTrackLandNumber)) {
            Dikuai dikuai = Dikuai.getDikuai(normalizedLand);
            totalLandAreaSqMeters = parseLandAreaSqMeters(dikuai != null ? dikuai.getLandArea() : null);
            defaultMowerWidthMeters = parseMowerWidthMeters(dikuai != null ? dikuai.getMowingWidth() : null);
            loadRealtimeTrack(normalizedLand, dikuai != null ? dikuai.getMowingTrack() : null);
        }
 
        if (widthMeters > 0) {
            mowerEffectiveWidthMeters = widthMeters;
        } else if (mowerEffectiveWidthMeters <= 0) {
            mowerEffectiveWidthMeters = defaultMowerWidthMeters;
        }
 
        idleTrailSuppressed = true;
        clearIdleMowerTrail();
 
        realtimeTrackLandNumber = normalizedLand;
        realtimeTrackRecording = true;
        pendingTrackBreak = true;
        captureRealtimeTrackPoint();
    }
 
    public void pauseRealtimeTrackRecording() {
        realtimeTrackRecording = false;
        pendingTrackBreak = true;
        idleTrailSuppressed = false;
        maybePersistRealtimeTrack(true);
    }
 
    public void stopRealtimeTrackRecording() {
        realtimeTrackRecording = false;
        pendingTrackBreak = true;
        idleTrailSuppressed = false;
        maybePersistRealtimeTrack(true);
    }
 
    public void forceRealtimeTrackSnapshot() {
        if (!realtimeTrackRecording) {
            return;
        }
        captureRealtimeTrackPoint();
    }
 
    public void clearRealtimeTrack() {
        realtimeTrackRecording = false;
        realtimeMowingTrack.clear();
        trackLengthMeters = 0.0;
        completedMowingAreaSqMeters = 0.0;
        mowingCompletionRatio = 0.0;
        trackDirty = true;
        pendingTrackBreak = true;
        idleTrailSuppressed = false;
        maybePersistRealtimeTrack(true);
        visualizationPanel.repaint();
    }
 
    public void clearIdleTrail() {
        clearIdleMowerTrail();
    }
 
    public void setIdleTrailDurationSeconds(int seconds) {
        int sanitized = seconds;
        if (sanitized < 5 || sanitized > 600) {
            sanitized = DEFAULT_IDLE_TRAIL_DURATION_SECONDS;
        }
        idleTrailDurationMs = sanitized * 1_000L;
        pruneIdleMowerTrail(System.currentTimeMillis());
    }
 
    public int getIdleTrailDurationSeconds() {
        long seconds = idleTrailDurationMs / 1_000L;
        if (seconds <= 0L) {
            return DEFAULT_IDLE_TRAIL_DURATION_SECONDS;
        }
        if (seconds > Integer.MAX_VALUE) {
            return DEFAULT_IDLE_TRAIL_DURATION_SECONDS;
        }
        return (int) seconds;
    }
 
    public double getMowingCompletionRatio() {
        if (!isMowerInsideSelectedBoundary()) {
            return 0.0;
        }
        return mowingCompletionRatio;
    }
 
    public double getCompletedMowingAreaSqMeters() {
        if (!isMowerInsideSelectedBoundary()) {
            return 0.0;
        }
        return completedMowingAreaSqMeters;
    }
 
    public double getTotalLandAreaSqMeters() {
        return totalLandAreaSqMeters;
    }
 
    public double getTrackLengthMeters() {
        return trackLengthMeters;
    }
 
    private boolean isMowerInsideSelectedBoundary() {
        Point2D.Double position = mower.getPosition();
        if (position == null) {
            return false;
        }
        return isPointInsideActiveBoundary(position);
    }
 
    public void flushRealtimeTrack() {
        maybePersistRealtimeTrack(true);
    }
 
    private void loadRealtimeTrack(String landNumber, String trackData) {
        realtimeTrackRecording = false;
        realtimeTrackLandNumber = landNumber;
        realtimeMowingTrack.clear();
        trackLengthMeters = 0.0;
        completedMowingAreaSqMeters = 0.0;
        mowingCompletionRatio = 0.0;
        trackDirty = false;
        lastTrackPersistTimeMillis = 0L;
        pendingTrackBreak = true;
        realtimeBoundaryPathCache = null;
        realtimeBoundaryPathLand = null;
 
        String trimmed = normalizeValue(trackData);
        if (trimmed == null || trimmed.isEmpty()) {
            updateCompletionMetrics();
            return;
        }
 
        String[] segments = trimmed.split(";");
        Path2D.Double boundaryPath = getRealtimeBoundaryPath();
        Point2D.Double lastPoint = null;
        for (String segment : segments) {
            if (segment == null || segment.trim().isEmpty()) {
                continue;
            }
            String[] parts = segment.trim().split(",");
            if (parts.length < 2) {
                continue;
            }
            try {
                double x = Double.parseDouble(parts[0].trim());
                double y = Double.parseDouble(parts[1].trim());
                if (!Double.isFinite(x) || !Double.isFinite(y)) {
                    continue;
                }
                Point2D.Double current = new Point2D.Double(x, y);
                if (boundaryPath != null && !isPointInsideBoundary(current, boundaryPath)) {
                    continue;
                }
                if (lastPoint != null) {
                    double dx = current.x - lastPoint.x;
                    double dy = current.y - lastPoint.y;
                    double distance = Math.hypot(dx, dy);
                    if (distance <= TRACK_DUPLICATE_TOLERANCE_METERS) {
                        continue;
                    }
                    if (distance < TRACK_SAMPLE_MIN_DISTANCE_METERS) {
                        continue;
                    }
                    trackLengthMeters += distance;
                }
                realtimeMowingTrack.add(current);
                lastPoint = current;
            } catch (NumberFormatException ignored) {
                // 跳过异常条目
            }
        }
 
        updateCompletionMetrics();
    }
 
    private double parseLandAreaSqMeters(String raw) {
        if (raw == null) {
            return 0.0;
        }
        String trimmed = raw.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return 0.0;
        }
        try {
            double area = Double.parseDouble(trimmed);
            return area > 0 ? area : 0.0;
        } catch (NumberFormatException ex) {
            return 0.0;
        }
    }
 
    private double parseMowerWidthMeters(String raw) {
        if (raw == null) {
            return 0.0;
        }
        String sanitized = raw.trim().toLowerCase(Locale.ROOT);
        if (sanitized.isEmpty() || "-1".equals(sanitized)) {
            return 0.0;
        }
        sanitized = sanitized.replace("厘米", "cm");
        sanitized = sanitized.replace("公分", "cm");
        sanitized = sanitized.replace("米", "m");
        sanitized = sanitized.replace("cm", "");
        sanitized = sanitized.replace("m", "");
        sanitized = sanitized.trim();
        if (sanitized.isEmpty()) {
            return 0.0;
        }
        try {
            double value = Double.parseDouble(sanitized);
            if (value <= 0) {
                return 0.0;
            }
            if (value > 10) {
                return value / 100.0; // 视为厘米
            }
            return value;
        } catch (NumberFormatException ex) {
            return 0.0;
        }
    }
 
    private String normalizeValue(String value) {
        if (value == null) {
            return null;
        }
        String trimmed = value.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return null;
        }
        return trimmed;
    }
 
    private boolean equalsLand(String a, String b) {
        if (a == null && b == null) {
            return true;
        }
        if (a == null || b == null) {
            return false;
        }
        return a.equals(b);
    }
 
    private boolean handleMowerClick(Point screenPoint) {
        if (!mower.hasValidPosition()) {
            return false;
        }
        Point2D.Double mowerPosition = mower.getPosition();
        if (mowerPosition == null) {
            return false;
        }
        Point2D.Double worldPoint = screenToWorld(screenPoint);
        double radius = mower.getWorldRadius(scale);
        if (Double.isNaN(radius)) {
            return false;
        }
        double dx = worldPoint.x - mowerPosition.x;
        double dy = worldPoint.y - mowerPosition.y;
        if (dx * dx + dy * dy <= radius * radius) {
            showMowerInfo();
            return true;
        }
        return false;
    }
 
    private Point2D.Double screenToWorld(Point screenPoint) {
        double worldX = (screenPoint.x - visualizationPanel.getWidth() / 2.0) / scale - translateX;
        double worldY = (screenPoint.y - visualizationPanel.getHeight() / 2.0) / scale - translateY;
        return new Point2D.Double(worldX, worldY);
    }
    
    /**
     * 处理测量模式点击
     */
    private boolean handleMeasurementClick(Point screenPoint) {
        if (!measurementModeActive) {
            return false;
        }
        Point2D.Double worldPoint = screenToWorld(screenPoint);
        celiangmoshi.addPoint(worldPoint);
        visualizationPanel.repaint();
        return true;
    }
    
    /**
     * 设置手动绘制边界模式
     */
    public void setManualBoundaryDrawingMode(boolean active) {
        manualBoundaryDrawer.setManualBoundaryDrawingMode(active);
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 获取手动绘制的边界点列表
     */
    public List<Point2D.Double> getManualBoundaryPoints() {
        return manualBoundaryDrawer.getManualBoundaryPoints();
    }
    
    /**
     * 清空手动绘制的边界点
     */
    public void clearManualBoundaryPoints() {
        manualBoundaryDrawer.clearManualBoundaryPoints();
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 设置测量模式
     */
    public void setMeasurementMode(boolean active) {
        measurementModeActive = active;
        if (!active) {
            celiangmoshi.clear();
        }
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 触发地图重绘
     */
    public void repaint() {
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 绘制测量模式
     */
    private void drawMeasurementMode(Graphics2D g2d, double scale) {
        List<Point2D.Double> points = celiangmoshi.getPoints();
        if (points.isEmpty()) {
            return;
        }
        
        // 保存原始变换
        AffineTransform originalTransform = g2d.getTransform();
        
        // 设置测量模式颜色
        Color lineColor = new Color(255, 0, 0, 200);  // 红色半透明
        Color pointColor = new Color(255, 0, 0, 255);  // 红色
        Color textColor = new Color(33, 37, 41, 220);  // 深灰色文字
        
        // 设置线宽和点的大小(确保点和线连接)
        float lineWidth = (float)(2.0 / scale);
        // 点的大小(在世界坐标系中,米),确保点足够大以覆盖线的端点
        double pointSizeInWorld = 0.15d;  // 点的大小(米)
        double halfSize = pointSizeInWorld / 2.0;
        
        // 先绘制所有测量点(作为基础层)
        g2d.setColor(pointColor);
        for (Point2D.Double point : points) {
            // 点的中心在 point.x, point.y
            Ellipse2D.Double pointShape = new Ellipse2D.Double(
                point.x - halfSize,
                point.y - halfSize,
                pointSizeInWorld,
                pointSizeInWorld
            );
            g2d.fill(pointShape);
        }
        
        // 然后绘制连线,确保线从点的中心开始和结束,点和线连接在一起
        g2d.setColor(lineColor);
        g2d.setStroke(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        
        // 绘制连线和距离文字(显示两个相邻点连线的长度)
        for (int i = 0; i < points.size() - 1; i++) {
            Point2D.Double p1 = points.get(i);
            Point2D.Double p2 = points.get(i + 1);
            
            // 绘制连线(从第一个点的中心到第二个点的中心)
            // 使用 Path2D 确保精确绘制,保持浮点精度
            Path2D.Double linePath = new Path2D.Double();
            linePath.moveTo(p1.x, p1.y);
            linePath.lineTo(p2.x, p2.y);
            g2d.draw(linePath);
            
            // 计算距离(两个相邻点连线的长度)
            double distance = celiangmoshi.calculateDistance(p1, p2);
            String distanceText = celiangmoshi.formatDistance(distance);
            
            // 计算中点位置(用于显示文字)
            double midX = (p1.x + p2.x) / 2.0;
            double midY = (p1.y + p2.y) / 2.0;
            
            // 将世界坐标转换为屏幕坐标(用于文字显示)
            Point2D.Double worldMid = new Point2D.Double(midX, midY);
            Point2D.Double screenMid = worldToScreen(worldMid);
            
            // 恢复原始变换以绘制文字(固定大小,不随缩放变化)
            g2d.setTransform(new AffineTransform());
            
            // 设置字体(与缩放文字大小一致,11号字体)
            Font labelFont = new Font("微软雅黑", Font.PLAIN, 11);
            g2d.setFont(labelFont);
            FontMetrics metrics = g2d.getFontMetrics(labelFont);
            
            // 计算文字位置(居中显示)
            int textWidth = metrics.stringWidth(distanceText);
            int textHeight = metrics.getHeight();
            int textX = (int)Math.round(screenMid.x - textWidth / 2.0);
            int textY = (int)Math.round(screenMid.y - textHeight / 2.0) + metrics.getAscent();
            
            // 绘制文字背景(可选,用于提高可读性)
            g2d.setColor(new Color(255, 255, 255, 200));
            g2d.fillRoundRect(textX - 2, textY - metrics.getAscent() - 2, textWidth + 4, textHeight + 4, 4, 4);
            
            // 绘制文字
            g2d.setColor(textColor);
            g2d.drawString(distanceText, textX, textY);
            
            // 恢复变换
            g2d.setTransform(originalTransform);
        }
        
        // 最后再次绘制测量点(在连线之上,确保点覆盖在线的端点上,点和线连接在一起)
        g2d.setColor(pointColor);
        for (Point2D.Double point : points) {
            // 点的中心在 point.x, point.y,正好是线的端点位置
            Ellipse2D.Double pointShape = new Ellipse2D.Double(
                point.x - halfSize,
                point.y - halfSize,
                pointSizeInWorld,
                pointSizeInWorld
            );
            g2d.fill(pointShape);
        }
    }
 
    private void drawCurrentBoundary(Graphics2D g2d) {
        bianjiedrwa.drawBoundary(g2d, currentBoundary, scale, GRASS_FILL_COLOR, GRASS_BORDER_COLOR);
    }
 
    private void drawCurrentPlannedPath(Graphics2D g2d) {
        double arrowScale = previewSizingEnabled ? 0.5d : 1.0d;
        
        // 尝试获取地块信息以支持区分作业路径和移动路径,以及绘制内缩边界
        String boundaryCoords = null;
        String mowingWidth = null;
        String safetyDistance = null;
        String obstaclesCoords = null;
        String mowingPattern = null;
        
        // 从当前地块编号获取地块信息
        if (currentBoundaryLandNumber != null) {
            Dikuai landData = Dikuai.getDikuai(currentBoundaryLandNumber);
            if (landData != null) {
                boundaryCoords = landData.getBoundaryCoordinates();
                mowingWidth = landData.getMowingWidth();
                safetyDistance = landData.getMowingSafetyDistance();
                mowingPattern = landData.getMowingPattern();
                
                // 获取障碍物坐标
                try {
                    java.io.File configFile = new java.io.File("Obstacledge.properties");
                    if (configFile.exists()) {
                        Obstacledge.ConfigManager manager = new Obstacledge.ConfigManager();
                        if (manager.loadFromFile(configFile.getAbsolutePath())) {
                            Obstacledge.Plot plot = manager.getPlotById(currentBoundaryLandNumber.trim());
                            if (plot != null && plot.getObstacles() != null && !plot.getObstacles().isEmpty()) {
                                obstaclesCoords = Obstacledge.buildPlannerPayload(plot.getObstacles());
                            }
                        }
                    }
                } catch (Exception e) {
                    // 忽略障碍物加载错误
                }
            }
        }
        
        // 如果无法从地块获取边界,尝试使用当前显示的边界
        if (boundaryCoords == null || boundaryCoords.trim().isEmpty() || "-1".equals(boundaryCoords.trim())) {
            if (currentBoundary != null && !currentBoundary.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < currentBoundary.size(); i++) {
                    Point2D.Double pt = currentBoundary.get(i);
                    if (i > 0) sb.append(";");
                    sb.append(String.format(java.util.Locale.US, "%.3f,%.3f", pt.x, pt.y));
                }
                boundaryCoords = sb.toString();
            }
        }
        
        // 转换割草宽度从厘米到米(如果存在)
        if (mowingWidth != null && !mowingWidth.trim().isEmpty() && !"-1".equals(mowingWidth.trim())) {
            try {
                double widthCm = Double.parseDouble(mowingWidth.trim());
                double widthMeters = widthCm / 100.0;
                mowingWidth = String.format(java.util.Locale.US, "%.3f", widthMeters);
            } catch (NumberFormatException e) {
                // 如果已经是米为单位,保持原值
            }
        }
        
        // 转换安全距离从厘米到米(如果存在)
        if (safetyDistance != null && !safetyDistance.trim().isEmpty() && !"-1".equals(safetyDistance.trim())) {
            try {
                double distCm = Double.parseDouble(safetyDistance.trim());
                // 如果值大于100,认为是厘米,需要转换为米
                if (distCm > 100) {
                    double distMeters = distCm / 100.0;
                    safetyDistance = String.format(java.util.Locale.US, "%.3f", distMeters);
                }
            } catch (NumberFormatException e) {
                // 如果已经是米为单位,保持原值
            }
        }
        
        // 调用带地块信息的绘制方法
        lujingdraw.drawPlannedPath(g2d, currentPlannedPath, scale, arrowScale, 
                                   boundaryCoords, mowingWidth, safetyDistance, obstaclesCoords, mowingPattern);
    }
 
    private void drawCircleSampleMarkers(Graphics2D g2d, List<double[]> markers, double scale) {
        if (markers == null || markers.isEmpty()) {
            return;
        }
        
        // 保存原始变换
        AffineTransform originalTransform = g2d.getTransform();
        
        Shape markerShape;
        double half = CIRCLE_SAMPLE_SIZE / 2.0;
        g2d.setColor(CIRCLE_SAMPLE_COLOR);
        g2d.setStroke(new BasicStroke((float) (1.2f / scale), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        
        // 设置字体(与缩放文字大小一致,11号字体,不随缩放变化)
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 11);
        g2d.setFont(labelFont);
        FontMetrics metrics = g2d.getFontMetrics(labelFont);
        
        for (double[] pt : markers) {
            if (pt == null || pt.length < 2 || !Double.isFinite(pt[0]) || !Double.isFinite(pt[1])) {
                continue;
            }
            double x = pt[0];
            double y = pt[1];
            
            // 绘制点(在世界坐标系中,随缩放变化)
            markerShape = new Ellipse2D.Double(x - half, y - half, CIRCLE_SAMPLE_SIZE, CIRCLE_SAMPLE_SIZE);
            g2d.fill(markerShape);
            
            // 将世界坐标转换为屏幕坐标以绘制文字(不随缩放变化)
            Point2D.Double worldPoint = new Point2D.Double(x, y);
            Point2D.Double screenPoint = new Point2D.Double();
            originalTransform.transform(worldPoint, screenPoint);
            
            // 恢复原始变换以使用屏幕坐标绘制文字
            g2d.setTransform(new AffineTransform());
            
            String label = String.format(Locale.US, "%.2f,%.2f", x, y);
            int textWidth = metrics.stringWidth(label);
            int textHeight = metrics.getHeight();
            
            // 在屏幕坐标系中绘制文字(不随缩放变化)
            int textX = (int)(screenPoint.x - textWidth / 2.0);
            int textY = (int)(screenPoint.y - half - 0.2d) - metrics.getDescent();
            g2d.setColor(new Color(33, 37, 41, 220));
            g2d.drawString(label, textX, textY);
            
            // 恢复原始变换
            g2d.setTransform(originalTransform);
            g2d.setColor(CIRCLE_SAMPLE_COLOR);
        }
    }
 
    private void drawCircleCaptureOverlay(Graphics2D g2d, CircleCaptureOverlay overlay, double scale) {
        double diameter = overlay.radius * 2.0;
        Ellipse2D outline = new Ellipse2D.Double(
                overlay.centerX - overlay.radius,
                overlay.centerY - overlay.radius,
                diameter,
                diameter);
 
        Color fillColor = new Color(255, 152, 0, 80);
        Color borderColor = new Color(255, 87, 34, 230);
        Color centerColor = new Color(46, 139, 87, 230);
 
        g2d.setColor(fillColor);
        g2d.fill(outline);
 
        g2d.setColor(borderColor);
        g2d.setStroke(new BasicStroke((float) (1.8f / scale), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g2d.draw(outline);
 
        double markerSize = 0.18d;
        double centerMarkerSize = 0.22d;
 
        Ellipse2D centerMarker = new Ellipse2D.Double(
                overlay.centerX - centerMarkerSize / 2.0,
                overlay.centerY - centerMarkerSize / 2.0,
                centerMarkerSize,
                centerMarkerSize);
        g2d.setColor(centerColor);
        g2d.fill(centerMarker);
    }
 
    public void showCircleCaptureOverlay(double centerX, double centerY, double radius, List<double[]> samplePoints) {
        List<double[]> copies = new ArrayList<>();
        if (samplePoints != null) {
            for (double[] pt : samplePoints) {
                if (pt == null || pt.length < 2) {
                    continue;
                }
                copies.add(new double[]{pt[0], pt[1]});
            }
        }
        circleCaptureOverlay = new CircleCaptureOverlay(centerX, centerY, radius, copies);
        updateCircleSampleMarkers(samplePoints);
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
 
    public void clearCircleCaptureOverlay() {
        circleCaptureOverlay = null;
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
 
    public void updateCircleSampleMarkers(List<double[]> samplePoints) {
        circleSampleMarkers.clear();
        if (samplePoints != null) {
            for (double[] pt : samplePoints) {
                if (pt == null || pt.length < 2) {
                    continue;
                }
                double x = pt[0];
                double y = pt[1];
                if (!Double.isFinite(x) || !Double.isFinite(y)) {
                    continue;
                }
                circleSampleMarkers.add(new double[]{x, y});
            }
        }
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
 
    public void clearCircleSampleMarkers() {
        if (!circleSampleMarkers.isEmpty()) {
            circleSampleMarkers.clear();
            if (visualizationPanel != null) {
                visualizationPanel.repaint();
            }
        }
    }
 
    private static final class CircleCaptureOverlay {
        final double centerX;
        final double centerY;
        final double radius;
        final List<double[]> samplePoints;
 
        CircleCaptureOverlay(double centerX, double centerY, double radius, List<double[]> samplePoints) {
            this.centerX = centerX;
            this.centerY = centerY;
            this.radius = radius;
            this.samplePoints = samplePoints;
        }
    }
 
    public void showMowerInfo() {
        if (mowerInfoManager != null) {
            mowerInfoManager.showMowerInfo();
        }
    }
 
    /**
     * 处理障碍物边界点点击
     * @param screenPoint 屏幕坐标点
     * @return 如果处理了点击返回true,否则返回false
     */
    private boolean handleObstaclePointClick(Point screenPoint) {
        if (currentObstacles == null || currentObstacles.isEmpty() || currentObstacleLandNumber == null) {
            return false;
        }
 
        double threshold = computeSelectionThresholdPixels();
        
        // 遍历所有障碍物,找到被点击的点
        for (Obstacledge.Obstacle obstacle : currentObstacles) {
            if (obstacle == null) {
                continue;
            }
            
            List<Obstacledge.XYCoordinate> xyCoords = obstacle.getXyCoordinates();
            if (xyCoords == null || xyCoords.isEmpty()) {
                continue;
            }
            
            // 检查每个点
            for (int i = 0; i < xyCoords.size(); i++) {
                Obstacledge.XYCoordinate coord = xyCoords.get(i);
                Point2D.Double worldPoint = new Point2D.Double(coord.getX(), coord.getY());
                Point2D.Double screenPosition = worldToScreen(worldPoint);
                
                double dx = screenPosition.x - screenPoint.x;
                double dy = screenPosition.y - screenPoint.y;
                if (Math.hypot(dx, dy) <= threshold) {
                    // 找到被点击的点
                    String obstacleName = obstacle.getObstacleName();
                    String pointLabel = (i + 1) + "";
                    String message = "确定要删除障碍物 \"" + obstacleName + "\" 的第" + pointLabel + "号边界点吗?";
                    
                    int choice = JOptionPane.showConfirmDialog(
                        visualizationPanel,
                        message,
                        "删除障碍物边界点",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.WARNING_MESSAGE
                    );
                    
                    if (choice == JOptionPane.OK_OPTION) {
                        removeObstaclePoint(obstacle, i);
                    }
                    return true;
                }
            }
        }
        
        return false;
    }
 
    /**
     * 删除障碍物的指定边界点
     */
    private void removeObstaclePoint(Obstacledge.Obstacle obstacle, int pointIndex) {
        if (obstacle == null || currentObstacleLandNumber == null) {
            return;
        }
        
        List<Obstacledge.XYCoordinate> xyCoords = obstacle.getXyCoordinates();
        if (xyCoords == null || pointIndex < 0 || pointIndex >= xyCoords.size()) {
            return;
        }
        
        // 检查删除后是否还有足够的点
        Obstacledge.ObstacleShape shape = obstacle.getShape();
        int minPoints = (shape == Obstacledge.ObstacleShape.CIRCLE) ? 2 : 3;
        
        if (xyCoords.size() <= minPoints) {
            JOptionPane.showMessageDialog(
                visualizationPanel,
                "障碍物至少需要" + minPoints + "个点,无法删除",
                "提示",
                JOptionPane.INFORMATION_MESSAGE
            );
            return;
        }
        
        // 创建新的坐标列表(移除指定点)
        List<Obstacledge.XYCoordinate> updatedCoords = new ArrayList<>(xyCoords);
        updatedCoords.remove(pointIndex);
        
        // 更新障碍物坐标
        obstacle.setXyCoordinates(updatedCoords);
        
        // 保存到配置文件
        try {
            File configFile = new File("Obstacledge.properties");
            Obstacledge.ConfigManager manager = new Obstacledge.ConfigManager();
            if (configFile.exists()) {
                manager.loadFromFile(configFile.getAbsolutePath());
            }
            
            Obstacledge.Plot plot = manager.getPlotById(currentObstacleLandNumber.trim());
            if (plot != null) {
                // 移除旧障碍物并添加更新后的障碍物
                plot.removeObstacleByName(obstacle.getObstacleName());
                plot.addObstacle(obstacle);
                manager.saveToFile(configFile.getAbsolutePath());
                
                // 更新地块更新时间
                Dikuai.updateField(currentObstacleLandNumber.trim(), "updateTime", 
                    new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));
                Dikuai.saveToProperties();
                
                // 重新加载障碍物数据以刷新显示
                List<Obstacledge.Obstacle> updatedObstacles = new ArrayList<>();
                for (Obstacledge.Obstacle obs : currentObstacles) {
                    if (obs.getObstacleName().equals(obstacle.getObstacleName())) {
                        updatedObstacles.add(obstacle); // 使用更新后的障碍物
                    } else {
                        updatedObstacles.add(obs); // 保持其他障碍物不变
                    }
                }
                applyObstaclesToRenderer(updatedObstacles, currentObstacleLandNumber);
                visualizationPanel.repaint();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(
                visualizationPanel,
                "保存失败: " + ex.getMessage(),
                "错误",
                JOptionPane.ERROR_MESSAGE
            );
        }
    }
 
    private void handleBoundaryPointClick(Point screenPoint) {
        if (currentBoundary == null || currentBoundaryLandNumber == null) {
            return;
        }
        int hitIndex = findBoundaryPointIndex(screenPoint);
        if (hitIndex < 0) {
            return;
        }
 
        String pointLabel = String.valueOf(hitIndex + 1);
        int choice = JOptionPane.showConfirmDialog(
            visualizationPanel,
            "确定要删除第" + pointLabel + "号边界点吗?",
            "删除边界点",
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE
        );
 
        if (choice == JOptionPane.OK_OPTION) {
            removeBoundaryPoint(hitIndex);
        }
    }
 
    private int findBoundaryPointIndex(Point screenPoint) {
        if (currentBoundary == null || currentBoundary.size() < 2) {
            return -1;
        }
        boolean closed = isBoundaryClosed(currentBoundary);
        int effectiveCount = closed ? currentBoundary.size() - 1 : currentBoundary.size();
        if (effectiveCount <= 0) {
            return -1;
        }
 
        double threshold = computeSelectionThresholdPixels();
 
        for (int i = 0; i < effectiveCount; i++) {
            Point2D.Double worldPoint = currentBoundary.get(i);
            Point2D.Double screenPosition = worldToScreen(worldPoint);
            double dx = screenPosition.x - screenPoint.x;
            double dy = screenPosition.y - screenPoint.y;
            if (Math.hypot(dx, dy) <= threshold) {
                return i;
            }
        }
        return -1;
    }
 
    private double computeSelectionThresholdPixels() {
        double scaleFactor = Math.max(0.5, scale);
        double diameterScale = boundaryPointSizeScale * (previewSizingEnabled ? PREVIEW_BOUNDARY_MARKER_SCALE : 1.0d);
        if (!Double.isFinite(diameterScale) || diameterScale <= 0.0d) {
            diameterScale = 1.0d;
        }
        double markerDiameterWorld = Math.max(1.0, (10.0 / scaleFactor) * 0.2 * diameterScale);
        double markerDiameterPixels = markerDiameterWorld * scale;
        return Math.max(8.0, markerDiameterPixels * 1.5);
    }
 
    private Point2D.Double worldToScreen(Point2D.Double worldPoint) {
        double screenX = (worldPoint.x + translateX) * scale + visualizationPanel.getWidth() / 2.0;
        double screenY = (worldPoint.y + translateY) * scale + visualizationPanel.getHeight() / 2.0;
        return new Point2D.Double(screenX, screenY);
    }
 
    private void removeBoundaryPoint(int index) {
        if (currentBoundary == null || currentBoundary.size() < 2) {
            return;
        }
 
        List<Point2D.Double> updated = new ArrayList<>(currentBoundary);
        boolean closed = isBoundaryClosed(updated);
        int effectiveCount = closed ? updated.size() - 1 : updated.size();
        if (index < 0 || index >= effectiveCount) {
            return;
        }
 
        updated.remove(index);
 
        if (closed && updated.size() >= 2) {
            Point2D.Double first = updated.get(0);
            Point2D.Double last = updated.get(updated.size() - 1);
            if (!arePointsClose(first, last)) {
                updated.set(updated.size() - 1, new Point2D.Double(first.x, first.y));
            }
        }
 
        boolean success = persistBoundaryChanges(updated);
        if (!success) {
            return;
        }
 
        if (updated.size() < 2) {
            currentBoundary = null;
            currentBoundaryPath = null;
            boundaryBounds = null;
            boundaryPointsVisible = false;
            Dikuaiguanli.updateBoundaryPointVisibility(currentBoundaryLandNumber, false);
            visualizationPanel.repaint();
            adjustViewAfterBoundaryReset();
        } else {
            currentBoundary = updated;
            rebuildBoundaryPath();
            boundaryBounds = computeBounds(updated);
            Dikuaiguanli.updateBoundaryPointVisibility(currentBoundaryLandNumber, boundaryPointsVisible);
            visualizationPanel.repaint();
        }
        pendingTrackBreak = true;
    }
 
    private boolean persistBoundaryChanges(List<Point2D.Double> updatedBoundary) {
        if (currentBoundaryLandNumber == null) {
            return false;
        }
 
        String serialized = serializeBoundary(updatedBoundary);
        String storedValue = (serialized == null || serialized.trim().isEmpty()) ? "-1" : serialized;
 
        boolean updated = Dikuai.updateField(currentBoundaryLandNumber, "boundaryCoordinates", storedValue);
        if (!updated) {
            JOptionPane.showMessageDialog(visualizationPanel, "无法更新边界数据", "错误", JOptionPane.ERROR_MESSAGE);
            return false;
        }
 
        Dikuai.saveToProperties();
        Dikuaiguanli.notifyExternalCreation(currentBoundaryLandNumber);
        return true;
    }
 
    private String serializeBoundary(List<Point2D.Double> boundary) {
        if (boundary == null || boundary.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < boundary.size(); i++) {
            Point2D.Double point = boundary.get(i);
            builder.append(formatCoordinate(point.x))
                   .append(',')
                   .append(formatCoordinate(point.y));
            if (i < boundary.size() - 1) {
                builder.append(';');
            }
        }
        return builder.toString();
    }
 
    private String formatCoordinate(double value) {
        BigDecimal decimal = BigDecimal.valueOf(value).stripTrailingZeros();
        return decimal.toPlainString();
    }
 
    private boolean isBoundaryClosed(List<Point2D.Double> boundary) {
        if (boundary == null || boundary.size() < 2) {
            return false;
        }
        Point2D.Double first = boundary.get(0);
        Point2D.Double last = boundary.get(boundary.size() - 1);
        return arePointsClose(first, last);
    }
 
    private boolean arePointsClose(Point2D.Double a, Point2D.Double b) {
        if (a == null || b == null) {
            return false;
        }
        double dx = a.x - b.x;
        double dy = a.y - b.y;
        return Math.hypot(dx, dy) <= BOUNDARY_POINT_MERGE_THRESHOLD;
    }
 
    private boolean isHighPrecisionFix(String fixQuality) {
        if (fixQuality == null) {
            return false;
        }
        String trimmed = fixQuality.trim();
        if (trimmed.isEmpty()) {
            return false;
        }
        if ("4".equals(trimmed)) {
            return true;
        }
        try {
            double value = Double.parseDouble(trimmed);
            return Math.abs(value - 4.0d) < 1e-6;
        } catch (NumberFormatException ex) {
            return false;
        }
    }
    
    /**
     * 判断定位状态是否有效,可用于显示拖尾
     * 接受状态1(单点定位)、2(码差分)、3(无效PPS)、4(固定解)、5(浮点解)
     */
    private boolean isValidFixForTrail(String fixQuality) {
        if (fixQuality == null) {
            return false;
        }
        String trimmed = fixQuality.trim();
        if (trimmed.isEmpty()) {
            return false;
        }
        // 接受状态1,2,3,4,5(只要不是0或无效状态)
        if ("1".equals(trimmed) || "2".equals(trimmed) || "3".equals(trimmed) || 
            "4".equals(trimmed) || "5".equals(trimmed)) {
            return true;
        }
        try {
            double value = Double.parseDouble(trimmed);
            // 接受1.0, 2.0, 3.0, 4.0, 5.0(只要不是0)
            return value >= 1.0 && value <= 5.0;
        } catch (NumberFormatException ex) {
            return false;
        }
    }
 
    private boolean isPointInsideActiveBoundary(Point2D.Double point) {
        if (point == null || !Double.isFinite(point.x) || !Double.isFinite(point.y)) {
            return false;
        }
        if (realtimeTrackLandNumber == null) {
            return false;
        }
        Path2D.Double path = getRealtimeBoundaryPath();
        return isPointInsideBoundary(point, path);
    }
 
    private boolean isPointInsideBoundary(Point2D.Double point, Path2D.Double path) {
        if (point == null || path == null || !Double.isFinite(point.x) || !Double.isFinite(point.y)) {
            return false;
        }
        if (path.contains(point.x, point.y)) {
            return true;
        }
        double size = BOUNDARY_CONTAINS_TOLERANCE * 2.0;
        return path.intersects(point.x - BOUNDARY_CONTAINS_TOLERANCE, point.y - BOUNDARY_CONTAINS_TOLERANCE, size, size);
    }
 
    private void rebuildBoundaryPath() {
        currentBoundaryPath = buildBoundaryPath(currentBoundary);
    }
 
    private Path2D.Double buildBoundaryPath(List<Point2D.Double> boundary) {
        if (boundary == null || boundary.size() < 3) {
            return null;
        }
        Path2D.Double path = new Path2D.Double();
        boolean started = false;
        for (Point2D.Double point : boundary) {
            if (point == null || !Double.isFinite(point.x) || !Double.isFinite(point.y)) {
                continue;
            }
            if (!started) {
                path.moveTo(point.x, point.y);
                started = true;
            } else {
                path.lineTo(point.x, point.y);
            }
        }
        if (!started) {
            return null;
        }
        path.closePath();
        return path;
    }
 
    
    /**
     * 绘制视图信息
     */
    /**
     * 绘制障碍物坐标点(带序号)
     * 序号显示在点中心,字体大小与障碍物名称一致(11号),不随缩放变化
     */
    private void drawObstaclePointsWithNumbers(Graphics2D g2d, List<Obstacledge.Obstacle> obstacles, double scale) {
        if (obstacles == null || obstacles.isEmpty()) {
            return;
        }
        
        // 保存原始变换
        AffineTransform originalTransform = g2d.getTransform();
        
        // 设置点的大小(随缩放变化)
        double scaleFactor = Math.max(0.5, scale);
        double clampedScale = boundaryPointSizeScale * (previewSizingEnabled ? PREVIEW_BOUNDARY_MARKER_SCALE : 1.0d);
        if (!Double.isFinite(clampedScale) || clampedScale <= 0.0d) {
            clampedScale = 1.0d;
        }
        double minimumDiameter = clampedScale < 1.0 ? 0.5 : 1.0;
        double markerDiameter = Math.max(minimumDiameter, (10.0 / scaleFactor) * 0.2 * clampedScale);
        double markerRadius = markerDiameter / 2.0;
        
        // 设置字体(与障碍物名称一致,不随缩放变化)
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 11);
        g2d.setFont(labelFont);
        FontMetrics fontMetrics = g2d.getFontMetrics(labelFont);
        
        // 遍历所有障碍物
        for (Obstacledge.Obstacle obstacle : obstacles) {
            if (obstacle == null || !obstacle.isValid()) {
                continue;
            }
            
            List<Obstacledge.XYCoordinate> xyCoords = obstacle.getXyCoordinates();
            if (xyCoords == null || xyCoords.isEmpty()) {
                continue;
            }
            
            // 绘制每个点及其序号
            for (int i = 0; i < xyCoords.size(); i++) {
                Obstacledge.XYCoordinate coord = xyCoords.get(i);
                double x = coord.getX();
                double y = coord.getY();
                
                // 绘制点(在世界坐标系中,随缩放变化)
                g2d.setColor(OBSTACLE_POINT_COLOR);
                Ellipse2D.Double marker = new Ellipse2D.Double(
                    x - markerRadius, 
                    y - markerRadius, 
                    markerDiameter, 
                    markerDiameter
                );
                g2d.fill(marker);
                
                // 将世界坐标转换为屏幕坐标以绘制序号(不随缩放变化)
                Point2D.Double worldPoint = new Point2D.Double(x, y);
                Point2D.Double screenPoint = new Point2D.Double();
                originalTransform.transform(worldPoint, screenPoint);
                
                // 保存当前变换
                AffineTransform savedTransform = g2d.getTransform();
                
                // 重置变换为屏幕坐标系统
                g2d.setTransform(new AffineTransform());
                
                // 绘制序号(在屏幕坐标系中,不随缩放变化)
                String numberText = String.valueOf(i + 1);
                int textWidth = fontMetrics.stringWidth(numberText);
                int textHeight = fontMetrics.getHeight();
                
                // 在点中心绘制序号
                int textX = (int)(screenPoint.x - textWidth / 2.0);
                int textY = (int)(screenPoint.y + textHeight / 4.0);
                
                // 绘制序号文字(无背景)
                g2d.setColor(Color.BLACK);
                g2d.drawString(numberText, textX, textY);
                
                // 恢复变换
                g2d.setTransform(savedTransform);
            }
        }
        
        // 恢复原始变换
        g2d.setTransform(originalTransform);
    }
    
    /**
     * 绘制边界点(带序号)
     * 序号显示在点中心,字体大小与障碍物序号一致(11号),不随缩放变化
     */
    private void drawBoundaryPointsWithNumbers(Graphics2D g2d, List<Point2D.Double> boundary, double scale) {
        if (boundary == null || boundary.size() < 2) {
            return;
        }
        
        // 保存原始变换
        AffineTransform originalTransform = g2d.getTransform();
        
        int totalPoints = boundary.size();
        boolean closed = totalPoints > 2 && areBoundaryPointsClose(boundary.get(0), boundary.get(totalPoints - 1));
        int effectiveCount = closed ? totalPoints - 1 : totalPoints;
        if (effectiveCount <= 0) {
            return;
        }
        
        // 设置点的大小(边界线宽度的2倍)
        // 边界线宽度:3 / Math.max(0.5, scale)
        double scaleFactor = Math.max(0.5, scale);
        double boundaryLineWidth = 3.0 / scaleFactor;  // 边界线宽度
        double markerDiameter = boundaryLineWidth * 2.0;  // 边界点直径 = 边界线宽度的2倍
        double markerRadius = markerDiameter / 2.0;
        
        // 设置字体(与障碍物序号一致,不随缩放变化)
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 11);
        g2d.setFont(labelFont);
        FontMetrics fontMetrics = g2d.getFontMetrics(labelFont);
        
        // 绘制每个点及其序号
        for (int i = 0; i < effectiveCount; i++) {
            Point2D.Double point = boundary.get(i);
            double x = point.x;
            double y = point.y;
            
            // 绘制点(在世界坐标系中,随缩放变化)
            g2d.setColor(BOUNDARY_POINT_COLOR);
            Ellipse2D.Double marker = new Ellipse2D.Double(
                x - markerRadius, 
                y - markerRadius, 
                markerDiameter, 
                markerDiameter
            );
            g2d.fill(marker);
            
            // 将世界坐标转换为屏幕坐标以绘制序号(不随缩放变化)
            Point2D.Double worldPoint = new Point2D.Double(x, y);
            Point2D.Double screenPoint = new Point2D.Double();
            originalTransform.transform(worldPoint, screenPoint);
            
            // 保存当前变换
            AffineTransform savedTransform = g2d.getTransform();
            
            // 重置变换为屏幕坐标系统
            g2d.setTransform(new AffineTransform());
            
            // 绘制序号(在屏幕坐标系中,不随缩放变化)
            String numberText = String.valueOf(i + 1);
            int textWidth = fontMetrics.stringWidth(numberText);
            int textHeight = fontMetrics.getHeight();
            
            // 在点中心绘制序号
            int textX = (int)(screenPoint.x - textWidth / 2.0);
            int textY = (int)(screenPoint.y + textHeight / 4.0);
            
            // 绘制序号文字(无背景)
            g2d.setColor(Color.BLACK);
            g2d.drawString(numberText, textX, textY);
            
            // 恢复变换
            g2d.setTransform(savedTransform);
        }
        
        // 恢复原始变换
        g2d.setTransform(originalTransform);
    }
    
    /**
     * 检查两个边界点是否接近(用于判断边界是否闭合)
     */
    private boolean areBoundaryPointsClose(Point2D.Double a, Point2D.Double b) {
        if (a == null || b == null) {
            return false;
        }
        double dx = a.x - b.x;
        double dy = a.y - b.y;
        return Math.hypot(dx, dy) <= BOUNDARY_POINT_MERGE_THRESHOLD;
    }
    
    private void drawViewInfo(Graphics2D g2d) {
        g2d.setColor(new Color(80, 80, 80));
        g2d.setFont(new Font("微软雅黑", Font.PLAIN, 11));
 
        // 在地图顶部左侧显示遥控摇杆对应速度(若非零)
        try {
            int forward = Control03.getCurrentForwardSpeed();
            int steer = Control03.getCurrentSteeringSpeed();
            if (forward != 0 || steer != 0) {
                String speedInfo = String.format("行进:%d 转向:%d", forward, steer);
                // 背景半透明矩形增强可读性
                FontMetrics fm = g2d.getFontMetrics();
                int padding = 6;
                int w = fm.stringWidth(speedInfo) + padding * 2;
                int h = fm.getHeight() + padding;
                int x = 12;
                int y = 12;
                Color bg = new Color(255, 255, 255, 180);
                g2d.setColor(bg);
                g2d.fillRoundRect(x, y, w, h, 8, 8);
                g2d.setColor(new Color(120, 120, 120));
                g2d.drawString(speedInfo, x + padding, y + fm.getAscent() + (padding/2));
            }
        } catch (Throwable t) {
            // 不应阻塞渲染,静默处理任何异常
        }
 
        // 保留底部的缩放比例信息
        String info = String.format("缩放: %.2fx", scale);
        g2d.setColor(new Color(80, 80, 80));
        g2d.drawString(info, 15, visualizationPanel.getHeight() - 15);
    }
    
    /**
     * 获取当前平移量X
     */
    public double getTranslateX() {
        return translateX;
    }
    
    /**
     * 获取当前平移量Y
     */
    public double getTranslateY() {
        return translateY;
    }
    
    /**
     * 设置视图变换参数(用于程序化控制)
     */
    public void setViewTransform(double scale, double translateX, double translateY) {
        // 限制缩放范围
        scale = Math.max(MIN_SCALE, Math.min(scale, MAX_SCALE));
        // 如果缩放比例改变了,保存到配置文件
        if (Math.abs(this.scale - scale) > SCALE_EPSILON) {
            this.scale = scale;
            saveScaleToProperties();
        } else {
            this.scale = scale;
        }
        this.translateX = translateX;
        this.translateY = translateY;
        visualizationPanel.repaint();
    }
 
    public void setCurrentBoundary(String boundaryCoordinates, String landNumber, String landName) {
        this.boundaryName = landName;
        this.currentBoundaryLandNumber = landNumber;
        this.realtimeBoundaryPathCache = null;
        this.realtimeBoundaryPathLand = null;
 
        if (boundaryCoordinates == null) {
            clearBoundaryData();
            adjustViewAfterBoundaryReset();
            return;
        }
 
        String trimmed = boundaryCoordinates.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            clearBoundaryData();
            adjustViewAfterBoundaryReset();
            return;
        }
 
        List<Point2D.Double> parsed = parseBoundary(trimmed);
        if (parsed.size() < 2) {
            clearBoundaryData();
            adjustViewAfterBoundaryReset();
            return;
        }
 
    currentBoundary = parsed;
    rebuildBoundaryPath();
    pendingTrackBreak = true;
    boundaryBounds = computeBounds(parsed);
 
        Rectangle2D.Double bounds = boundaryBounds;
        SwingUtilities.invokeLater(() -> {
            fitBoundsToView(bounds);
            visualizationPanel.repaint();
        });
    }
 
    private void clearBoundaryData() {
        currentBoundary = null;
        currentBoundaryPath = null;
        boundaryBounds = null;
        boundaryName = null;
        boundaryPointsVisible = false;
        currentBoundaryLandNumber = null;
        pendingTrackBreak = true;
        realtimeBoundaryPathCache = null;
        realtimeBoundaryPathLand = null;
    }
 
    public void setCurrentObstacles(String obstaclesData, String landNumber) {
        List<Obstacledge.Obstacle> parsed = parseObstacles(obstaclesData, landNumber);
        applyObstaclesToRenderer(parsed, landNumber);
    }
 
    public void setCurrentObstacles(List<Obstacledge.Obstacle> obstacles, String landNumber) {
        List<Obstacledge.Obstacle> cloned = cloneObstacles(obstacles, landNumber);
        applyObstaclesToRenderer(cloned, landNumber);
    }
 
    private void applyObstaclesToRenderer(List<Obstacledge.Obstacle> obstacles, String landNumber) {
        List<Obstacledge.Obstacle> safeList = obstacles != null ? obstacles : Collections.emptyList();
        String normalizedLand = (landNumber != null) ? landNumber.trim() : null;
 
        if (normalizedLand != null && !normalizedLand.isEmpty()) {
            safeList = filterObstaclesForLand(safeList, normalizedLand);
        }
 
        if (normalizedLand == null || normalizedLand.isEmpty()) {
            clearObstacleData();
            if (!hasRenderableBoundary() && !hasRenderablePlannedPath()) {
                resetView();
            } else {
                visualizationPanel.repaint();
            }
            return;
        }
 
        if (safeList.isEmpty()) {
            clearObstacleData();
            if (!hasRenderableBoundary() && !hasRenderablePlannedPath()) {
                resetView();
            } else {
                visualizationPanel.repaint();
            }
            return;
        }
 
        currentObstacles = Collections.unmodifiableList(new ArrayList<>(safeList));
        currentObstacleLandNumber = normalizedLand;
        obstacleBounds = convertObstacleBounds(Obstacledraw.getAllObstaclesBounds(currentObstacles));
        selectedObstacleName = null;
 
        if (!hasRenderableBoundary() && !hasRenderablePlannedPath() && obstacleBounds != null) {
            Rectangle2D.Double bounds = obstacleBounds;
            SwingUtilities.invokeLater(() -> {
                fitBoundsToView(bounds);
                visualizationPanel.repaint();
            });
        } else {
            visualizationPanel.repaint();
        }
    }
 
    private List<Obstacledge.Obstacle> cloneObstacles(List<Obstacledge.Obstacle> obstacles, String landNumber) {
        List<Obstacledge.Obstacle> result = new ArrayList<>();
        if (obstacles == null || obstacles.isEmpty()) {
            return result;
        }
 
        String normalizedLandNumber = landNumber != null ? landNumber.trim() : null;
        Set<String> usedNames = new LinkedHashSet<>();
        int fallbackIndex = 1;
 
        for (Obstacledge.Obstacle source : obstacles) {
            if (source == null) {
                continue;
            }
 
            if (normalizedLandNumber != null && !normalizedLandNumber.isEmpty()) {
                String sourcePlotId = source.getPlotId();
                if (sourcePlotId != null && !sourcePlotId.trim().isEmpty()
                        && !normalizedLandNumber.equalsIgnoreCase(sourcePlotId.trim())) {
                    continue;
                }
            }
 
            Obstacledge.ObstacleShape shape = source.getShape();
            List<Obstacledge.XYCoordinate> xySource = source.getXyCoordinates();
            if (shape == null || xySource == null) {
                continue;
            }
 
            List<Obstacledge.XYCoordinate> xyCopy = copyXYCoordinates(xySource);
            if (shape == Obstacledge.ObstacleShape.CIRCLE && xyCopy.size() < 2) {
                continue;
            }
            if (shape == Obstacledge.ObstacleShape.POLYGON && xyCopy.size() < 3) {
                continue;
            }
 
            String desiredName = source.getObstacleName();
            if (desiredName == null || desiredName.trim().isEmpty()) {
                desiredName = "障碍物" + fallbackIndex++;
            }
            String uniqueName = ensureUniqueName(usedNames, desiredName.trim());
 
            Obstacledge.Obstacle copy = new Obstacledge.Obstacle(
                normalizedLandNumber != null ? normalizedLandNumber : source.getPlotId(),
                uniqueName,
                shape
            );
 
            copy.setXyCoordinates(xyCopy);
 
            List<Obstacledge.DMCoordinate> dmCopy = copyDMCoordinates(source.getOriginalCoordinates());
            if (dmCopy.isEmpty()) {
                populateDummyOriginalCoordinates(copy, xyCopy.size());
            } else {
                copy.setOriginalCoordinates(dmCopy);
            }
 
            result.add(copy);
        }
 
        return result;
    }
 
    private List<Obstacledge.Obstacle> filterObstaclesForLand(List<Obstacledge.Obstacle> obstacles, String landNumber) {
        if (obstacles == null || obstacles.isEmpty()) {
            return Collections.emptyList();
        }
        if (landNumber == null || landNumber.trim().isEmpty()) {
            return Collections.emptyList();
        }
        String normalized = landNumber.trim();
        List<Obstacledge.Obstacle> filtered = new ArrayList<>();
        for (Obstacledge.Obstacle obstacle : obstacles) {
            if (obstacle == null) {
                continue;
            }
            String plotId = obstacle.getPlotId();
            if (plotId == null || plotId.trim().isEmpty()) {
                filtered.add(obstacle);
                continue;
            }
            if (normalized.equalsIgnoreCase(plotId.trim())) {
                filtered.add(obstacle);
            }
        }
        return filtered;
    }
 
    private String ensureUniqueName(Set<String> usedNames, String preferredName) {
        String base = (preferredName == null || preferredName.trim().isEmpty()) ? "障碍物" : preferredName.trim();
        String normalized = base.toLowerCase(Locale.ROOT);
        if (usedNames.add(normalized)) {
            return base;
        }
        int suffix = 2;
        while (true) {
            String attempt = base + suffix;
            String attemptKey = attempt.toLowerCase(Locale.ROOT);
            if (usedNames.add(attemptKey)) {
                return attempt;
            }
            suffix++;
        }
    }
 
    private List<Obstacledge.XYCoordinate> copyXYCoordinates(List<Obstacledge.XYCoordinate> source) {
        List<Obstacledge.XYCoordinate> copy = new ArrayList<>();
        if (source == null) {
            return copy;
        }
        for (Obstacledge.XYCoordinate coord : source) {
            if (coord == null) {
                continue;
            }
            double x = coord.getX();
            double y = coord.getY();
            if (!Double.isFinite(x) || !Double.isFinite(y)) {
                continue;
            }
            copy.add(new Obstacledge.XYCoordinate(x, y));
        }
        return copy;
    }
 
    private List<Obstacledge.DMCoordinate> copyDMCoordinates(List<Obstacledge.DMCoordinate> source) {
        List<Obstacledge.DMCoordinate> copy = new ArrayList<>();
        if (source == null) {
            return copy;
        }
        for (Obstacledge.DMCoordinate coord : source) {
            if (coord == null) {
                continue;
            }
            copy.add(new Obstacledge.DMCoordinate(coord.getDegreeMinute(), coord.getDirection()));
        }
        return copy;
    }
 
    private void clearObstacleData() {
        currentObstacles = null;
        obstacleBounds = null;
        selectedObstacleName = null;
        currentObstacleLandNumber = null;
        obstaclePointsVisible = false;
    }
 
    private List<Obstacledge.Obstacle> parseObstacles(String obstaclesData, String landNumber) {
        List<Obstacledge.Obstacle> obstacles = new ArrayList<>();
        if (obstaclesData == null) {
            return obstacles;
        }
 
        String normalized = stripInlineComment(obstaclesData.trim());
        if (normalized.isEmpty() || "-1".equals(normalized)) {
            return obstacles;
        }
 
        List<String> entries = splitObstacleEntries(normalized);
        int defaultIndex = 1;
 
        for (String entry : entries) {
            String trimmedEntry = stripInlineComment(entry);
            if (trimmedEntry.isEmpty()) {
                continue;
            }
 
            String nameToken = null;
            String shapeToken = null;
            String coordsSection = trimmedEntry;
 
            if (trimmedEntry.contains("::")) {
                String[] parts = trimmedEntry.split("::", 3);
                if (parts.length == 3) {
                    nameToken = parts[0].trim();
                    shapeToken = parts[1].trim();
                    coordsSection = parts[2].trim();
                }
            } else if (trimmedEntry.contains("@")) {
                String[] parts = trimmedEntry.split("@", 3);
                if (parts.length == 3) {
                    nameToken = parts[0].trim();
                    shapeToken = parts[1].trim();
                    coordsSection = parts[2].trim();
                } else if (parts.length == 2) {
                    shapeToken = parts[0].trim();
                    coordsSection = parts[1].trim();
                }
            } else if (trimmedEntry.contains(":")) {
                String[] parts = trimmedEntry.split(":", 3);
                if (parts.length == 3) {
                    nameToken = parts[0].trim();
                    shapeToken = parts[1].trim();
                    coordsSection = parts[2].trim();
                } else if (parts.length == 2) {
                    if (looksLikeShapeToken(parts[0])) {
                        shapeToken = parts[0].trim();
                        coordsSection = parts[1].trim();
                    } else {
                        nameToken = parts[0].trim();
                        coordsSection = parts[1].trim();
                    }
                }
            }
 
            List<Obstacledge.XYCoordinate> xyCoordinates = parseObstacleCoordinates(coordsSection);
            if (xyCoordinates.size() < 2) {
                continue;
            }
 
            Obstacledge.ObstacleShape shape = resolveObstacleShape(shapeToken, xyCoordinates.size());
            if (shape == null) {
                continue;
            }
 
            String obstacleName = (nameToken != null && !nameToken.isEmpty())
                    ? nameToken
                    : "障碍物" + defaultIndex++;
 
            Obstacledge.Obstacle obstacle = new Obstacledge.Obstacle(landNumber, obstacleName, shape);
            obstacle.setXyCoordinates(new ArrayList<>(xyCoordinates));
            populateDummyOriginalCoordinates(obstacle, xyCoordinates.size());
 
            if (obstacle.isValid()) {
                obstacles.add(obstacle);
            }
        }
 
        return obstacles;
    }
 
    private boolean looksLikeShapeToken(String token) {
        if (token == null) {
            return false;
        }
        String normalized = token.trim().toLowerCase(Locale.ROOT);
        return "circle".equals(normalized)
                || "polygon".equals(normalized)
                || "圆形".equals(normalized)
                || "多边形".equals(normalized)
                || "0".equals(normalized)
                || "1".equals(normalized);
    }
 
    private List<Obstacledge.XYCoordinate> parseObstacleCoordinates(String coordsSection) {
        List<Obstacledge.XYCoordinate> coords = new ArrayList<>();
        if (coordsSection == null) {
            return coords;
        }
 
        String sanitized = stripInlineComment(coordsSection.trim());
        if (sanitized.isEmpty() || "-1".equals(sanitized)) {
            return coords;
        }
 
        // Remove wrapper characters like parentheses that are used when persisting payloads
        sanitized = sanitized.replace("(", "").replace(")", "");
 
        String[] pairs = sanitized.split(";");
        for (String pair : pairs) {
            if (pair == null) {
                continue;
            }
            String trimmed = stripInlineComment(pair.trim());
            if (trimmed.isEmpty()) {
                continue;
            }
            trimmed = trimmed.replace("(", "").replace(")", "");
            if (trimmed.isEmpty()) {
                continue;
            }
            String[] parts = trimmed.split(",");
            if (parts.length < 2) {
                continue;
            }
            try {
                double x = Double.parseDouble(parts[0].trim());
                double y = Double.parseDouble(parts[1].trim());
                coords.add(new Obstacledge.XYCoordinate(x, y));
            } catch (NumberFormatException ignored) {
                // Skip malformed coordinate pair
            }
        }
 
        return coords;
    }
 
    private Obstacledge.ObstacleShape resolveObstacleShape(String shapeToken, int coordinateCount) {
        if (shapeToken != null && !shapeToken.trim().isEmpty()) {
            String normalized = shapeToken.trim().toLowerCase(Locale.ROOT);
            if ("circle".equals(normalized) || "圆形".equals(normalized) || "0".equals(normalized)) {
                return Obstacledge.ObstacleShape.CIRCLE;
            }
            if ("polygon".equals(normalized) || "多边形".equals(normalized) || "1".equals(normalized)) {
                return Obstacledge.ObstacleShape.POLYGON;
            }
        }
 
        if (coordinateCount == 2) {
            return Obstacledge.ObstacleShape.CIRCLE;
        }
        if (coordinateCount >= 3) {
            return Obstacledge.ObstacleShape.POLYGON;
        }
        return null;
    }
 
    private void populateDummyOriginalCoordinates(Obstacledge.Obstacle obstacle, int xyCount) {
        List<Obstacledge.DMCoordinate> dmCoordinates = new ArrayList<>();
        int points = Math.max(1, xyCount);
        for (int i = 0; i < points; i++) {
            dmCoordinates.add(new Obstacledge.DMCoordinate(0.0, 'N'));
            dmCoordinates.add(new Obstacledge.DMCoordinate(0.0, 'E'));
        }
        obstacle.setOriginalCoordinates(dmCoordinates);
    }
 
    private List<String> splitObstacleEntries(String data) {
        List<String> entries = new ArrayList<>();
        if (data.indexOf('|') >= 0) {
            String[] parts = data.split("\\|");
            for (String part : parts) {
                if (part != null && !part.trim().isEmpty()) {
                    entries.add(part.trim());
                }
            }
        } else if (data.contains("\n")) {
            String[] lines = data.split("\r?\n");
            for (String line : lines) {
                if (line != null && !line.trim().isEmpty()) {
                    entries.add(line.trim());
                }
            }
        } else {
            entries.add(data);
        }
        return entries;
    }
 
    private String stripInlineComment(String text) {
        if (text == null) {
            return "";
        }
        int hashIndex = text.indexOf('#');
        if (hashIndex >= 0) {
            return text.substring(0, hashIndex).trim();
        }
        return text.trim();
    }
 
    private Rectangle2D.Double convertObstacleBounds(double[] bounds) {
        if (bounds == null || bounds.length < 4) {
            return null;
        }
        double minX = bounds[0];
        double minY = bounds[1];
        double maxX = bounds[2];
        double maxY = bounds[3];
        return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
    }
 
    private boolean hasRenderableBoundary() {
        return currentBoundary != null && currentBoundary.size() >= 2;
    }
 
    private boolean hasRenderablePlannedPath() {
        return currentPlannedPath != null && currentPlannedPath.size() >= 2;
    }
 
    private void adjustViewAfterBoundaryReset() {
        if (plannedPathBounds != null) {
            Rectangle2D.Double bounds = plannedPathBounds;
            SwingUtilities.invokeLater(() -> {
                fitBoundsToView(bounds);
                visualizationPanel.repaint();
            });
            return;
        }
 
        if (obstacleBounds != null) {
            Rectangle2D.Double bounds = obstacleBounds;
            SwingUtilities.invokeLater(() -> {
                fitBoundsToView(bounds);
                visualizationPanel.repaint();
            });
            return;
        }
 
        resetView();
    }
 
    public void setCurrentPlannedPath(String plannedPath) {
        if (plannedPath == null) {
            currentPlannedPath = null;
            plannedPathBounds = null;
            if (!hasRenderableBoundary()) {
                resetView();
            } else {
                visualizationPanel.repaint();
            }
            return;
        }
 
        List<Point2D.Double> parsed = lujingdraw.parsePlannedPath(plannedPath);
        if (parsed.size() < 2) {
            currentPlannedPath = null;
            plannedPathBounds = null;
            if (!hasRenderableBoundary()) {
                resetView();
            } else {
                visualizationPanel.repaint();
            }
            return;
        }
 
        currentPlannedPath = parsed;
        plannedPathBounds = computeBounds(parsed);
 
        Rectangle2D.Double bounds = plannedPathBounds;
        SwingUtilities.invokeLater(() -> {
            if (!hasRenderableBoundary()) {
                fitBoundsToView(bounds);
            }
            visualizationPanel.repaint();
        });
    }
 
    public void setBoundaryPointsVisible(boolean visible) {
        this.boundaryPointsVisible = visible;
        visualizationPanel.repaint();
    }
 
    public void setObstaclePointsVisible(boolean visible) {
        this.obstaclePointsVisible = visible;
        visualizationPanel.repaint();
    }
    
    /**
     * 设置是否显示边界距离
     */
    public void setBoundaryLengthVisible(boolean visible) {
        boundaryLengthVisible = visible;
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 获取是否显示边界距离
     */
    public boolean isBoundaryLengthVisible() {
        return boundaryLengthVisible;
    }
 
    public void setBoundaryPointSizeScale(double sizeScale) {
        double normalized = (Double.isFinite(sizeScale) && sizeScale > 0.0d) ? sizeScale : 1.0d;
        if (Math.abs(boundaryPointSizeScale - normalized) < 1e-6) {
            return;
        }
        boundaryPointSizeScale = normalized;
        if (visualizationPanel == null) {
            return;
        }
        if (SwingUtilities.isEventDispatchThread()) {
            visualizationPanel.repaint();
        } else {
            SwingUtilities.invokeLater(visualizationPanel::repaint);
        }
    }
 
    public void setPathPreviewSizingEnabled(boolean enabled) {
        previewSizingEnabled = enabled;
        if (visualizationPanel == null) {
            return;
        }
        if (SwingUtilities.isEventDispatchThread()) {
            visualizationPanel.repaint();
        } else {
            SwingUtilities.invokeLater(visualizationPanel::repaint);
        }
    }
 
    public void setBoundaryPreviewMarkerScale(double markerScale) {
        double normalized = Double.isFinite(markerScale) && markerScale > 0.0d ? markerScale : 1.0d;
        if (Math.abs(boundaryPreviewMarkerScale - normalized) < 1e-6) {
            return;
        }
        boundaryPreviewMarkerScale = normalized;
        if (visualizationPanel == null) {
            return;
        }
        if (SwingUtilities.isEventDispatchThread()) {
            visualizationPanel.repaint();
        } else {
            SwingUtilities.invokeLater(visualizationPanel::repaint);
        }
    }
 
    public boolean setHandheldMowerIconActive(boolean handheldActive) {
        if (mower == null) {
            return false;
        }
        boolean changed = mower.useHandheldIcon(handheldActive);
        if (changed && visualizationPanel != null) {
            if (SwingUtilities.isEventDispatchThread()) {
                visualizationPanel.repaint();
            } else {
                SwingUtilities.invokeLater(visualizationPanel::repaint);
            }
        }
        return changed;
    }
 
    public void beginHandheldBoundaryPreview() {
        handheldBoundaryPreviewActive = true;
        handheldBoundaryPreview.clear();
        visualizationPanel.repaint();
    }
 
    public void addHandheldBoundaryPoint(double x, double y) {
        if (!Double.isFinite(x) || !Double.isFinite(y)) {
            return;
        }
        if (!handheldBoundaryPreviewActive) {
            beginHandheldBoundaryPreview();
        }
        Point2D.Double last = handheldBoundaryPreview.isEmpty() ? null : handheldBoundaryPreview.get(handheldBoundaryPreview.size() - 1);
        if (last != null) {
            double dx = x - last.x;
            double dy = y - last.y;
            if (Math.hypot(dx, dy) < 1e-6) {
                visualizationPanel.repaint();
                return;
            }
        }
        handheldBoundaryPreview.add(new Point2D.Double(x, y));
        visualizationPanel.repaint();
    }
 
    public void clearHandheldBoundaryPreview() {
        handheldBoundaryPreviewActive = false;
        handheldBoundaryPreview.clear();
        boundaryPreviewMarkerScale = 1.0d;
        visualizationPanel.repaint();
    }
 
    public List<Point2D.Double> getHandheldBoundaryPreviewPoints() {
        return new ArrayList<>(handheldBoundaryPreview);
    }
 
    private List<Point2D.Double> parseBoundary(String boundaryCoordinates) {
        List<Point2D.Double> points = new ArrayList<>();
        String[] entries = boundaryCoordinates.split(";");
 
        for (String entry : entries) {
            if (entry == null || entry.trim().isEmpty()) {
                continue;
            }
            String[] parts = entry.trim().split(",");
            if (parts.length < 2) {
                continue;
            }
            try {
                double x = Double.parseDouble(parts[0].trim());
                double y = Double.parseDouble(parts[1].trim());
                points.add(new Point2D.Double(x, y));
            } catch (NumberFormatException ex) {
                // ignore invalid entries
            }
        }
        return points;
    }
 
    private Rectangle2D.Double computeBounds(List<Point2D.Double> points) {
        double minX = Double.MAX_VALUE;
        double minY = Double.MAX_VALUE;
        double maxX = -Double.MAX_VALUE;
        double maxY = -Double.MAX_VALUE;
 
        for (Point2D.Double point : points) {
            if (point.x < minX) minX = point.x;
            if (point.x > maxX) maxX = point.x;
            if (point.y < minY) minY = point.y;
            if (point.y > maxY) maxY = point.y;
        }
 
        if (minX == Double.MAX_VALUE) {
            return null;
        }
 
        return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
    }
 
    private void fitBoundsToView(Rectangle2D.Double bounds) {
        if (bounds == null || visualizationPanel.getWidth() <= 0 || visualizationPanel.getHeight() <= 0) {
            return;
        }
 
        Rectangle2D.Double targetBounds = includeMowerInBounds(bounds);
 
        double width = Math.max(targetBounds.width, 1);
        double height = Math.max(targetBounds.height, 1);
 
        double targetWidth = width * 1.2;
        double targetHeight = height * 1.2;
 
        double panelWidth = visualizationPanel.getWidth();
        double panelHeight = visualizationPanel.getHeight();
 
        double newScale = Math.min(panelWidth / targetWidth, panelHeight / targetHeight);
        newScale = Math.max(0.05, Math.min(newScale, 50.0));
 
        this.scale = newScale;
        this.translateX = -targetBounds.getCenterX();
        this.translateY = -targetBounds.getCenterY();
    }
 
    // Keep the mower marker inside the viewport whenever the camera refits to scene bounds.
    private Rectangle2D.Double includeMowerInBounds(Rectangle2D.Double bounds) {
        Rectangle2D.Double expanded = new Rectangle2D.Double(
            bounds.x,
            bounds.y,
            Math.max(0.0, bounds.width),
            Math.max(0.0, bounds.height)
        );
 
        if (mower == null || !mower.hasValidPosition()) {
            return expanded;
        }
 
        Point2D.Double mowerPosition = mower.getPosition();
        if (mowerPosition == null
            || !Double.isFinite(mowerPosition.x)
            || !Double.isFinite(mowerPosition.y)) {
            return expanded;
        }
 
        double minX = Math.min(expanded.x, mowerPosition.x);
        double minY = Math.min(expanded.y, mowerPosition.y);
        double maxX = Math.max(expanded.x + expanded.width, mowerPosition.x);
        double maxY = Math.max(expanded.y + expanded.height, mowerPosition.y);
 
        expanded.x = minX;
        expanded.y = minY;
        expanded.width = Math.max(0.0, maxX - minX);
        expanded.height = Math.max(0.0, maxY - minY);
 
        return expanded;
    }
 
    public void dispose() {
        mowerUpdateTimer.stop();
        mowerInfoManager.dispose();
    }
 
    /**
     * 获取当前边界点列表
     * @return 当前边界点列表,如果没有边界则返回null
     */
    public List<Point2D.Double> getCurrentBoundary() {
        return currentBoundary;
    }
 
    /**
     * 获取割草机实例
     * @return 割草机实例
     */
    public Gecaoji getMower() {
        return mower;
    }
    
    /**
     * 设置往返路径绘制管理器
     */
    public void setReturnPathDrawer(WangfanDraw drawer) {
        this.returnPathDrawer = drawer;
    }
 
    /**
     * 设置预览的往返路径
     */
    public void setPreviewReturnPath(List<Point2D.Double> path) {
        this.previewReturnPath = path;
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 开始往返路径绘制
     */
    public void startReturnPathDrawing() {
        if (returnPathDrawer != null) {
            // 禁用拖尾效果(在往返路径绘制模式下不显示实时轨迹拖尾)
            idleTrailSuppressed = true;
            clearIdleMowerTrail();
            // 清空之前的路径点(通过 WangfanDraw 管理)
            repaint();
        }
    }
    
    /**
     * 停止往返路径绘制
     */
    public void stopReturnPathDrawing() {
        // 恢复拖尾效果
        idleTrailSuppressed = false;
        repaint();
    }
    
    /**
     * 设置拖尾抑制状态
     * @param suppressed true表示抑制拖尾绘制,false表示允许拖尾绘制
     */
    public void setIdleTrailSuppressed(boolean suppressed) {
        idleTrailSuppressed = suppressed;
        if (suppressed && !idleMowerTrail.isEmpty()) {
            clearIdleMowerTrail();
        }
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 添加往返路径点(已废弃,路径点由 WangfanDraw 直接管理)
     */
    @Deprecated
    public void addReturnPathPoint(double x, double y) {
        // 路径点由 WangfanDraw 直接管理,这里只需要重绘
        repaint();
    }
    
    /**
     * 获取往返路径点列表的快照
     */
    public List<Point2D.Double> getReturnPathPointsSnapshot() {
        if (returnPathDrawer != null) {
            return returnPathDrawer.getPointsSnapshot();
        }
        return new ArrayList<>();
    }
    
    /**
     * 设置边界预览数据(原始边界和优化后边界)
     */
    public void setBoundaryPreview(String originalBoundaryXY, String optimizedBoundary) {
        if (originalBoundaryXY != null && !originalBoundaryXY.trim().isEmpty() && !"-1".equals(originalBoundaryXY.trim())) {
            previewOriginalBoundary = parseBoundary(originalBoundaryXY.trim());
        } else {
            previewOriginalBoundary = null;
        }
        
        if (optimizedBoundary != null && !optimizedBoundary.trim().isEmpty() && !"-1".equals(optimizedBoundary.trim())) {
            previewOptimizedBoundary = parseBoundary(optimizedBoundary.trim());
        } else {
            previewOptimizedBoundary = null;
        }
        
        boundaryPreviewActive = (previewOriginalBoundary != null && previewOriginalBoundary.size() >= 2) ||
                               (previewOptimizedBoundary != null && previewOptimizedBoundary.size() >= 2);
        
        if (boundaryPreviewActive) {
            // 计算预览边界的边界框并调整视图
            List<Point2D.Double> allPoints = new ArrayList<>();
            if (previewOriginalBoundary != null) allPoints.addAll(previewOriginalBoundary);
            if (previewOptimizedBoundary != null) allPoints.addAll(previewOptimizedBoundary);
            if (!allPoints.isEmpty()) {
                Rectangle2D.Double bounds = computeBounds(allPoints);
                SwingUtilities.invokeLater(() -> {
                    fitBoundsToView(bounds);
                    visualizationPanel.repaint();
                });
            }
        } else {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 清除边界预览
     */
    public void clearBoundaryPreview() {
        previewOriginalBoundary = null;
        previewOptimizedBoundary = null;
        boundaryPreviewActive = false;
        visualizationPanel.repaint();
    }
    
    /**
     * 绘制边界预览(原始边界-紫色,优化后边界-绿色)
     */
    private void drawBoundaryPreview(Graphics2D g2d) {
        // 绘制原始边界(紫色)
        if (previewOriginalBoundary != null && previewOriginalBoundary.size() >= 2) {
            Color purpleFill = new Color(128, 0, 128, 80); // 紫色半透明填充
            Color purpleBorder = new Color(128, 0, 128, 255); // 紫色边框
            bianjiedrwa.drawBoundary(g2d, previewOriginalBoundary, scale, purpleFill, purpleBorder);
            
            // 如果隐藏了优化边界,显示原始边界坐标点(深绿色实心圆圈)
            if (showOnlyOriginalBoundary) {
                drawOriginalBoundaryPointsWithNumbers(g2d, previewOriginalBoundary, scale);
            }
        }
        
        // 根据标志决定是否绘制优化后边界
        if (!showOnlyOriginalBoundary) {
            // 绘制优化后边界(绿色,与正常边界颜色一致)
            if (previewOptimizedBoundary != null && previewOptimizedBoundary.size() >= 2) {
                bianjiedrwa.drawBoundary(g2d, previewOptimizedBoundary, scale, GRASS_FILL_COLOR, GRASS_BORDER_COLOR);
                
                // 绘制优化后边界坐标点(紫色实心圆圈,显示序号)
                drawOptimizedBoundaryPointsWithNumbers(g2d, previewOptimizedBoundary, scale);
            }
        }
    }
    
    /**
     * 设置是否只显示原始边界
     * @param showOnlyOriginal 如果为true,只显示原始边界;如果为false,显示原始边界和优化边界
     */
    public void setShowOnlyOriginalBoundary(boolean showOnlyOriginal) {
        this.showOnlyOriginalBoundary = showOnlyOriginal;
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 获取是否只显示原始边界
     * @return 如果只显示原始边界返回true,否则返回false
     */
    public boolean isShowOnlyOriginalBoundary() {
        return showOnlyOriginalBoundary;
    }
    
    /**
     * 绘制优化后边界坐标点(紫色实心圆圈,显示序号)
     * 序号显示在点中心,字体大小11号,不随缩放变化
     */
    private void drawOptimizedBoundaryPointsWithNumbers(Graphics2D g2d, List<Point2D.Double> boundary, double scale) {
        if (boundary == null || boundary.isEmpty()) {
            return;
        }
        
        // 保存原始变换
        AffineTransform originalTransform = g2d.getTransform();
        
        // 设置点的大小(实心圆圈,直径约0.3米)
        double scaleFactor = Math.max(0.5, scale);
        double markerDiameter = 0.3; // 圆圈直径(米)
        double markerRadius = markerDiameter / 2.0;
        
        // 设置字体(11号,不随缩放变化)
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 11);
        g2d.setFont(labelFont);
        FontMetrics fontMetrics = g2d.getFontMetrics(labelFont);
        
        // 紫色实心圆圈颜色
        Color purpleColor = new Color(128, 0, 128, 255); // 紫色
        
        // 绘制每个点及其序号
        for (int i = 0; i < boundary.size(); i++) {
            Point2D.Double point = boundary.get(i);
            double x = point.x;
            double y = point.y;
            
            // 绘制紫色实心圆圈(在世界坐标系中,随缩放变化)
            g2d.setColor(purpleColor);
            Ellipse2D.Double marker = new Ellipse2D.Double(
                x - markerRadius, 
                y - markerRadius, 
                markerDiameter, 
                markerDiameter
            );
            g2d.fill(marker);
            
            // 将世界坐标转换为屏幕坐标以绘制序号(不随缩放变化)
            Point2D.Double worldPoint = new Point2D.Double(x, y);
            Point2D.Double screenPoint = new Point2D.Double();
            originalTransform.transform(worldPoint, screenPoint);
            
            // 保存当前变换
            AffineTransform savedTransform = g2d.getTransform();
            
            // 重置变换为屏幕坐标系统
            g2d.setTransform(new AffineTransform());
            
            // 绘制序号(在屏幕坐标系中,不随缩放变化)
            String numberText = String.valueOf(i + 1);
            int textWidth = fontMetrics.stringWidth(numberText);
            int textHeight = fontMetrics.getHeight();
            
            // 在点中心绘制序号
            int textX = (int)(screenPoint.x - textWidth / 2.0);
            int textY = (int)(screenPoint.y + textHeight / 4.0);
            
            // 绘制序号文字(黑色)
            g2d.setColor(Color.BLACK);
            g2d.drawString(numberText, textX, textY);
            
            // 恢复变换
            g2d.setTransform(savedTransform);
        }
        
        // 恢复原始变换
        g2d.setTransform(originalTransform);
    }
    
    /**
     * 绘制原始边界坐标点(深绿色实心圆圈,显示序号)
     * 只在隐藏优化边界时显示
     */
    private void drawOriginalBoundaryPointsWithNumbers(Graphics2D g2d, List<Point2D.Double> boundary, double scale) {
        if (boundary == null || boundary.isEmpty()) {
            return;
        }
        
        // 保存原始变换
        AffineTransform originalTransform = g2d.getTransform();
        
        // 设置点的大小(实心圆圈,直径约0.3米,与优化后边界坐标点大小一致)
        double scaleFactor = Math.max(0.5, scale);
        double markerDiameter = 0.3; // 圆圈直径(米)
        double markerRadius = markerDiameter / 2.0;
        
        // 设置字体(11号,不随缩放变化)
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 11);
        g2d.setFont(labelFont);
        FontMetrics fontMetrics = g2d.getFontMetrics(labelFont);
        
        // 深绿色实心圆圈颜色
        Color darkGreenColor = new Color(0, 100, 0, 255); // 深绿色
        
        // 绘制每个点及其序号
        for (int i = 0; i < boundary.size(); i++) {
            Point2D.Double point = boundary.get(i);
            double x = point.x;
            double y = point.y;
            
            // 绘制深绿色实心圆圈(在世界坐标系中,随缩放变化)
            g2d.setColor(darkGreenColor);
            Ellipse2D.Double marker = new Ellipse2D.Double(
                x - markerRadius, 
                y - markerRadius, 
                markerDiameter, 
                markerDiameter
            );
            g2d.fill(marker);
            
            // 将世界坐标转换为屏幕坐标以绘制序号(不随缩放变化)
            Point2D.Double worldPoint = new Point2D.Double(x, y);
            Point2D.Double screenPoint = new Point2D.Double();
            originalTransform.transform(worldPoint, screenPoint);
            
            // 保存当前变换
            AffineTransform savedTransform = g2d.getTransform();
            
            // 重置变换为屏幕坐标系统
            g2d.setTransform(new AffineTransform());
            
            // 绘制序号(在屏幕坐标系中,不随缩放变化)
            String numberText = String.valueOf(i + 1);
            int textWidth = fontMetrics.stringWidth(numberText);
            int textHeight = fontMetrics.getHeight();
            
            // 在点中心绘制序号
            int textX = (int)(screenPoint.x - textWidth / 2.0);
            int textY = (int)(screenPoint.y + textHeight / 4.0);
            
            // 绘制序号文字(黑色)
            g2d.setColor(Color.BLACK);
            g2d.drawString(numberText, textX, textY);
            
            // 恢复变换
            g2d.setTransform(savedTransform);
        }
        
        // 恢复原始变换
        g2d.setTransform(originalTransform);
    }
    
    /**
     * 处理优化后边界坐标点点击
     * @param screenPoint 屏幕坐标点
     * @return 是否处理了点击
     */
    private boolean handleOptimizedBoundaryPointClick(Point screenPoint) {
        if (previewOptimizedBoundary == null || previewOptimizedBoundary.isEmpty()) {
            return false;
        }
        
        // 计算选择阈值(像素)
        double threshold = computeOptimizedBoundaryPointSelectionThreshold();
        
        // 查找被点击的点
        int hitIndex = -1;
        for (int i = 0; i < previewOptimizedBoundary.size(); i++) {
            Point2D.Double worldPoint = previewOptimizedBoundary.get(i);
            Point2D.Double screenPosition = worldToScreen(worldPoint);
            double dx = screenPosition.x - screenPoint.x;
            double dy = screenPosition.y - screenPoint.y;
            if (Math.hypot(dx, dy) <= threshold) {
                hitIndex = i;
                break;
            }
        }
        
        if (hitIndex < 0) {
            return false;
        }
        
        // 弹出确认对话框
        String pointLabel = String.valueOf(hitIndex + 1);
        int choice = JOptionPane.showConfirmDialog(
            visualizationPanel,
            "确定要删除第" + pointLabel + "号优化后边界坐标点吗?",
            "删除边界坐标点",
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE
        );
        
        if (choice == JOptionPane.OK_OPTION) {
            // 删除坐标点
            List<Point2D.Double> updated = new ArrayList<>(previewOptimizedBoundary);
            updated.remove(hitIndex);
            
            // 更新预览边界
            previewOptimizedBoundary = updated;
            
            // 转换为字符串格式并保存
            String updatedBoundaryString = convertBoundaryToString(updated);
            
            // 通知 Shouye 保存更新后的边界坐标
            if (boundaryPreviewUpdateCallback != null) {
                boundaryPreviewUpdateCallback.accept(updatedBoundaryString);
            }
            
            // 刷新显示
            visualizationPanel.repaint();
        }
        
        return true;
    }
    
    /**
     * 计算优化后边界坐标点的选择阈值(像素)
     */
    private double computeOptimizedBoundaryPointSelectionThreshold() {
        double scaleFactor = Math.max(0.5, scale);
        double markerDiameterWorld = 0.3; // 圆圈直径(米)
        double markerDiameterPixels = markerDiameterWorld * scale;
        return Math.max(8.0, markerDiameterPixels * 1.5);
    }
    
    /**
     * 将边界点列表转换为字符串格式
     */
    private String convertBoundaryToString(List<Point2D.Double> boundary) {
        if (boundary == null || boundary.isEmpty()) {
            return "";
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < boundary.size(); i++) {
            Point2D.Double point = boundary.get(i);
            sb.append(String.format(Locale.US, "%.2f,%.2f", point.x, point.y));
            if (i < boundary.size() - 1) {
                sb.append(";");
            }
        }
        return sb.toString();
    }
    
    /**
     * 设置边界预览更新回调
     */
    private java.util.function.Consumer<String> boundaryPreviewUpdateCallback;
    
    public void setBoundaryPreviewUpdateCallback(java.util.function.Consumer<String> callback) {
        this.boundaryPreviewUpdateCallback = callback;
    }
 
}