-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
609 lines (527 loc) · 16.1 KB
/
index.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
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Interactive Gallery</title>
<style>
#help{
/* position:absolute;
top:0;
left:0;
right:0;*/
text-align: center;
}
path.polygon {
stroke: #000;
fill: #eee;
line-width: 5px;
}
path.polygon.bad {
fill: transparent;
}
path.triangulation {
stroke: #797;
fill: transparent;
line-width: 4px;
pointer-events:none;
}
path.guard_vis {
stroke: transparent;
fill: rgba(255,0,0,0.3);
pointer-events:none;
}
circle.polygon_v {
fill: #00F;
}
circle.guard {
fill: #F00;
stroke: #000;
line-width:1px;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
margin-left:auto;
margin-right:auto;
text-align: center;
}
table {
margin-bottom: 10px;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<div id="help">
Click inside the polygon to spawn new guards.<br>
Click any existing guard or vertex to remove it.<br>
Drag any point to move it, and shift-drag on a polygon vertex to add a new vertex.<br>
Finally, click <a href="#" id="triangulater">here</a> to automatically triangulate the polygon<br>
and place guards according to a 3-coloring of the triangulation.
</div>
<br>
<table>
<tr>
<th>📗 Read polygon from file</th>
<th>💾 Save polygon to file</th>
</tr>
<tr>
<td>
<form name="upload">
<input type="file" accept=".poly" onclick="this.value=null;" id="file" name="file">
</form>
</td>
<td>
<form name="download">
<input type="button" value="Save" onclick="save_polygon()">
</form>
</td>
</tr>
</table>
<hr>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
//var polygon = [[300,300],[600, 300],[450, 450]];
var polygon = [[400,100],[700, 100],[550, 250]];
var polygon_is_good = true;
//var guards = [[450,375]];
var guards = [[550,175]];
var guard_vis = [];
var triangulation = [];
//////////////////////////
function dragmove(d,i) {
console.log("Drag");
d[0] += d3.event.dx;
d[1] += d3.event.dy;
if(d[0]<0) d[0]=0;
if(d[0]>width) d[0]=width;
if(d[1]<0) d[1]=0;
if(d[1]>height) d[1]=height;
d3.select(this).attr("transform", function(d,i){
return "translate(" + d + ")"
});
triangulation = [];
update();
}
function drag_removeguards(){
var good = check_simple(polygon) && check_clockwise(polygon);
if(!good) return;
for (var i = 0; i < guards.length; i++) {
var g = guards[i];
if(!check_inside(g,polygon)){
console.log("Guard dragged out!");
guards.splice(i,1);
i--;
}
};
update();
}
function drag_spawnpoly(d,i) {
console.log("Start");
if(d3.event.sourceEvent.shiftKey){
console.log("Drag spawn!");
var copy = d.slice();
polygon.splice(i,0,copy);
}
update();
}
var dragguard = d3.behavior.drag()
.on("drag", dragmove)
.on("dragend",drag_removeguards);
var dragpoly = d3.behavior.drag()
.on("drag", dragmove)
.on("dragstart",drag_spawnpoly)
.on("dragend",drag_removeguards);
function click_to_remove(x, sourcearray, min){
min = min | 0;
x.on("click.to_rem", function(d,i){
if (d3.event.defaultPrevented) return;
if (sourcearray.length <= min) return;
sourcearray.splice(i,1);
update();
});
}
function click_spawn_guard(x){
x.on("click.spawn", function(d,i){
if (d3.event.defaultPrevented) return;
pos = d3.mouse(svg[0][0]);
guards.push(pos);
update();
});
}
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
var polygon_path = svg.append("g").selectAll("path.polygon");
var triangulation_path = svg.append("g").selectAll("path.triangulation");
var guard_vis_path = svg.append("g").selectAll("path.guard_vis");
var polygon_verts = svg.append("g").selectAll("circle.polygon_v");
var guard_verts = svg.append("g").selectAll("circle.guard");
update();
function determinant(a,b,c,d){
return a*d - b*c;
}
function intersect_edges(a1,a2,b1,b2){
// s a1x + (1-s) a2x = t b1x + (1-t) a2x
var a = a1[0];
var b = a2[0]-a1[0];
var c = b1[0];
var d = b2[0]-b1[0];
var e = a1[1];
var f = a2[1]-a1[1];
var g = b1[1];
var h = b2[1]-b1[1];
var det = determinant(b,-d,f,-h);
var a_time = determinant(c-a,-d,g-e,-h)/det;
var b_time = determinant(b,c-a,f,g-e)/det;
return {a:a_time,b:b_time};
}
function vector_angle(x1,y1,x2,y2){
var dot = x1*x2 + y1*y2;
var cross_z = x1*y2 - y1*x2;
var angle = Math.atan2(cross_z,dot);
return angle;
}
function check_simple(poly){
// STUB: Should return true if polygon is simple
// (doesn't cross itself)
for (var i = 0; i < poly.length; i++) {
var v1 = poly[i];
var v2 = poly[(i+1)%poly.length];
var j = 0;
if(i==poly.length-1) j=1;
for (; j < i-1; j++) {
var v3 = poly[j];
var v4 = poly[(j+1)%poly.length];
var ires = intersect_edges(v1,v2,v3,v4);
if(!(ires.a < 0 || ires.a > 1 || ires.b < 0 || ires.b > 1)){
return false;
}
}
};
return true;
}
function check_clockwise(poly){
var cum_ang = 0;
for (var i = 0; i < poly.length; i++) {
var v1 = poly[i];
var v2 = poly[(i+1)%poly.length];
var v3 = poly[(i+2)%poly.length];
cum_ang += vector_angle(v2[0]-v1[0],v2[1]-v1[1],v3[0]-v2[0],v3[1]-v2[1]);
};
// console.log(cum_ang);
return cum_ang > 0;
}
function check_inside(point,poly){
// Return true if the [x,y] point is in the polygon, which
// is guaranteed to be simple.
var EPSILON = 0.000001;
var end = [point[0], 2*height];
var num_intersects = 0;
for (var i = 0; i < poly.length; i++) {
var v1 = poly[i];
var v2 = poly[(i+1)%poly.length];
// bump them if they are in line with the guard
if(v1[0]==point[0]) v1=[v1[0]+EPSILON, v1[1]];
if(v2[0]==point[0]) v2=[v2[0]+EPSILON, v2[1]];
var ires = intersect_edges(point,end,v1,v2);
if(ires.a>=0 && ires.b >= 0 && ires.b < 1){
num_intersects++;
}
};
// console.log(num_intersects);
return (num_intersects%2) == 1;
}
function generate_guard_vis(guard,poly){
// STUB: Given a [x,y] guard position (guaranteed inside the polygon),
// should return a polygon of the form
// [[x1,y1],[x2,y2],...]
// that represents the guard's visibility as a simple,
// clockwise-oriented polygon
var visPoly = [];
var vertexAngle = [];
for(var i = 0; i < poly.length; i++) {
vertexAngle.push([poly[i],vector_angle(poly[0][0]-guard[0],poly[0][1]-guard[1],
poly[i][0]-guard[0],poly[i][1]-guard[1]),i]);
}
vertexAngle.sort(function(a,b){return a[1]-b[1]});
var vertexByAngle = [];
for(var i = 0; i < vertexAngle.length;i++) {
vertexByAngle.push([vertexAngle[i][0],vertexAngle[i][2]]);
}
for(var i = 0; i < vertexByAngle.length;i++) {
var trackVertex = Infinity;
var guardRay = vertexByAngle[i][0];
var addForward = false;
var addBackward = false;
var polyIndex = vertexByAngle[i][1];
console.log(polyIndex);
console.log((polyIndex-1+poly.length)%poly.length);
var ang1 = vector_angle(guardRay[0]-guard[0],guardRay[1]-guard[1],
poly[(polyIndex-1+poly.length)%poly.length][0]-poly[polyIndex][0],
poly[(polyIndex-1+poly.length)%poly.length][1]-poly[polyIndex][1]);
var ang2 = vector_angle(guardRay[0]-guard[0],guardRay[1]-guard[1],
poly[(polyIndex+1)%poly.length][0]-poly[polyIndex][0],
poly[(polyIndex+1)%poly.length][1]-poly[polyIndex][1]);
for(var j = 0; j < poly.length; j++) {
var v1 = poly[j];
var v2 = poly[(j+1)%poly.length];
if(v1 === vertexByAngle[i][0] || v2 === vertexByAngle[i][0]) {
continue;
}
var intersection = intersect_edges(guard,guardRay,v1,v2);
if((intersection.a > 0) &&(intersection.b > 0) && (intersection.b < 1)) {
if(intersection.a < trackVertex) {
trackVertex = intersection.a
}
}
}
if(trackVertex < 1) {
visPoly.push([trackVertex*(guardRay[0]-guard[0])+guard[0],
trackVertex*(guardRay[1]-guard[1])+guard[1]]);
}
else if((ang1 > 0) && (ang2 > 0)) {
visPoly.push([trackVertex*(guardRay[0]-guard[0])+guard[0],
trackVertex*(guardRay[1]-guard[1])+guard[1]]);
visPoly.push(guardRay);
}
else if((ang1 < 0) && (ang2 < 0)) {
visPoly.push(guardRay);
visPoly.push([trackVertex*(guardRay[0]-guard[0])+guard[0],
trackVertex*(guardRay[1]-guard[1])+guard[1]]);
}
else if((ang1 > 0) === (ang2 < 0)) {
visPoly.push(guardRay);
}
}
return visPoly;
}
function trim_ear(poly){
// Returns [ear, newPoly] where ear is a triangle
// and newPoly is poly with the ear removed
var ear = [];
var newPoly = [];
// The case where the ear is [poly[0], poly[1], poly[length-1]]
// is awkward. Luckily, the polygon has two ears, so we can
// just avoid checking this triangle. This means the for loop
// doesn't hit the first and last elements.
for (var i = 1; i < poly.length - 1; i++) {
var maybe_ear = [];
maybe_ear.push(poly[i - 1]); // Left corner
maybe_ear.push(poly[i]); // Ear tip
maybe_ear.push(poly[i + 1]);; // Right corner
var maybe_ear_angle = vector_angle(
poly[i][0] - poly[i-1][0], poly[i][1] - poly[i-1][1],
poly[i+1][0] - poly[i][0], poly[i+1][1] - poly[i][1]);
// Check whether the candidate is actually an ear.
for (var j = 0; j < poly.length; j++) {
// If a vertex is inside the ear candidate and
// it does not belong to the ear candidate OR
// if we have an "inverse ear" we need to break
// and try a new candidate ear
if ((j !== i - 1 &&
j !== i &&
j !== i + 1 &&
check_inside(poly[j], maybe_ear)) ||
maybe_ear_angle < 0) {
break;
}
}
if (j === poly.length) {
// If we get here, the candidate is an ear.
ear = maybe_ear;
newPoly = poly.slice();
newPoly.splice(i, 1); // Remove the ear
return [ear, newPoly];
}
}
console.log("not returdnre");
}
function triangulate_and_color(poly){
// Returns [t, colorDict] where t is a set of
// triangles and colorDict is a mapping of
// colors to vertices of poly
var copy = poly.slice();
var ear_stack = [];
var colorDict = {};
var t = [];
// Trim ears and put them on a stack
while (copy.length > 2) {
var trimmed = trim_ear(copy);
ear_stack.push(trimmed[0]);
copy = trimmed[1];
}
t = ear_stack.slice();
// Color the first triangle arbitrarily
var earToColor = ear_stack.pop();
for (var i = 0; i < 3; i++) {
colorDict[earToColor[i]] = i;
}
// Pop ears, color them, put the vertices in the dictionary
while (ear_stack.length > 0) {
// colorTracker[i] is true if color i has been used
var colorTracker = [false, false, false];
var newlyAddedVertex = [];
earToColor = ear_stack.pop();
for (var i = 0; i < 3; i++) {
if (earToColor[i] in colorDict) {
colorTracker[colorDict[earToColor[i]]] = true;
}
else {
newlyAddedVertex = earToColor[i];
}
}
// The missing color will be the only false left in the array
colorDict[newlyAddedVertex] = colorTracker.indexOf(false);
}
return [t, colorDict];
}
function minimal_color(colorDict) {
// Returns the int representing the least frequently-used
// vertex color in colorDict
var colorCount = [0, 0, 0];
for (var i in colorDict) {
colorCount[colorDict[i]]++;
}
return colorCount.indexOf(Math.min.apply(Math, colorCount));
}
function generate_triangulation_and_guard_pos(poly){
// Triangulate the polygon, place guards, and return
// [t, g] where t is an array of triangles
// [[x1,y1],[x2,y2],[x3,y3]]
// and g is an array of points [x,y]
var t_and_c = triangulate_and_color(poly);
var t = t_and_c[0];
var c = t_and_c[1];
var g = [];
// Place guards on the vertices of least frequent color
var guardColor = minimal_color(t_and_c[1]);
for (var i = 0; i < poly.length; i++) {
var point = poly[i];
// Figure out how to bump the guard position to avoid
// guards exactly on vertices
var prevVertex = poly[(i - 1 + poly.length)%poly.length];
var nextVertex = poly[(i + 1)%poly.length];
var bumpAngle = vector_angle(point[0] - prevVertex[0], point[1] - prevVertex[1],
nextVertex[0] - point[0], nextVertex[1] - point[1]);
bumpAngle = (bumpAngle + Math.PI)/2;
var baseAngle = Math.atan2(point[1] - prevVertex[1], point[0] - prevVertex[0]);
console.log("Baseangle is ", baseAngle);
bumpAngle += baseAngle;
console.log("bumpAngle is ", bumpAngle);
var guardPoint = [point[0] + Math.cos(bumpAngle), point[1] + Math.sin(bumpAngle)];
console.log("guardpoint is ", guardPoint);
if (c[point] === guardColor) {
g.push(guardPoint);
}
}
return [t,g];
};
document.getElementById("triangulater").addEventListener("click", function(){
t_g = generate_triangulation_and_guard_pos(polygon);
triangulation = t_g[0];
guards = t_g[1];
update();
});
function update(){
polygon_is_good = check_simple(polygon) && check_clockwise(polygon);
if(polygon_is_good){
guard_vis = [];
for (var i = 0; i < guards.length; i++) {
var guard = guards[i];
if(check_inside(guard,polygon)){
guard_vis.push(generate_guard_vis(guard,polygon));
}
}
}else{
guard_vis = [];
}
redraw();
}
function redraw(){
polygon_path = polygon_path.data([polygon]);
polygon_path.exit().remove();
polygon_path.enter().append("path").attr("class","polygon");
polygon_path.attr("d", poly_d_fn)
.call(click_spawn_guard);
if(polygon_is_good){
polygon_path.attr("class", "polygon");
}else{
polygon_path.attr("class", "polygon bad");
}
triangulation_path = triangulation_path.data(triangulation);
triangulation_path.exit().remove();
triangulation_path.enter().append("path").attr("class","triangulation");
triangulation_path.attr("d", poly_d_fn);
guard_vis_path = guard_vis_path.data(guard_vis);
guard_vis_path.exit().remove();
guard_vis_path.enter().append("path").attr("class","guard_vis");
guard_vis_path.attr("d", poly_d_fn);
polygon_verts = polygon_verts.data(polygon);
polygon_verts.exit().remove();
polygon_verts.enter().append("circle");
polygon_verts.attr("class","polygon_v")
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 6)
.call(dragpoly).call(click_to_remove,polygon,3);
guard_verts = guard_verts.data(guards);
guard_verts.exit().remove();
guard_verts.enter().append("circle");
guard_verts.attr("class","guard")
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 4)
.call(dragguard).call(click_to_remove,guards);
}
function poly_d_fn(d) {
return "M" + d.join("L") + "Z";
}
////////
// Fires whenever file is uploaded.
document.getElementById('file').onchange = function() {
console.log("Reading polygon from file...");
if (this.files.length == 1) {
var file = this.files[0];
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
var poly_and_guards = evt.target.result.split("#");
polygon = JSON.parse(poly_and_guards[0]);
guards = JSON.parse(poly_and_guards[1]);
update();
}
reader.onerror = function (evt) {
console.log("Error reading file!")
}
}
};
// Fires whenever "Save" button is clicked
function save_polygon() {
console.log("Saving polygon and guards...");
var text = JSON.stringify(polygon) + "#" + JSON.stringify(guards);
download(text, "polygon.poly", "text");
}
// Function to download data to a file
// Src: https://stackoverflow.com/questions/13405129/javascript-create-and-save-file
function download(data, filename, type) {
var file = new Blob([data], {type: type});
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
</script>
</body>
</html>