-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.html
More file actions
653 lines (565 loc) · 27.4 KB
/
Copy path2.html
File metadata and controls
653 lines (565 loc) · 27.4 KB
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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Voronoi NavMesh A* & Funnel 寻路演示</title>
<style>
:root {
--color-background-primary: #ffffff;
--color-background-secondary: #f0f2f5;
--color-border-secondary: #d1d5db;
--color-border-tertiary: #e5e7eb;
--color-text-primary: #111827;
--color-text-secondary: #4b5563;
--border-radius-md: 6px;
--border-radius-lg: 8px;
--font-sans: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background-color: var(--color-background-secondary);
display: flex;
justify-content: center;
padding: 20px;
margin: 0;
}
#app {
font-family: var(--font-sans);
padding: 20px;
background: white;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
max-width: 950px;
width: 100%;
}
h2 {
margin-top: 0;
color: #333;
text-align: center;
font-size: 1.5rem;
}
canvas {
display: block;
border-radius: var(--border-radius-lg);
border: 1px solid var(--color-border-tertiary);
width: 100%;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
background-color: #e5e7eb;
}
.controls {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
margin-top: 15px;
font-size: 14px;
color: var(--color-text-secondary);
}
button {
font-size: 14px;
padding: 8px 16px;
border-radius: var(--border-radius-md);
border: 1px solid var(--color-border-secondary);
background: var(--color-background-primary);
color: var(--color-text-primary);
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
}
button:hover {
background: #f3f4f6;
border-color: #9ca3af;
}
button:active {
transform: scale(0.97);
}
.legend {
display: flex;
gap: 16px;
flex-wrap: wrap;
background: #f8f9fa;
padding: 10px 15px;
border-radius: 8px;
border: 1px solid #eee;
width: 100%;
}
.leg {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--color-text-secondary);
font-weight: 500;
}
.dot {
width: 12px;
height: 12px;
border-radius: 3px;
flex-shrink: 0;
border: 1px solid rgba(0, 0, 0, 0.1);
}
#status {
font-size: 14px;
font-weight: bold;
color: #2563eb;
min-width: 200px;
margin-left: auto;
padding: 6px 12px;
background: #eff6ff;
border-radius: 6px;
border: 1px solid #bfdbfe;
}
</style>
</head>
<body>
<div id="app">
<h2>NavMesh A* & Funnel 算法 (拉紧/平滑) 演示</h2>
<canvas id="c" height="500"></canvas>
<div class="controls">
<button onclick="init()">🔄 生成新地形</button>
<button onclick="runPathfinding()">▶ 开始 寻路与Funnel平滑</button>
<button onclick="resetPath()">↺ 重置</button>
<span id="status">点击 "开始 寻路与Funnel平滑"</span>
</div>
<div class="controls">
<div class="legend">
<div class="leg">
<div class="dot" style="background:#e8f5e9"></div>可行走区域
</div>
<div class="leg">
<div class="dot" style="background:#90a4ae"></div>障碍物
</div>
<div class="leg">
<div class="dot" style="background:#fff176"></div>A* 评估区域
</div>
<div class="leg">
<div class="dot" style="background:#ef4444"></div>A* 原始路径 (单元格中心)
</div>
<div class="leg">
<div class="dot" style="background:#3b82f6; border-radius: 50%;"></div>漏斗左边界射线
</div>
<div class="leg">
<div class="dot" style="background:#ef4444; border-radius: 50%;"></div>漏斗右边界射线
</div>
<div class="leg">
<div class="dot" style="background:#8b5cf6"></div>Funnel 最终平滑路径
</div>
</div>
</div>
</div>
<script>
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
let W, H, cells = [], graph = {}, walls = new Set(), path = [], explored = [], animFrame = 0;
// Funnel 状态变量
let funnelMode = false;
let funnelState = null;
let funnelPortals = [];
let smoothedPath = [];
function resize() {
const r = canvas.getBoundingClientRect();
W = canvas.width = r.width * devicePixelRatio;
H = canvas.height = 500 * devicePixelRatio;
canvas.style.height = '500px';
ctx.scale(devicePixelRatio, devicePixelRatio);
}
// ================= 1. 地图生成与几何算法 =================
function init() {
resize();
W /= devicePixelRatio; H /= devicePixelRatio;
// 【修复这里】直接重置状态变量,不要调用 resetPath() 触发重绘
path = []; explored = [];
funnelMode = false; funnelState = null; smoothedPath = []; funnelPortals = [];
document.getElementById('status').textContent = '地图已生成。请点击 "开始 寻路与Funnel平滑"';
const N = 28 + Math.floor(Math.random() * 12);
let seeds = [];
seeds.push({ x: 60 + Math.random() * 60, y: 60 + Math.random() * 60 }); // Start
for (let i = 1; i < N - 1; i++) seeds.push({ x: 30 + Math.random() * (W - 60), y: 30 + Math.random() * (H - 60) });
seeds.push({ x: W - 120 + Math.random() * 60, y: H - 120 + Math.random() * 60 }); // Goal
cells = computeVoronoi(seeds, W, H, 2);
walls = new Set();
for (let i = 1; i < cells.length - 1; i++) {
if (Math.random() < 0.28) walls.add(i);
}
walls.delete(0); walls.delete(cells.length - 1);
buildGraph();
draw([], []);
}
function computeVoronoi(seeds, W, H, relaxIter) {
for (let iter = 0; iter < relaxIter; iter++) {
const counts = seeds.map(() => ({ sx: 0, sy: 0, n: 0 }));
for (let px = 0; px < W; px += 2) for (let py = 0; py < H; py += 2) {
const ci = nearest(seeds, px, py);
counts[ci].sx += px; counts[ci].sy += py; counts[ci].n++;
}
seeds = seeds.map((s, i) => counts[i].n > 0 ? { x: counts[i].sx / counts[i].n, y: counts[i].sy / counts[i].n } : s);
}
const regionPts = seeds.map(() => []);
const step = 3;
for (let px = 0; px < W; px += step) for (let py = 0; py < H; py += step) {
const ci = nearest(seeds, px, py);
let border = false;
if (px > 0 && nearest(seeds, px - step, py) !== ci) border = true;
if (py > 0 && nearest(seeds, px, py - step) !== ci) border = true;
if (!border) { regionPts[ci].push([px, py]); }
regionPts[ci].push([px, py]);
}
[[0, 0], [W, 0], [0, H], [W, H]].forEach(([px, py]) => regionPts[nearest(seeds, px, py)].push([px, py]));
return seeds.map((s, i) => {
const pts = regionPts[i];
return { cx: s.x, cy: s.y, points: convexHull(pts) };
});
}
function nearest(seeds, px, py) {
let best = 0, bd = 1e18;
for (let i = 0; i < seeds.length; i++) {
const d = (seeds[i].x - px) ** 2 + (seeds[i].y - py) ** 2;
if (d < bd) { bd = d; best = i; }
}
return best;
}
function convexHull(pts) {
if (pts.length < 3) return pts;
pts = pts.map(p => Array.isArray(p) ? p : p);
pts.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
const unique = [];
pts.forEach(p => { if (!unique.length || unique[unique.length - 1][0] !== p[0] || unique[unique.length - 1][1] !== p[1]) unique.push(p); });
if (unique.length < 2) return unique;
const lower = [], upper = [];
for (const p of unique) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
lower.push(p);
}
for (let i = unique.length - 1; i >= 0; i--) {
const p = unique[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
upper.push(p);
}
upper.pop(); lower.pop();
return [...lower, ...upper];
}
function cross(O, A, B) { return (A[0] - O[0]) * (B[1] - O[1]) - (A[1] - O[1]) * (B[0] - O[0]); }
function buildGraph() {
graph = {};
for (let i = 0; i < cells.length; i++) graph[i] = [];
for (let i = 0; i < cells.length; i++) {
for (let j = i + 1; j < cells.length; j++) {
if (cellsAdjacent(i, j)) {
graph[i].push(j); graph[j].push(i);
}
}
}
}
function cellsAdjacent(i, j) {
const dist = Math.sqrt((cells[i].cx - cells[j].cx) ** 2 + (cells[i].cy - cells[j].cy) ** 2);
return dist < (avgRadius(cells[i]) + avgRadius(cells[j])) * 1.05;
}
function avgRadius(cell) {
if (!cell.points.length) return 0;
return cell.points.reduce((s, p) => s + Math.sqrt((p[0] - cell.cx) ** 2 + (p[1] - cell.cy) ** 2), 0) / cell.points.length;
}
function heuristic(i, j) { return Math.sqrt((cells[i].cx - cells[j].cx) ** 2 + (cells[i].cy - cells[j].cy) ** 2); }
// ================= 2. A* 寻路 =================
function runPathfinding() {
if (!cells.length) return;
resetPath();
const start = 0, goal = cells.length - 1;
document.getElementById('status').textContent = '计算 A*...';
const open = new MinHeap();
const gScore = {}, fScore = {}, parent = {};
for (let i = 0; i < cells.length; i++) { gScore[i] = Infinity; fScore[i] = Infinity; }
gScore[start] = 0; fScore[start] = heuristic(start, goal);
open.push({ i: start, f: fScore[start] });
const closed = new Set();
const steps = [];
while (!open.empty()) {
const { i: cur } = open.pop();
if (closed.has(cur)) continue;
closed.add(cur);
steps.push({ cur, open: [...open.data.map(d => d.i)], closed: [...closed] });
if (cur === goal) {
let c = goal; const p = [];
while (c !== undefined) { p.unshift(c); c = parent[c]; }
path = p; break;
}
for (const nb of graph[cur]) {
if (walls.has(nb) || closed.has(nb)) continue;
const tg = gScore[cur] + heuristic(cur, nb);
if (tg < gScore[nb]) {
parent[nb] = cur;
gScore[nb] = tg;
fScore[nb] = tg + heuristic(nb, goal);
open.push({ i: nb, f: fScore[nb] });
}
}
}
if (!path.length) {
document.getElementById('status').textContent = '未找到可行路径!请重新生成。';
draw([], []);
return;
}
animAStarSteps(steps, path);
}
function animAStarSteps(steps, finalPath) {
let frame = 0;
function tick() {
if (frame <= steps.length) {
draw(steps.slice(0, frame).map(s => s.cur), frame === steps.length ? finalPath : []);
document.getElementById('status').textContent = `A* 探索中... ${frame}/${steps.length}`;
frame++;
setTimeout(tick, 20);
} else {
animFunnel(finalPath); // A*完成,直接开始拉紧过程
}
}
tick();
}
// ================= 3. Funnel 算法核心 (漏斗拉紧) =================
// 计算二维向量叉积。结果 < 0 表示 C 在 AB 的左侧 (基于 Canvas Y轴向下的坐标系)
function crossArea(a, b, c) {
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
}
function isLeft(a, b, c) { return crossArea(a, b, c) < -1e-4; }
function isRight(a, b, c) { return crossArea(a, b, c) > 1e-4; }
// 获取两个相邻 Cell 的共享边 (Portal)
function getPortalEdge(cellA, cellB) {
let bestEdge = null;
let minDist = Infinity;
const pts = cellA.points;
// 找到 CellA 中离 CellB 中心最近的边,作为穿越传送门
for (let i = 0; i < pts.length; i++) {
const p1 = pts[i];
const p2 = pts[(i + 1) % pts.length];
const d = distToSegment(cellB.cx, cellB.cy, p1[0], p1[1], p2[0], p2[1]);
if (d < minDist) { minDist = d; bestEdge = [p1, p2]; }
}
return bestEdge;
}
function distToSegment(px, py, x1, y1, x2, y2) {
const l2 = (x2 - x1) ** 2 + (y2 - y1) ** 2;
if (l2 === 0) return (px - x1) ** 2 + (py - y1) ** 2;
let t = ((px - x1) * (x2 - x1) + (py - y1) * (y2 - y1)) / l2;
t = Math.max(0, Math.min(1, t));
return (px - (x1 + t * (x2 - x1))) ** 2 + (py - (y1 + t * (y2 - y1))) ** 2;
}
// 计算并记录 Funnel 步进动画状态
function calcFunnel(pathCells) {
const startX = cells[pathCells[0]].cx, startY = cells[pathCells[0]].cy;
const goalX = cells[pathCells[pathCells.length - 1]].cx, goalY = cells[pathCells[pathCells.length - 1]].cy;
const portals = [];
// 构建传送门列表
for (let i = 0; i < pathCells.length - 1; i++) {
const c1 = cells[pathCells[i]];
const c2 = cells[pathCells[i + 1]];
const edge = getPortalEdge(c1, c2);
// 确定传送门的左右端点。通过比较叉积来决定左右视角
const cp1 = crossArea([c1.cx, c1.cy], [c2.cx, c2.cy], edge[0]);
const cp2 = crossArea([c1.cx, c1.cy], [c2.cx, c2.cy], edge[1]);
if (cp1 < cp2) portals.push({ left: edge[0], right: edge[1] }); // 越负越在左
else portals.push({ left: edge[1], right: edge[0] });
}
// 目标点作为最终的一个“点”传送门
portals.push({ left: [goalX, goalY], right: [goalX, goalY] });
const steps = [];
const pts = [[startX, startY]];
let apex = [startX, startY];
let left = portals[0].left, right = portals[0].right;
let apexIndex = 0, leftIndex = 0, rightIndex = 0;
steps.push({ apex, left, right, portalIdx: 0, pts: [...pts] });
// 开始“拉绳子”扫描
for (let i = 1; i < portals.length; i++) {
const newLeft = portals[i].left;
const newRight = portals[i].right;
steps.push({ apex, left, right, newLeft, newRight, portalIdx: i, pts: [...pts], inspecting: true });
// 更新右边界
if (!isRight(apex, right, newRight)) { // 新边界使漏斗变窄
// 检查是否越过了左边界
if (apex[0] === right[0] && apex[1] === right[1] || !isLeft(apex, left, newRight)) {
right = newRight; rightIndex = i; // 正常收缩
} else {
// 越界了!发生折断,沿左边界绕过拐角
pts.push(left);
apex = left; apexIndex = leftIndex;
left = apex; right = apex;
leftIndex = apexIndex; rightIndex = apexIndex;
i = apexIndex; // 从新顶点重新扫描
steps.push({ apex, left, right, portalIdx: i, pts: [...pts], snap: 'left' });
continue;
}
}
// 更新左边界
if (!isLeft(apex, left, newLeft)) { // 新边界使漏斗变窄
// 检查是否越过了右边界
if (apex[0] === left[0] && apex[1] === left[1] || !isRight(apex, right, newLeft)) {
left = newLeft; leftIndex = i; // 正常收缩
} else {
// 越界了!发生折断,沿右边界绕过拐角
pts.push(right);
apex = right; apexIndex = rightIndex;
left = apex; right = apex;
leftIndex = apexIndex; rightIndex = apexIndex;
i = apexIndex; // 从新顶点重新扫描
steps.push({ apex, left, right, portalIdx: i, pts: [...pts], snap: 'right' });
continue;
}
}
steps.push({ apex, left, right, portalIdx: i, pts: [...pts] });
}
pts.push([goalX, goalY]);
steps.push({ apex, left, right, portalIdx: portals.length - 1, pts: [...pts], done: true });
return { portals, steps, finalPath: pts };
}
// 执行 Funnel 动画
function animFunnel(rawPathCells) {
document.getElementById('status').textContent = `正在准备 Funnel 拉紧算法...`;
const { portals, steps, finalPath } = calcFunnel(rawPathCells);
funnelPortals = portals;
funnelMode = true;
let frame = 0;
function tickFunnel() {
if (frame < steps.length) {
funnelState = steps[frame];
smoothedPath = funnelState.pts;
draw([], rawPathCells);
let msg = `Funnel 漏斗平滑中 (${frame}/${steps.length}) : `;
if (funnelState.snap) msg += `绳子卡住拐点,形成新顶点!`;
else if (funnelState.inspecting) msg += `评估新的传送门...`;
else msg += `收缩射线边界。`;
document.getElementById('status').textContent = msg;
frame++;
setTimeout(tickFunnel, 150); // 慢速播放,看清漏斗边界的移动
} else {
funnelState = null;
smoothedPath = finalPath;
draw([], rawPathCells);
document.getElementById('status').textContent = `寻路与平滑均已完成!原始节点: ${rawPathCells.length}个, 拉紧后关键点: ${finalPath.length}个。`;
}
}
setTimeout(tickFunnel, 800); // A*结束后稍微停顿再开始Funnel
}
function resetPath() {
path = []; explored = [];
funnelMode = false; funnelState = null; smoothedPath = []; funnelPortals = [];
draw([], []);
document.getElementById('status').textContent = '路径已重置。';
}
// ================= 4. 绘制逻辑 =================
function draw(exploredCells, pathCells) {
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = '#e5e7eb';
ctx.fillRect(0, 0, W, H);
const exploredSet = new Set(exploredCells);
const pathSet = new Set(pathCells);
// 画地图多边形
cells.forEach((cell, i) => {
if (!cell.points.length) return;
ctx.beginPath();
ctx.moveTo(cell.points[0][0], cell.points[0][1]);
for (let k = 1; k < cell.points.length; k++) ctx.lineTo(cell.points[k][0], cell.points[k][1]);
ctx.closePath();
let fill;
if (walls.has(i)) fill = '#64748b';
else if (pathSet.has(i)) fill = funnelMode ? '#e0f2fe' : '#90caf9'; // Funnel时底色变淡
else if (exploredSet.has(i)) fill = '#fff176';
else fill = '#ffffff';
ctx.fillStyle = fill;
ctx.fill();
ctx.strokeStyle = 'rgba(100,116,139,0.3)';
ctx.lineWidth = 1;
ctx.stroke();
if (walls.has(i)) {
ctx.fillStyle = 'rgba(0,0,0,0.05)';
ctx.fill();
}
});
// 如果处于 Funnel 模式,画出通过的传送门边界
if (funnelMode) {
ctx.lineWidth = 2;
ctx.setLineDash([5, 5]);
funnelPortals.forEach(p => {
ctx.beginPath();
ctx.moveTo(p.left[0], p.left[1]);
ctx.lineTo(p.right[0], p.right[1]);
ctx.strokeStyle = 'rgba(16, 185, 129, 0.4)'; // 绿色虚线
ctx.stroke();
});
ctx.setLineDash([]);
}
// 画 A* 原始路径(中心点连线)
if (pathCells.length > 1) {
ctx.beginPath();
ctx.moveTo(cells[pathCells[0]].cx, cells[pathCells[0]].cy);
for (let k = 1; k < pathCells.length; k++) ctx.lineTo(cells[pathCells[k]].cx, cells[pathCells[k]].cy);
ctx.strokeStyle = (funnelMode) ? 'rgba(239, 68, 68, 0.3)' : '#ef4444'; // 进入Funnel后变淡
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.stroke();
if (!funnelMode) {
pathCells.forEach(i => {
ctx.beginPath(); ctx.arc(cells[i].cx, cells[i].cy, 4, 0, Math.PI * 2);
ctx.fillStyle = '#b91c1c'; ctx.fill();
});
}
}
// 画 Funnel 平滑路径与射线状态
if (funnelMode && smoothedPath.length) {
// 已确定的平滑路径
ctx.beginPath();
ctx.moveTo(smoothedPath[0][0], smoothedPath[0][1]);
for (let k = 1; k < smoothedPath.length; k++) ctx.lineTo(smoothedPath[k][0], smoothedPath[k][1]);
// 如果在动画中,连线到当前的 Apex
if (funnelState && !funnelState.done) {
ctx.lineTo(funnelState.apex[0], funnelState.apex[1]);
}
ctx.strokeStyle = '#8b5cf6'; // 紫色平滑路径
ctx.lineWidth = 4;
ctx.lineJoin = 'round';
ctx.stroke();
// 绘制当前正在扫描的漏斗边界
if (funnelState && !funnelState.done) {
const { apex, left, right, newLeft, newRight, inspecting } = funnelState;
// 预判虚线射线
if (inspecting && newLeft && newRight) {
ctx.beginPath(); ctx.moveTo(apex[0], apex[1]); ctx.lineTo(newLeft[0], newLeft[1]);
ctx.strokeStyle = 'rgba(59, 130, 246, 0.3)'; ctx.lineWidth = 1; ctx.stroke();
ctx.beginPath(); ctx.moveTo(apex[0], apex[1]); ctx.lineTo(newRight[0], newRight[1]);
ctx.strokeStyle = 'rgba(239, 68, 68, 0.3)'; ctx.lineWidth = 1; ctx.stroke();
}
// 左边界射线 (蓝色)
ctx.beginPath(); ctx.moveTo(apex[0], apex[1]); ctx.lineTo(left[0], left[1]);
ctx.strokeStyle = '#3b82f6'; ctx.lineWidth = 3; ctx.stroke();
// 右边界射线 (红色)
ctx.beginPath(); ctx.moveTo(apex[0], apex[1]); ctx.lineTo(right[0], right[1]);
ctx.strokeStyle = '#ef4444'; ctx.lineWidth = 3; ctx.stroke();
// 绘制顶点Apex
ctx.beginPath(); ctx.arc(apex[0], apex[1], 6, 0, Math.PI * 2);
ctx.fillStyle = '#8b5cf6'; ctx.fill();
}
// 绘制路径经过的确切拐点
smoothedPath.forEach(p => {
ctx.beginPath(); ctx.arc(p[0], p[1], 5, 0, Math.PI * 2);
ctx.fillStyle = '#8b5cf6'; ctx.fill();
ctx.strokeStyle = '#fff'; ctx.lineWidth = 1.5; ctx.stroke();
});
}
drawMarker(cells[0].cx, cells[0].cy, '起', '#10b981');
drawMarker(cells[cells.length - 1].cx, cells[cells.length - 1].cy, '终', '#f43f5e');
}
function drawMarker(x, y, label, color) {
ctx.beginPath(); ctx.arc(x, y, 14, 0, Math.PI * 2);
ctx.fillStyle = color; ctx.fill();
ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; ctx.stroke();
ctx.fillStyle = '#fff'; ctx.font = 'bold 13px sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(label, x, y);
}
class MinHeap {
constructor() { this.data = []; }
push(v) { this.data.push(v); this._up(this.data.length - 1); }
pop() { const top = this.data[0]; const last = this.data.pop(); if (this.data.length) { this.data[0] = last; this._down(0); } return top; }
empty() { return this.data.length === 0; }
_up(i) { while (i > 0) { const p = (i - 1) >> 1; if (this.data[p].f > this.data[i].f) { [this.data[p], this.data[i]] = [this.data[i], this.data[p]]; i = p; } else break; } }
_down(i) { const n = this.data.length; while (true) { let s = i, l = 2 * i + 1, r = 2 * i + 2; if (l < n && this.data[l].f < this.data[s].f) s = l; if (r < n && this.data[r].f < this.data[s].f) s = r; if (s === i) break;[this.data[s], this.data[i]] = [this.data[i], this.data[s]]; i = s; } }
}
init();
</script>
</body>
</html>