-
Notifications
You must be signed in to change notification settings - Fork 1
/
index4.html
859 lines (756 loc) · 24.6 KB
/
index4.html
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
<html lang="en">
<meta charset="utf-8"/>
<head><title>Test Voronoï</title></head>
<body>
<h1>A* on a Constrained Delaunay triangulation algorithm implemented with Quad-Edges</h1>
<p>This example uses a refinement algorithm where we compute a giant triangle
surrounding all the sites, then insert them one by one while keeping the
triangulation.</p>
<p>The geometric predicates (inCircle and isRightOf) have not been made robust. The envelope has been left gray. </p>
<p>Clicking on a triangle displays its circumscribed
circle, it should be respect the "Modified circle criterion".</p>
<div id="draw"></div>
<script src="svg.js"></script>
<script>
// http://www.cs.cmu.edu/afs/andrew/scs/cs/15-463/2001/pub/src/a2/cell/
// https://github.com/hastebrot/jsts-dist/blob/master/src/jsts
// https://github.com/savithru-j/cdt-js
// https://doc.cgal.org/latest/Triangulation_2/index.html
//http://www.neolithicsphere.com/geodesica/doc/quad_edge_overview.htm
// GRAPH STUFF
class QuadEdge {
constructor () {
this.rot = null
this.vertex = null
this.next = null
}
get sym () {
return this.rot.rot
}
get org () {
return this.vertex
}
set org (o) {
this.vertex = o
}
get dest () {
return this.sym.org
}
set dest (d) {
this.sym.org = d
}
get invRot () {
return this.rot.sym
}
get left () {
return this.rot.vertex
}
set left (v) {
this.rot.vertex = v
}
get right () {
return this.invRot.vertex
}
get lNext () {
return this.invRot.oNext.rot
}
get lPrev () {
return this.next.sym
}
get rNext () {
return this.rot.oNext.invRot
}
get oNext () {
return this.next
}
get oPrev () {
return this.rot.next.rot
}
get dPrev () {
return this.invRot.oNext.invRot
}
get rPrev () {
return this.sym.oNext
}
}
const allEdges = []
function makeEdge (v1, v2) {
const q0 = new QuadEdge()
allEdges.push(q0)
const q1 = new QuadEdge()
const q2 = new QuadEdge()
const q3 = new QuadEdge()
q0.rot = q1
q1.rot = q2
q2.rot = q3
q3.rot = q0
q0.next = q0
q1.next = q3
q2.next = q2
q3.next = q1
q0.org = v1
q0.dest = v2
console.assert(q0.dest === v2)
console.assert(q0.org !== q0.dest, q0.org, q0.dest)
console.assert(q0.left === q0.right)
console.assert(q0.lNext === q0.rNext)
console.assert(q0.lNext === q0.sym)
console.assert(q0.oPrev === q0.oNext)
console.assert(q0.oPrev === q0)
return q0
}
function splice (a, b) {
const alpha = a.oNext.rot
const beta = b.oNext.rot
const t1 = b.oNext
const t2 = a.oNext
const t3 = beta.oNext
const t4 = alpha.oNext
a.next = t1
b.next = t2
alpha.next = t3
beta.next = t4
}
function connect (a, b) {
const e = makeEdge(a.dest, b.org)
splice(e, a.lNext)
splice(e.sym, b)
return e
}
function deleteEdge (e) {
splice(e, e.oPrev)
splice(e.sym, e.sym.oPrev)
}
function swap (e) {
const a = e.oPrev
const b = e.sym.oPrev
splice(e, a)
splice(e.sym, b)
splice(e, a.lNext)
splice(e.sym, b.lNext)
e.org = a.dest
e.dest = b.dest
}
</script>
<script>
// GEOMETRIC STUFF
function triArea (a, b, c) {
return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)
}
function ccw (a, b, c) {
return triArea(a, b, c) > 0
}
function inCircle (a, b, c, p) {
const det = (a.x * a.x + a.y * a.y) * triArea(b, c, p) -
(b.x * b.x + b.y * b.y) * triArea(a, c, p) +
(c.x * c.x + c.y * c.y) * triArea(a, b, p) -
(p.x * p.x + p.y * p.y) * triArea(a, b, c)
return det > 0
}
// check the circle of the triangle this edge is in vs the point of the symmetric triangle
function inCircleEdge (edge) {
return inCircle(edge.org, edge.rPrev.dest, edge.dest, edge.sym.rPrev.dest)
}
function circumCenter (p0, p1, p2) {
const d = 2 * (p0.x * (p1.y - p2.y) + p1.x * (p2.y - p0.y) + p2.x * (p0.y - p1.y))
const p0_mag = p0.x * p0.x + p0.y * p0.y
const p1_mag = p1.x * p1.x + p1.y * p1.y
const p2_mag = p2.x * p2.x + p2.y * p2.y
const x = (p0_mag * (p1.y - p2.y) + p1_mag * (p2.y - p0.y) + p2_mag * (p0.y - p1.y)) / d
const y = (p0_mag * (p2.x - p1.x) + p1_mag * (p0.x - p2.x) + p2_mag * (p1.x - p0.x)) / d
return {x, y}
}
function circumCircleForEdge (edge) {
return circumCircle(edge.org, edge.dest, edge.rPrev.dest)
}
function distance (v1, v2) {
const sq = v => v * v
return Math.sqrt(sq(v1.x - v2.x) + sq(v1.y - v2.y))
}
function circumCircle (a, b, c) {
const {x, y} = circumCenter(a, b, c)
const center = {x, y}
return {...center, r: distance(a, center)}
}
console.assert(inCircle({x: 1, y: 2}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 1.5, y: 1.5}))
console.assert(!inCircle({x: 1, y: 2}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 15, y: 15}))
function edgeVector (e) {
const dx = e.dest.x - e.org.x
const dy = e.dest.y - e.org.y
return {x: dx, y: dy}
}
function edgeLength (e) {
return distance(e.dest, e.org)
}
function edgeOriginBisector (e) {
const prevVector = edgeVector(e.oNext)
const prevLength = edgeLength(e.oNext)
const vector = edgeVector(e)
const length = edgeLength(e)
return {
x: 20 * (vector.x / length + prevVector.x / prevLength),
y: 20 * (vector.y / length + prevVector.y / prevLength)
}
}
function edgeNormal (e, factor = 1) {
const vector = edgeVector(e)
const length = edgeLength(e)
// noinspection JSSuspiciousNameCombination
return {x: factor * -vector.y / length, y: factor * vector.x / length}
}
function edgeDirection (e, factor = 1) {
const vector = edgeVector(e)
const length = edgeLength(e)
return {x: factor * vector.x / length, y: factor * vector.y / length}
}
function isRightOf (point, edge) {
return ccw(point, edge.dest, edge.org)
}
// one edge and 2 points, will return false if edge and points are collinear
function doesIntersect (edge, p1, p2) {
//https://stackoverflow.com/a/1968345/72637
const s1X = edge.dest.x - edge.org.x
const s1Y = edge.dest.y - edge.org.y
const s2X = p2.x - p1.x
const s2Y = p2.y - p1.y
let denominator = (-s2X * s1Y + s1X * s2Y)
if (denominator === 0)
return false
let s = (-s1Y * (edge.org.x - p1.x) + s1X * (edge.org.y - p1.y)) / denominator
let t = (s2X * (edge.org.y - p1.y) - s2Y * (edge.org.x - p1.x)) / denominator
if (!isFinite(s))
return false
if (isNaN(s))
throw new Error('Nan')
return (s >= 0 && s <= 1 && t >= 0 && t <= 1)
}
// https://stackoverflow.com/a/328110/72637
// http://bit-player.org/wp-content/extras/bph-publications/BeautifulCode-2007-Hayes.pdf
function pointIsOnSegment (p1, p2, testPoint) {
function within (a, b, candidate) {
const arr = [a, b, candidate]
arr.sort((a, b) => a - b)
return arr[1] === candidate
}
const collinear = (p2.x - p1.x) * (testPoint.y - p1.y) === (testPoint.x - p1.x) * (p2.y - p1.y)
return collinear && (p1.x !== p2.x ? within(p1.x, p2.x, testPoint.x) : within(p1.y, p2.y, testPoint.y))
}
function edgeEndsAtPoint (edge, point) {
return edge.org === point || edge.dest === point
}
function isConvex (p1, p2, p3, p4) {
const arr = [p1, p2, p3, p4]
const nextPoint = index => arr[(index + 1) % arr.length]
const edgeVector = (fromP, toP) => ({x: toP.x - fromP.x, y: toP.y - fromP.y})
const crossProductZ = (v1, v2) => v1.x * v2.y - v1.y * v2.x
const edgesCrossProducts = arr.map((p, i) => crossProductZ(edgeVector(p, nextPoint(i)), edgeVector(nextPoint(i), nextPoint(i + 1))))
edgesCrossProducts.sort((a, b) => a - b)
return Math.sign(edgesCrossProducts.shift()) * Math.sign(edgesCrossProducts.pop()) === 1
}
function isQuadAroundEdgeConvex (edge) {
return isConvex(edge.rNext.org, edge.org, edge.oNext.dest, edge.dest)
}
function locateFromEdge (vertex, edge) {
let iter = 0
let e = edge
while (true) {
iter++
if (iter > 1000) {
throw new Error('lol')
}
if (vertex === e.org || vertex === e.dest) {
break
}
if (isRightOf(vertex, e)) {
e = e.sym
} else if (!isRightOf(vertex, e.oNext)) {
e = e.oNext
} else if (!isRightOf(vertex, e.dPrev)) {
e = e.dPrev
} else {
break
}
}
return e
}
</script>
<script>
// DELAUNAY
function makeTriangle (v1, v2, v3) {
const ea = makeEdge(v1, v2)
const eb = makeEdge(v2, v3)
splice(ea.sym, eb)
const ec = makeEdge(v3, v1)
splice(eb.sym, ec)
splice(ec.sym, ea)
return ea
}
const TAN_60 = Math.sqrt(3)
/***
* This is a triangle with an horizontal base and 2 60° sides.
* minX and maxX are the abscissa at y == 0
*/
class Envelope {
constructor () {
this.minY = NaN
this.minX = NaN
this.maxX = NaN
}
addPoint (x, y) {
this.minY = isNaN(this.minY) || y < this.minY ? y : this.minY
const limits = [x - y / TAN_60, x + y / TAN_60, this.minX, this.maxX].filter(e => !isNaN(e))
limits.sort((a, b) => a - b)
this.minX = limits[0]
this.maxX = limits[limits.length - 1]
}
get apex () {
const x = (this.minX + this.maxX) / 2
return {x: x, y: Math.abs(this.minX - x) * TAN_60 + 20}
}
get botLeft () {
const y = this.minY - 20
return {x: this.minX - 20 + (y / TAN_60), y}
}
get botRight () {
const y = this.minY - 20
return {x: this.maxX + 20 - (y / TAN_60), y}
}
}
function displayAllPolygons (edge, svgGroup) {
for (let polygon of iteratePolygons(edge)) {
svgGroup.polygon(polygon.map(point => [point.x, point.y])).attr({
fill: 'blue',
'fill-opacity': 0.2,
stroke: 'white',
'stroke-width': 2,
'stroke-linejoin': 'round'
})
}
}
class PointOnSegmentError extends Error {
constructor (message, point) {
super(message)
this.point = point
}
}
/**
*
* http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.61.3862&rep=rep1&type=pdf
* https://infoscience.epfl.ch/record/100269/files/Kallmann_and_al_Geometric_Modeling_03.pdf
* @throws PointOnSegmentError every time a point is found exactly on the constraint
*/
function insertConstraint (edge, p1, p2) {
let e = locateFromEdge(p1, edge)
if (e.org !== p1)
e = e.sym
// check if there is an existing edge from P1 to P2
for (let n of getNeighbors(e)) {
if (edgeEndsAtPoint(n, p2)) {
n.constrained = true
n.sym.constrained = true
return n
}
}
while (!doesIntersect(e.rPrev, p1, p2))
e = e.oNext
const findNextCrossingEdge = (e) => doesIntersect(e.rPrev, p1, p2) && !edgeEndsAtPoint(e.rPrev, p1) && !edgeEndsAtPoint(e.rPrev, p2) ? e.rPrev : e.rPrev.rPrev
let e1 = e.rPrev.sym
const intersectingEdges = []
while (!edgeEndsAtPoint(e1, p2)) {
if (pointIsOnSegment(p1, p2, e1.org))
throw new PointOnSegmentError('point on Segment', e1.org)
if (pointIsOnSegment(p1, p2, e1.dest))
throw new PointOnSegmentError('point on Segment', e1.dest)
intersectingEdges.push(e1)
e1 = findNextCrossingEdge(e1).sym
}
let currentEdge
const newEdgesSet = new Set()
//move the intersecting edges out of the way
while ((currentEdge = intersectingEdges.shift())) {
if (isQuadAroundEdgeConvex(currentEdge)) {
swap(currentEdge)
newEdgesSet.add(currentEdge)
if (!edgeEndsAtPoint(currentEdge, p1) && !edgeEndsAtPoint(currentEdge, p2) && doesIntersect(currentEdge, p1, p2))
intersectingEdges.push(currentEdge)
} else
intersectingEdges.push(currentEdge)
}
const newEdges = [...newEdgesSet]
let constrainedEdge = null
let hasSwapped
// try to fix the triangulation
do {
hasSwapped = false
for (currentEdge of newEdges) {
if (!(edgeEndsAtPoint(currentEdge, p1) && edgeEndsAtPoint(currentEdge, p2))) {
if (isQuadAroundEdgeConvex(currentEdge) && inCircleEdge(currentEdge)) {
swap(currentEdge)
hasSwapped = true
}
} else {
currentEdge.constrained = true
currentEdge.sym.constrained = true
constrainedEdge = currentEdge
}
}
} while (hasSwapped)
return constrainedEdge
}
function insertSite (edge, vertex) {
let e = locateFromEdge(vertex, edge)
if (e.org === vertex || e.dest === vertex) {
return e
}
//TODO: is on edge
let base = makeEdge(e.org, vertex)
splice(base, e)
const startEdge = base
let i = 10
do {
base = connect(e, base.sym)
e = base.oPrev
i--
if (i <= 0)
throw Error('error')
} while (e.lNext !== startEdge && i > 0)
i = 100
do {
const t = e.oPrev
if (isRightOf(t.dest, e) && inCircle(e.org, t.dest, e.dest, vertex)) {
swap(e)
// go back and re-test the same edge with the new triangle
e = e.oPrev
} else {
if (e.oNext === startEdge) {
return base
}
e = e.oNext.lPrev
}
i--
if (i <= 0)
throw Error('error')
} while (true)
}
</script>
<script>
// A*
// yields arrays of 3 edges, grouped by face
function * iterateEdgesPerFace (startEdge, skippedVertices = new Set()) {
const markedEdges = new Set()
const edgeStack = [startEdge]
while (edgeStack.length) {
const e = edgeStack.pop()
if (markedEdges.has(e)) {
continue
}
let skipFace = false
let faceEdges = []
let faceEdge = e
do {
markedEdges.add(faceEdge)
edgeStack.push(faceEdge.sym)
if (skippedVertices.has(faceEdge.org))
skipFace = true
faceEdges.push(faceEdge)
faceEdge = faceEdge.lNext
} while (faceEdge !== e)
if (!skipFace)
yield faceEdges
}
}
function * iterateEdges (startEdge, skippedVertices = new Set()) {
for (let edgeArray of iterateEdgesPerFace(startEdge, skippedVertices))
for (let e of edgeArray)
yield e
}
function comparePoints (a, b) {
let xDiff = a.x - b.x
return xDiff !== 0 ? xDiff : a.y - b.y
}
const pointID = p => `${p.x},${p.y}`
const undirectedEdgeId = e => {
const vertices = [e.org, e.dest]
vertices.sort(comparePoints)
return `${pointID(vertices[0])}|${pointID(vertices[1])}`
}
function collectUndirectedEdges (startEdge, skippedVertices = new Set()) {
const markedEdges = {}
for (let e of iterateEdges(startEdge, skippedVertices)) {
let s = undirectedEdgeId(e)
markedEdges[s] = e
}
return markedEdges
}
function getNeighbors (edge, neighborOperator = e => e.oPrev) {
const res = []
let e = edge
do {
e = neighborOperator(e)
res.push(e)
} while (e !== edge)
return res
}
function createQueue () {
// the laziest queue implementation you'll see today
const queue = []
// some values might be inserted twice with varying priorities, so we just keep the list of who has been deleted
// it's forbidden to pass twice in the same node
const deleted = new Set()
const sortOrder = (elem1, elem2) => elem1.priority - elem2.priority
const res = {
deleted,
queue,
addToQueue: (v, priority) => {
queue.push({v, priority})
queue.sort(sortOrder)
},
getFromQueue: () => {
if (queue.length === 0)
return undefined
const val = queue.shift().v
if (deleted.has(val))
return res.getFromQueue()
deleted.add(val)
return val
},
isQueueEmpty: () => {
if (queue.length === 0)
return true
// the head of the queue could be some old deleted stuff
while (queue.length && deleted.has(queue[0]))
queue.shift()
return queue.length === 0
}
}
return res
}
//https://en.wikipedia.org/wiki/A*_search_algorithm
//https://www.youtube.com/watch?v=ySN5Wnu88nE
//https://www.redblobgames.com/pathfinding/a-star/implementation.html
// for now this is a weird navigation on the graph, where the start and end points
// are the center of one of the faces adjacent to the start and end vertex
function aStar (oneEdge, startVertex, destinationVertex) {
const nextEdge = e => e.next.sym //e => e.sym.lNext
let endEdge = locateFromEdge(destinationVertex, oneEdge)
destinationVertex = endEdge.left
circlePoint(destinationVertex, root)
let startEdge = locateFromEdge(startVertex, oneEdge)
if (startEdge.org !== startVertex)
startEdge = startEdge.sym
startEdge = startEdge.invRot
startVertex = startEdge.org
circlePoint(startVertex, root)
const heuristic = distance
const queue = createQueue()
queue.addToQueue(startEdge, 0)
const cameFrom = {[pointID(startEdge.org)]: null}
const costSoFar = {[pointID(startEdge.org)]: 0}
while (!queue.isQueueEmpty()) {
const current = queue.getFromQueue()
const currentVertexID = pointID(current.org)
if (current.org === destinationVertex)
break
let neighbors = getNeighbors(current, e => e.sym.next.sym)
for (let n of neighbors) {
const neighborVertexID = pointID(n.dest)
let edgeLength = distance(n.org, n.dest)
if (n.rot.constrained)
edgeLength = Infinity
const newCost = costSoFar[currentVertexID] + edgeLength
if (costSoFar[neighborVertexID] === undefined || newCost < costSoFar[neighborVertexID]) {
costSoFar[neighborVertexID] = newCost
const priority = newCost + heuristic(destinationVertex, n.dest)
queue.addToQueue(nextEdge(n), priority)
cameFrom[neighborVertexID] = n
}
}
}
let currentPoint = destinationVertex
const result = []
while (currentPoint !== startVertex) {
const vID = pointID(currentPoint)
const edge = cameFrom[vID]
result.unshift(edge)
currentPoint = edge.org
}
return result
}
</script>
<script>
// google: octilinear metric
function generatePoints (count, xMin, xSize, yMin, ySize) {
const getNumber = (size) => Math.floor(Math.random() * size / 25) * 25
const points = {}
while (Object.keys(points).length < count) {
const point = {x: xMin + getNumber(xSize), y: yMin + getNumber(ySize)}
points[`${point.x}|${point.y}`] = point
}
return Object.values(points)
}
const generateColor = () => '#' + ('000000' + ((1 << 24) * Math.random() | 0).toString(16)).substr(-6)
function displayEdge (e, group) {
const o = e.org
const d = e.dest
return group.line(o.x, o.y, d.x, d.y)
}
function displayPolygon (edges, group) {
group.polygon(edges.map(e => [e.org.x, e.org.y]))
}
function circlePoint (vertex, group) {
return group.circle(10).move(vertex.x - 5, vertex.y - 5).attr({'stroke-width': 1, fill: 'none'})
}
function displayEdgeCircumCircle (edge, group) {
const circleDef = circumCircleForEdge(edge)
return group.circle(circleDef.r * 2).move(circleDef.x - circleDef.r, circleDef.y - circleDef.r)
}
function * iteratePolygons (startEdge, skippedVertices = new Set()) {
for (let edgeArray of iterateEdgesPerFace(startEdge, skippedVertices)) {
yield edgeArray.map(e => e.org)
}
}
// for each face, sets its vertex as the barycenter, not really voronoi
// the external face gets a {x: Infinity, y: Infinity} vertex.
function setVoronoiVertices (startEdge, skippedVertices = new Set()) {
for (let edgeArray of iterateEdgesPerFace(startEdge, skippedVertices)) {
const x = edgeArray.reduce((acc, val) => acc + val.org.x, 0) / edgeArray.length
const y = edgeArray.reduce((acc, val) => acc + val.org.y, 0) / edgeArray.length
let p = {x, y}
if (polygonArea(edgeArray.map(e => e.org)) > 0)
p = {x: Infinity, y: Infinity}
for (let e of edgeArray)
e.left = p
}
}
function polygonArea (points) {
let sum = 0
const length = points.length
for (let i = 0; i < length; i++) {
const p1 = points[i]
const p2 = points[(i + 1) % length]
sum += (p2.x - p1.x) * (p2.y + p1.y)
}
return sum
}
let svg = SVG(document.querySelector('#draw'))
let points = [{'x': 30, 'y': 155}, {'x': 380, 'y': 180}, {'x': 305, 'y': 180}, {'x': 130, 'y': 30}, {
'x': 155,
'y': 305
}, {'x': 105, 'y': 105}, {'x': 280, 'y': 105}, {'x': 180, 'y': 230}, {'x': 80, 'y': 280}, {
'x': 255,
'y': 305
}, {'x': 255, 'y': 80}, {'x': 305, 'y': 305}, {'x': 280, 'y': 205}, {'x': 55, 'y': 155}, {
'x': 180,
'y': 55
}, {'x': 180, 'y': 30}, {'x': 380, 'y': 30}, {'x': 330, 'y': 130}, {'x': 30, 'y': 205}, {
'x': 205,
'y': 105
}, {'x': 55, 'y': 55}, {'x': 330, 'y': 280}, {'x': 30, 'y': 180}, {'x': 305, 'y': 255}, {
'x': 105,
'y': 305
}, {'x': 105, 'y': 255}, {'x': 205, 'y': 155}, {'x': 405, 'y': 280}, {'x': 405, 'y': 55}, {'x': 30, 'y': 30}]
const constraints = [[7, 26], [9, 10], [26, 15], [24, 5]]
const background = svg.group()
const root = svg.group().attr({stroke: 'red', fill: 'none', class: 'root', 'vector-effect': 'non-scaling-stroke'})
const arrowMarker = svg.marker(10, 10, function (g) {
g.path('M0,0 L10,5 0,10').attr({'fill': 'black', 'fill-opacity': 0.5})
})
const blueGroup = svg.group().attr({stroke: 'blue', fill: 'blue'})
const edgeGroup = svg.group().attr({class: 'edges', 'vector-effect': 'non-scaling-stroke'})
edgeGroup.attr({stroke: 'orange', 'stroke-width': 1.5, 'marker-end': arrowMarker})
const envelope = new Envelope()
points.forEach(({x, y}) => envelope.addPoint(x, y))
function displayPoint (p, name) {
root.line(p.x - 10, p.y - 10, p.x + 10, p.y + 10)
root.line(p.x - 10, p.y + 10, p.x + 10, p.y - 10)
root.plain(name).move(p.x, p.y)
}
let botLeft = envelope.botLeft
let botRight = envelope.botRight
let apex = envelope.apex
let ea = makeTriangle(apex, botRight, botLeft)
let i = 0
for (let vertex of points) {
displayPoint(vertex, 'V' + i)
const polygons = background.group()
for (let polygon of iteratePolygons(ea)) {
polygons.polygon(polygon.map(point => [point.x, point.y])).attr({
fill: 'blue',
'fill-opacity': 0.2,
stroke: 'white',
'stroke-width': 2,
'stroke-linejoin': 'round'
})
}
insertSite(ea, vertex)
polygons.remove()
i++
}
let skippedVertices = new Set([apex, botRight, botLeft])
// find an edge that will not be destroyed
for (let face of iterateEdgesPerFace(ea)) {
for (let edge of face)
if (!(skippedVertices.has(edge.org) || skippedVertices.has(edge.dest))) {
ea = edge
}
}
function deleteVertices (verticesSet) {
const collected = new Set()
for (let face of iterateEdgesPerFace(ea)) {
for (let edge of face) {
if (verticesSet.has(edge.org)) {
collected.add(edge)
}
}
}
for (let edge of collected) {
deleteEdge(edge)
}
}
deleteVertices(new Set([apex, botRight, botLeft]))
for (let constraint of constraints) {
let splitSegments = [[points[constraint[0]], points[constraint[1]]]]
while (splitSegments.length) {
const currentConstraint = splitSegments.shift()
try {
const constrainedEdge = insertConstraint(ea, currentConstraint[0], currentConstraint[1])
displayEdge(constrainedEdge, root).attr({stroke: 'red', 'stroke-width': '3'})
} catch (e) {
if (e instanceof PointOnSegmentError) {
splitSegments.unshift([e.point, currentConstraint[1]])
splitSegments.unshift([currentConstraint[0], e.point])
} else
throw e
}
}
}
setVoronoiVertices(ea)
let currentCircle = null
for (let polygon of iteratePolygons(ea)) {
if (polygonArea(polygon) < 0)
background.polygon(polygon.map(point => [point.x, point.y])).attr({
fill: 'blue',
'fill-opacity': 0.3,
stroke: 'white',
'stroke-width': 4,
'stroke-linejoin': 'round'
}).click(() => {
if (currentCircle)
currentCircle.remove()
const circleDef = circumCircle(...polygon)
currentCircle = root.group()
currentCircle.polygon(polygon.map(point => [point.x, point.y])).attr({
fill: 'red',
stroke: 'white',
'stroke-width': 4,
'stroke-linejoin': 'round'
})
currentCircle.circle(circleDef.r * 2).move(circleDef.x - circleDef.r, circleDef.y - circleDef.r)
})
}
const path = aStar(ea, points[23], points[13])
for (let e of path)
displayEdge(e, edgeGroup).attr({stroke: 'black'})
</script>
</body>
</html>