-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
1212 lines (1162 loc) · 50.3 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
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
<html>
<title>Circle-Squaring</title>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
</head>
<body>
<canvas id="myCanvas"></canvas>
<p>
<button type="button" onclick="saveSolution()">Save solution</button>
<button type="button" onclick="loadSolution()">Load solution</button><br>
<textarea type="text" id="data" cols="100" rows="10"></textarea>
<script>
// ======================================
// utility functions
function crossProduct2D( v, w ) { return v.x*w.y - v.y*w.x; }
// --------------------------------------
function add( a, b ) { return new Point2D( a.x + b.x, a.y + b.y ); }
// --------------------------------------
function sub( a, b ) { return new Point2D( a.x - b.x, a.y - b.y ); }
// --------------------------------------
function sqr( x ) { return x * x }
// --------------------------------------
function dist2( v, w ) { return sqr(v.x - w.x) + sqr(v.y - w.y) }
// --------------------------------------
function distToSegmentSquared( p, v, w ) {
var l2 = dist2(v, w);
if (l2 == 0) return dist2(p, v);
var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
if (t < 0) return dist2(p, v);
if (t > 1) return dist2(p, w);
return dist2(p, { x: v.x + t * (w.x - v.x),
y: v.y + t * (w.y - v.y) });
}
// --------------------------------------
function distToSegment( p, v, w ) { return Math.sqrt(distToSegmentSquared(p, v, w)); }
// --------------------------------------
function lineSegmentsIntersect( p, p2, q, q2 ) {
// two line segments: [p,p2] and [q,q2] - do they intersect?
// http://stackoverflow.com/a/565282/126823
var r = sub(p2, p);
var s = sub(q2, q);
var uNumerator = crossProduct2D(sub(q, p), r);
var denominator = crossProduct2D(r, s);
if( uNumerator == 0 && denominator == 0 ) {
// colinear, so do they overlap?
return ((q.x - p.x < 0) != (q.x - p2.x < 0) != (q2.x - p.x < 0) != (q2.x - p2.x < 0)) ||
((q.y - p.y < 0) != (q.y - p2.y < 0) != (q2.y - p.y < 0) != (q2.y - p2.y < 0));
}
if( denominator == 0 ) {
// lines are parallel
return false;
}
var u = uNumerator / denominator;
var t = crossProduct2D(sub(q, p), s) / denominator;
return (t >= 0) && (t <= 1) && (u >= 0) && (u <= 1);
}
// --------------------------------------
function dot( a, b ) {
return a.x * b.x + a.y * b.y;
}
// --------------------------------------
function angleBetweenTwoVectors( a, b ) {
return Math.acos( dot( a, b ) / ( a.len() * b.len() ) );
}
// ======================================
// Point2D class
function Point2D( x, y ) {
this.x = x;
this.y = y;
};
// --------------------------------------
Point2D.prototype.add = function( p ) {
this.x += p.x;
this.y += p.y;
return this;
};
// --------------------------------------
Point2D.prototype.sub = function( p ) {
this.x -= p.x;
this.y -= p.y;
return this;
};
// --------------------------------------
Point2D.prototype.mul = function( f ) {
this.x *= f;
this.y *= f;
return this;
};
// --------------------------------------
Point2D.prototype.div = function( f ) {
this.x /= f;
this.y /= f;
return this;
};
// --------------------------------------
Point2D.prototype.dist = function( p ) {
return Math.sqrt( sqr( this.x - p.x ) + sqr( this.y - p.y ) );
};
// --------------------------------------
Point2D.prototype.len = function() {
return Math.sqrt( sqr( this.x ) + sqr( this.y ) );
}
// --------------------------------------
Point2D.prototype.normalize = function() {
return this.div( this.len() );
};
// ======================================
// Transform class
function Transform( r, p ) {
this.rotate = r; // radians
this.translate = new Point2D( p.x, p.y ); // Point2D
};
// --------------------------------------
Transform.prototype.apply = function( p ) {
return new Point2D( p.x * Math.cos( this.rotate ) - p.y * Math.sin( this.rotate ) + this.translate.x,
p.x * Math.sin( this.rotate ) + p.y * Math.cos( this.rotate ) + this.translate.y );
};
// --------------------------------------
Transform.prototype.applyInverse = function( p ) {
return new Point2D( ( p.x - this.translate.x ) * Math.cos( -this.rotate ) - ( p.y - this.translate.y ) * Math.sin( -this.rotate ),
( p.x - this.translate.x ) * Math.sin( -this.rotate ) + ( p.y - this.translate.y ) * Math.cos( -this.rotate ) );
};
// ======================================
// Polygon class
function Polygon() {
this.points = new Array(); // a list of Point2D's
};
// --------------------------------------
Polygon.prototype.drawPath = function( ctx ) {
if( this.points.length == 0 )
return;
ctx.beginPath();
ctx.moveTo( this.points[0].x, this.points[0].y );
for( var i = 1; i < this.points.length; ++i )
ctx.lineTo( this.points[i].x, this.points[i].y );
ctx.closePath();
};
// --------------------------------------
Polygon.prototype.getArea = function() {
var area=0.0;
var i, j = this.points.length-1;
for( i = 0; i < this.points.length; ++i )
{
area += ( this.points[j].x + this.points[i].x ) * ( this.points[j].y - this.points[i].y );
j = i;
}
return area * 0.5;
};
// --------------------------------------
Polygon.prototype.getCentroid = function() {
var centroid = new Point2D( 0, 0 );
for( var i = 0; i < this.points.length; ++i )
centroid.add( this.points[ i ] );
return centroid.div( this.points.length );
};
// --------------------------------------
function getCircle( center, radius, n )
{
var poly = new Polygon();
for( var i = 0; i < n; ++i )
{
poly.points[i] = new Point2D( center.x + radius * Math.cos( i * 2.0 * Math.PI / n ),
center.y - radius * Math.sin( i * 2.0 * Math.PI / n ) );
}
return poly;
};
// --------------------------------------
Polygon.prototype.contains = function( p ) {
var c = false;
var i, j;
var vertxi,vertyi,vertxj,vertyj;
for( i = 0, j = this.points.length-1; i < this.points.length; j = i++ )
{
vertxi = this.points[i].x;
vertyi = this.points[i].y;
vertxj = this.points[j].x;
vertyj = this.points[j].y;
if ( ((vertyi>p.y) != (vertyj>p.y)) && (p.x < (vertxj-vertxi) * (p.y-vertyi) / (vertyj-vertyi) + vertxi) )
{
c = !c;
}
}
return c;
};
// --------------------------------------
Polygon.prototype.doesLineSegmentIntersect = function( p, p2 ) {
for( var i = 0; i < this.points.length; ++i )
{
var q = this.points[ i ];
var q2 = this.points[ (i+1)%this.points.length ];
if( lineSegmentsIntersect( p, p2, q, q2 ) )
return true;
}
return false;
};
// --------------------------------------
var PolygonRelationEnum = Object.freeze ({ disjoint: {}, contained: {}, containing: {}, intersecting: {} });
// --------------------------------------
Polygon.prototype.getPolygonRelationWith = function( poly ) {
for( var i = 0; i < this.points.length; ++i )
{
var p = this.points[ i ];
var p2 = this.points[ (i+1)%this.points.length ];
for( var j = 0; j < poly.points.length; ++j )
{
var q = poly.points[ j ];
var q2 = poly.points[ (j+1)%poly.points.length ];
if( lineSegmentsIntersect( p, p2, q, q2 ) )
return PolygonRelationEnum.intersecting;
}
}
if( poly.contains( this.points[0] ) )
return PolygonRelationEnum.contained;
if( this.contains( poly.points[0] ) )
return PolygonRelationEnum.containing;
return PolygonRelationEnum.disjoint;
};
// --------------------------------------
Polygon.prototype.getTransformed = function( t ) {
var poly = new Polygon();
for( var iPt = 0; iPt < this.points.length; ++iPt )
poly.points[ iPt ] = t.apply( this.points[ iPt ] );
return poly;
};
// --------------------------------------
Polygon.prototype.isPointNearEdge = function( p, tol ) {
for( var iPt = 0; iPt < this.points.length; ++iPt )
if( distToSegment( p, this.points[iPt], this.points[ (iPt+1)%this.points.length ] ) < tol )
return true;
return false;
};
// --------------------------------------
Polygon.prototype.getNormal = function( iPt ) {
// return average of two neighboring edge normals
var a = this.points[ (iPt+this.points.length-1)%this.points.length ];
var b = this.points[ iPt ];
var c = this.points[ (iPt+1)%this.points.length ];
var e1 = sub( b, a );
var en1 = new Point2D( -e1.y, e1.x ).normalize();
var e2 = sub( c, b );
var en2 = new Point2D( -e2.y, e2.x ).normalize();
var n = add( en1, en2 ).normalize();
return n;
};
// --------------------------------------
Polygon.prototype.isSelfIntersecting = function() {
// does any line segment cross any other?
for( var iPt = 0; iPt < this.points.length; ++iPt )
{
var iP1 = iPt;
var iP2 = (iPt+1)%this.points.length;
var p1 = this.points[ iP1 ];
var p2 = this.points[ iP2 ];
for( var iPt2 = 0; iPt2 < iPt-1; ++iPt2 )
{
var iQ1 = iPt2;
var iQ2 = (iPt2+1)%this.points.length;
if( iQ1 == iP2 || iQ2 == iP1 )
continue; // neighboring edges, ignore
var q1 = this.points[ iQ1 ];
var q2 = this.points[ iQ2 ];
if( lineSegmentsIntersect( p1, p2, q1, q2 ) )
return true;
}
}
return false;
};
// ======================================
// Piece class
// --------------------------------------
var PieceStateEnum = Object.freeze ({ inactive: {}, highlighted: {}, selected: {}, translating: {}, vertexDragging: {}, rotating: {} });
// --------------------------------------
function Piece() {
this.atOrigin = new Polygon(); // canonical polygon with centroid at the origin
this.originToTarget = new Array(); // a Transform for each target
this.state = PieceStateEnum.inactive;
this.iActiveVertex = -1;
this.whichTargetSelected = -1;
this.draggingPoint = null;
this.hue = Math.random() * 360.0;
this.vertexRadius = 5;
};
// --------------------------------------
Piece.prototype.isSelected = function() {
return this.state != PieceStateEnum.inactive && this.state != PieceStateEnum.highlighted;
}
// --------------------------------------
Piece.prototype.draw = function( ctx ) {
// draw the pieces on each target
ctx.strokeStyle = "rgb(0,0,0)";
ctx.lineWidth = 1;
for(var iTarget = 0; iTarget < this.originToTarget.length; ++iTarget )
{
ctx.save();
if( this.state != PieceStateEnum.inactive )
ctx.fillStyle = "hsla("+this.hue+",100%,50%,0.8)";
else
ctx.fillStyle = "hsla("+this.hue+",80%,50%,0.3)";
ctx.translate( this.originToTarget[ iTarget ].translate.x, this.originToTarget[ iTarget ].translate.y );
ctx.rotate( this.originToTarget[ iTarget ].rotate );
this.atOrigin.drawPath( ctx );
ctx.fill();
if( this.isSelected() )
{
ctx.stroke();
// draw vertex handles
ctx.fillStyle = "rgba(0,0,0,0.4)";
for( var iVert = 0; iVert < this.atOrigin.points.length; ++iVert ) {
ctx.beginPath();
ctx.arc( this.atOrigin.points[ iVert ].x, this.atOrigin.points[ iVert ].y, this.vertexRadius, 0, 2*Math.PI );
ctx.fill();
if( this.state == PieceStateEnum.vertexDragging && this.iActiveVertex == iVert )
ctx.stroke();
ctx.closePath();
}
}
ctx.restore();
}
// draw the cursor
if( this.state == PieceStateEnum.rotating ) {
// draw a broken circle to show that piece can be rotated like this
ctx.strokeStyle = "rgba(0,0,0,0.2)";
ctx.lineWidth = this.vertexRadius;
var arcRadius = this.vertexRadius*2;
ctx.beginPath();
var pOnTarget = this.originToTarget[ this.whichTargetSelected ].apply( this.draggingPoint );
ctx.arc( pOnTarget.x, pOnTarget.y, arcRadius, 0, 1.8 * Math.PI );
ctx.stroke();
ctx.closePath();
// also draw the center of rotation
var center = this.originToTarget[ this.whichTargetSelected ].apply( new Point2D( 0, 0 ) );
ctx.strokeStyle = "rgba(0,0,0,1)";
ctx.lineWidth = 1;
var crossWidth = this.vertexRadius/2;
ctx.beginPath();
ctx.moveTo( center.x - crossWidth, center.y )
ctx.lineTo( center.x + crossWidth, center.y )
ctx.moveTo( center.x, center.y - crossWidth )
ctx.lineTo( center.x, center.y + crossWidth )
ctx.stroke();
ctx.closePath();
}
else if( this.state == PieceStateEnum.translating || this.state == PieceStateEnum.highlighted ) {
// draw a cross to show that piece can be moved like this
ctx.strokeStyle = "rgba(0,0,0,0.2)";
ctx.lineWidth = this.vertexRadius;
var crossWidth = this.vertexRadius*2;
ctx.beginPath();
ctx.moveTo( this.draggingPoint.x - crossWidth, this.draggingPoint.y )
ctx.lineTo( this.draggingPoint.x + crossWidth, this.draggingPoint.y )
ctx.moveTo( this.draggingPoint.x, this.draggingPoint.y - crossWidth )
ctx.lineTo( this.draggingPoint.x, this.draggingPoint.y + crossWidth )
ctx.stroke();
ctx.closePath();
}
};
// --------------------------------------
Piece.prototype.getPolygonOnTarget = function( iTarget ) {
return this.atOrigin.getTransformed( this.originToTarget[ iTarget ] ); // TODO: cache this, only update when needed
};
// --------------------------------------
Piece.prototype.recenter = function() {
var center = this.atOrigin.getCentroid();
for( var iPt = 0; iPt < this.atOrigin.points.length; ++iPt )
this.atOrigin.points[ iPt ].sub( center );
for( var iTarget = 0; iTarget < this.originToTarget.length; ++iTarget )
this.originToTarget[ iTarget ].translate = this.originToTarget[ iTarget ].apply( center );
};
// --------------------------------------
Piece.prototype.onMouseMove = function( mousePos ) {
// selected -> selected, translating, rotating or vertexDragging
if( this.isSelected() )
{
for( var iTarget = 0; iTarget < this.originToTarget.length; ++iTarget )
{
var pAtOrigin = this.originToTarget[ iTarget ].applyInverse( mousePos );
// in position for vertex dragging?
for( var iVert = 0; iVert < this.atOrigin.points.length; ++iVert ) {
if( pAtOrigin.dist( this.atOrigin.points[ iVert ] ) < this.vertexRadius ) {
this.state = PieceStateEnum.vertexDragging;
this.iActiveVertex = iVert;
this.draggingPoint = pAtOrigin;
this.whichTargetSelected = iTarget;
return;
}
}
// in position for rotating the piece?
if( this.atOrigin.isPointNearEdge( pAtOrigin, this.vertexRadius*2 ) ) {
this.state = PieceStateEnum.rotating;
this.draggingPoint = pAtOrigin;
this.whichTargetSelected = iTarget;
return;
}
// in position for translating the piece?
if( this.atOrigin.contains( pAtOrigin ) ) {
this.state = PieceStateEnum.translating;
this.draggingPoint = mousePos;
this.whichTargetSelected = iTarget;
return;
}
}
this.state = PieceStateEnum.selected;
this.whichTargetSelected = -1;
return;
}
// inactive or highlighted
for( var iTarget = 0; iTarget < this.originToTarget.length; ++iTarget )
{
var pAtOrigin = this.originToTarget[ iTarget ].applyInverse( mousePos );
if( this.atOrigin.contains( pAtOrigin ) )
{
this.state = PieceStateEnum.highlighted;
this.draggingPoint = mousePos;
this.whichTargetSelected = iTarget;
return;
}
}
this.state = PieceStateEnum.inactive;
this.whichTargetSelected = -1;
};
// --------------------------------------
Piece.prototype.onMouseLeftDown = function( mousePos ) {
switch( this.state )
{
case PieceStateEnum.selected:
this.state = PieceStateEnum.inactive;
return false;
case PieceStateEnum.highlighted:
this.state = PieceStateEnum.translating;
return true; // no other piece should get this mouse click
case PieceStateEnum.inactive:
return false;
default:
return true; // translating/rotating/vertexDraggging is happening, no other piece should get this mouse click
}
};
// --------------------------------------
Piece.prototype.onMouseLeftDrag = function( mousePos ) {
switch( this.state )
{
case PieceStateEnum.vertexDragging:
var pAtOrigin = this.originToTarget[ this.whichTargetSelected ].applyInverse( mousePos );
this.atOrigin.points[ this.iActiveVertex ].add( sub( pAtOrigin, this.draggingPoint ) );
this.recenter();
this.draggingPoint = this.originToTarget[ this.whichTargetSelected ].applyInverse( mousePos ); // need to recompute because transform has changed
break;
case PieceStateEnum.translating:
this.originToTarget[ this.whichTargetSelected ].translate.add( sub( mousePos, this.draggingPoint ) );
this.draggingPoint = mousePos;
break;
case PieceStateEnum.rotating:
var pAtOrigin = this.originToTarget[ this.whichTargetSelected].applyInverse( mousePos );
this.originToTarget[ this.whichTargetSelected ].rotate += Math.atan2( pAtOrigin.y, pAtOrigin.x ) - Math.atan2( this.draggingPoint.y, this.draggingPoint.x );
this.draggingPoint = this.originToTarget[ this.whichTargetSelected].applyInverse( mousePos ); // need to recompute because transform has changed
break;
}
};
// --------------------------------------
Piece.prototype.removeVertex = function( iPt ) {
this.atOrigin.points.splice( iPt, 1 );
if( this.state == PieceStateEnum.vertexDragging ) {
if( this.iActiveVertex == iPt ) {
this.state = PieceStateEnum.selected;
this.iActiveVertex = -1;
}
else if( this.iActiveVertex > iPt ) {
this.iActiveVertex--;
}
}
};
// --------------------------------------
Piece.prototype.subdivide = function( minEdgeLength ) {
var newPoints = new Array();
var newActiveVertex = -1;
for( var iOldPt = 0; iOldPt < this.atOrigin.points.length; ++iOldPt )
{
newPoints.push( this.atOrigin.points[ iOldPt ] );
if( this.state == PieceStateEnum.vertexDragging && this.iActiveVertex == iOldPt )
newActiveVertex = newPoints.length-1;
if( this.atOrigin.points[ iOldPt ].dist( this.atOrigin.points[ (iOldPt+1)%this.atOrigin.points.length ] ) > minEdgeLength )
newPoints.push( add( this.atOrigin.points[ iOldPt ], this.atOrigin.points[ (iOldPt+1)%this.atOrigin.points.length ] ).div( 2.0 ) );
}
if( this.state == PieceStateEnum.vertexDragging )
this.iActiveVertex = newActiveVertex;
this.atOrigin.points = newPoints;
};
// --------------------------------------
Piece.prototype.removeVerticesCloserThan = function( minEdgeLength ) {
do {
var removedOne = false;
for( var iPt = 0; iPt < this.atOrigin.points.length; ++iPt )
{
if( this.atOrigin.points[ iPt ].dist( this.atOrigin.points[ (iPt+1)%this.atOrigin.points.length ] ) < minEdgeLength ) {
this.removeVertex( iPt );
removedOne = true;
break;
}
}
} while( removedOne );
};
// --------------------------------------
Piece.prototype.removeVerticesStraighterThan = function( minAngle ) {
do {
var removedOne = false;
for( var iPt = 0; iPt < this.atOrigin.points.length; ++iPt )
{
var edge1 = sub( this.atOrigin.points[ iPt ], this.atOrigin.points[ (iPt+1)%this.atOrigin.points.length ] );
var edge2 = sub( this.atOrigin.points[ (iPt+this.atOrigin.points.length-1)%this.atOrigin.points.length ], this.atOrigin.points[ iPt ] );
if( angleBetweenTwoVectors( edge1, edge2 ) < minAngle ) {
this.removeVertex( iPt );
removedOne = true;
break;
}
}
} while( removedOne );
};
// --------------------------------------
Piece.prototype.removeSelfIntersectingVertices = function() {
// does any line segment cross any other?
for( var iPt = this.atOrigin.points.length-1; iPt >= 0; --iPt )
{
var iP1 = iPt;
var iP2 = (iPt+1)%this.atOrigin.points.length;
var p1 = this.atOrigin.points[ iP1 ];
var p2 = this.atOrigin.points[ iP2 ];
for( var iPt2 = 0; iPt2 < iPt-1; ++iPt2 )
{
var iQ1 = iPt2;
var iQ2 = (iPt2+1)%this.atOrigin.points.length;
if( iQ1 == iP2 || iQ2 == iP1 )
continue; // neighboring edges, ignore
var q1 = this.atOrigin.points[ iQ1 ];
var q2 = this.atOrigin.points[ iQ2 ];
if( lineSegmentsIntersect( p1, p2, q1, q2 ) ) {
this.removeVertex( iPt );
break;
}
}
}
};
// ======================================
// Button class
function Button( label, id, x, y, ctx ) {
this.polygon = new Polygon();
this.shadowPolygon = new Polygon();
this.label = label;
this.id = id;
this.isEnabled = false;
this.isPressed = false;
// initialise a rectangle around the text
this.fontHeight = 14;
ctx.font = this.fontHeight + "px Arial";
var textbox = ctx.measureText( label );
var pad = 5;
var shadowOffset = 4;
this.polygon.points[0] = new Point2D( x, y - this.fontHeight/2 - pad );
this.polygon.points[1] = new Point2D( x + textbox.width + pad*2, y - this.fontHeight/2 - pad );
this.polygon.points[2] = new Point2D( x + textbox.width + pad*2, y + this.fontHeight/2 + pad*2 );
this.polygon.points[3] = new Point2D( x, y + this.fontHeight/2 + pad*2 );
this.textPos = new Point2D( this.polygon.points[3].x + pad, this.polygon.points[3].y - pad*2 )
// make a shadow below and to the right
for( var i = 0; i < this.polygon.points.length; ++i )
this.shadowPolygon.points[ i ] = add( this.polygon.points[ i ], new Point2D( shadowOffset, shadowOffset ) );
};
// --------------------------------------
Button.prototype.getWidth = function() {
return this.polygon.points[1].x - this.polygon.points[0].x;
};
// --------------------------------------
Button.prototype.setWidth = function( width ) {
var deltaWidth = width - this.getWidth();
this.polygon.points[1].x += deltaWidth;
this.polygon.points[2].x += deltaWidth;
this.shadowPolygon.points[1].x += deltaWidth;
this.shadowPolygon.points[2].x += deltaWidth;
};
// --------------------------------------
Button.prototype.draw = function( ctx ) {
this.shadowPolygon.drawPath( ctx );
ctx.fillStyle = "rgba(0,0,0,0.2)";
ctx.fill();
this.polygon.drawPath( ctx );
if( !this.isEnabled )
ctx.fillStyle = "rgb(230,230,230)";
else if( this.isPressed )
ctx.fillStyle = "rgb(255,255,255)";
else
ctx.fillStyle = "rgb(111,202,255)";
ctx.fill();
ctx.font = this.fontHeight + "px Arial";
if( this.isEnabled )
ctx.fillStyle = "rgb(0,0,0)";
else
ctx.fillStyle = "rgb(200,200,200)";
ctx.fillText( this.label, this.textPos.x, this.textPos.y );
};
// --------------------------------------
Button.prototype.onMouseLeftDown = function( mousePos ) {
if( !this.isEnabled )
return false;
if( this.polygon.contains( mousePos ) ) {
this.isPressed = true;
return true;
}
return false;
};
// --------------------------------------
Button.prototype.onMouseLeftUp = function( mousePos ) {
this.isPressed = false;
};
// ======================================
// World class
function World( context ) {
this.isAutoEnabled = true;
this.circleCenter = new Point2D( 250, 350 );
this.circleRadius = 200.0;
this.squareCenter = new Point2D( 650, 350 );
this.squareRadius = this.circleRadius * Math.sqrt( Math.PI ) / 2.0;
this.targets = new Array();
this.targets[0] = getCircle( this.circleCenter, this.circleRadius, 100 );
this.targets[1] = new Polygon();
this.targets[1].points[0] = new Point2D( this.squareCenter.x - this.squareRadius, this.squareCenter.y - this.squareRadius );
this.targets[1].points[1] = new Point2D( this.squareCenter.x - this.squareRadius, this.squareCenter.y + this.squareRadius );
this.targets[1].points[2] = new Point2D( this.squareCenter.x + this.squareRadius, this.squareCenter.y + this.squareRadius );
this.targets[1].points[3] = new Point2D( this.squareCenter.x + this.squareRadius, this.squareCenter.y - this.squareRadius );
this.leaderboard = new Array();
this.username = "anon" + Math.floor(Math.random()*9000+1000);
this.pieces = new Array();
// make some pieces
var nPieces = Math.floor( Math.random()*3 ) + 4 ;
var scatterRadius = this.circleRadius * 0.7;
for( var iPiece = 0; iPiece < nPieces; ++iPiece ) {
var piece = this.pieces[ iPiece ] = new Piece();
piece.atOrigin = getCircle( new Point2D( 0, 0 ), Math.random()*20+20, Math.floor(Math.random()*4)+3 );
for( var iTarget = 0; iTarget < this.targets.length; ++iTarget )
piece.originToTarget[ iTarget ] = new Transform( Math.random()*2.0*Math.PI, add( this.targets[ iTarget ].getCentroid(),
new Point2D( Math.random()*scatterRadius*2-scatterRadius,
Math.random()*scatterRadius*2-scatterRadius ) ) );
}
this.buttons = new Array();
var buttonX = 15;
var buttonSep = 10;
this.deletePieceButton = this.buttons[0] = new Button( "Delete piece", "delete_piece", buttonX, 20, context );
buttonX += this.buttons[0].getWidth() + buttonSep;
this.newPieceButton = this.buttons[1] = new Button( "New piece", "new_piece", buttonX, 20, context );
buttonX += this.buttons[1].getWidth() + buttonSep;
this.automaticToggleButton = this.buttons[2] = new Button("Go manual", "toggle_auto", buttonX, 20, context );
buttonX += this.buttons[2].getWidth() + buttonSep;
this.automaticToggleButton.isEnabled = true;
this.submitSolutionButton = this.buttons[3] = new Button("Submit solution", "submit_solution", buttonX, 20, context );
buttonX = 15;
this.clonePieceButton = this.buttons[4] = new Button("Clone piece", "clone_piece", buttonX, 60, context );
buttonX += this.buttons[4].getWidth() + buttonSep;
this.subdividePieceButton = this.buttons[5] = new Button("Subdivide piece", "subdivide_piece", buttonX, 60, context );
buttonX += this.buttons[5].getWidth() + buttonSep;
this.simplifyPieceButton = this.buttons[6] = new Button("Simplify piece", "simplify_piece", buttonX, 60, context );
for( var N = 1; N <= 10; ++N ) {
this.buttons.push( new Button( "N="+N+" : unknown", "leaderboard", 900, 70+N*40, context ) );
this.buttons[ this.buttons.length-1 ].setWidth( 200 );
if( N==1 )
this.iFirstLeaderboardButton = this.buttons.length-1;
}
// we keep track of new results as they come in
this.updates = new Array();
};
// --------------------------------------
World.prototype.draw = function( canvas ) {
var context = canvas.getContext( "2d" );
var isValidSolution = this.isValidSolution();
// draw the background
context.fillStyle = "rgb(200,200,200)";
context.beginPath();
context.fillRect( 0, 0, canvas.width, canvas.height );
context.closePath();
// update the buttons
this.simplifyPieceButton.isEnabled = this.subdividePieceButton.isEnabled = this.clonePieceButton.isEnabled = this.deletePieceButton.isEnabled = this.isAnyPieceSelected();
this.newPieceButton.isEnabled = !this.isAutoEnabled;
var isCurrentBest = false;
if( this.pieces.length <1 || this.pieces.length >10 )
isCurrentBest = false;
else if( isValidSolution && this.leaderboard[ this.pieces.length ] && this.getPercentCovered() > this.leaderboard[ this.pieces.length ].percent+0.01 )
isCurrentBest = true;
else if( isValidSolution && typeof this.leaderboard[ this.pieces.length ] == "undefined" )
isCurrentBest = true;
this.submitSolutionButton.isEnabled = (this.updates.length > 0) && isCurrentBest;
// draw the buttons
for( var iButton = 0; iButton < this.buttons.length; ++iButton )
this.buttons[ iButton ].draw( context );
// draw the targets
context.fillStyle = "rgb(255,255,255)";
for( var i = 0; i < this.targets.length; ++i ) {
this.targets[i].drawPath( context );
context.fill();
}
// draw the pieces (in reverse order so that the transparency appearance matches the selection behavior)
for( var iPiece = this.pieces.length - 1; iPiece >= 0; --iPiece )
this.pieces[ iPiece ].draw( context );
// show some information about the current pieces
context.fillStyle = "rgb(0,0,0)";
context.font="12px Arial";
var percentageCoverage = this.getPercentCovered();
context.fillText( 'N = ' + this.pieces.length + " : " + percentageCoverage.toFixed(2) + "% coverage", 10, 100 );
if( isValidSolution )
context.fillText( "valid solution (no overlapping)", 10, 130 );
else
context.fillText( "overlapping detected!", 10, 130 );
// show the last few updates that have been happening
var numUpdatesToShow = Math.min( 5, this.updates.length );
var timeNow = new Date();
for( var i = 0; i < numUpdatesToShow; ++i ) {
var update = this.updates[ i ]
var msPerMinute = 1000*60;
var minuteDifference = ( timeNow.getTime() - update.time.getTime() ) / msPerMinute
var hourDifference = minuteDifference/60;
var dayDifference = hourDifference/24;
var yearDifference = dayDifference/365;
var timeDiff = "";
if( minuteDifference < 60 )
timeDiff = minuteDifference.toFixed(0) + " minute(s) ago: ";
else if( hourDifference < 24 )
timeDiff = hourDifference.toFixed(0) + " hour(s) ago: ";
else if( dayDifference < 365 )
timeDiff = dayDifference.toFixed(0) + " day(s) ago: ";
else
timeDiff = yearDifference.toFixed(0) + " year(s) ago: ";
context.fillText( timeDiff + update.text, 10, 700 - 20*i );
}
if( this.updates.length > 0 )
context.fillText( "Most recent of " + this.updates.length + " events:", 10, 700 - 20*numUpdatesToShow );
else
context.fillText( "Loading leaderboard...", 10, 700 - 20*numUpdatesToShow );
};
// --------------------------------------
World.prototype.isPointInsideTarget = function( point, iTarget ) {
switch( iTarget ) {
case 0: return( dist2( point, this.circleCenter ) < sqr( this.circleRadius ) );
default: return( this.targets[ iTarget ].contains( point ) );
}
};
// --------------------------------------
World.prototype.isPolygonInsideTarget = function( polygon, iTarget ) {
// simply check that all vertices are inside (assumes targets are convex)
for( var iPt = 0; iPt < polygon.points.length; ++iPt )
if( !this.isPointInsideTarget( polygon.points[ iPt ], iTarget ) )
return false;
return true;
};
// --------------------------------------
World.prototype.isValidSolution = function() {
var polysOnTarget = new Array();
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece ) {
// polygon must not be self-intersecting
if( this.pieces[ iPiece ].atOrigin.isSelfIntersecting() )
return false;
// polygon must be clockwise (positive area)
if( this.pieces[ iPiece ].atOrigin.getArea() <= 0 )
return false;
}
for( var iTarget = 0; iTarget < this.targets.length; ++iTarget ) {
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece ) {
// transform each piece onto this target
polysOnTarget[ iPiece ] = this.pieces[ iPiece ].getPolygonOnTarget( iTarget );
// invalid if any piece not fully contained in each target
if( !this.isPolygonInsideTarget( polysOnTarget[ iPiece ], iTarget ) )
return false;
// invalid if any piece not fully outside any other
for( var iPiece2 = 0; iPiece2 < iPiece; ++iPiece2 )
if( polysOnTarget[ iPiece ].getPolygonRelationWith( polysOnTarget[ iPiece2 ] ) != PolygonRelationEnum.disjoint )
return false;
}
}
return true;
};
// --------------------------------------
World.prototype.getPercentCovered = function() {
// assumes no overlapping
var area = 0.0;
for( var i = 0; i < this.pieces.length; ++i )
area += this.pieces[i].atOrigin.getArea();
return 100.0 * area / ( Math.PI * this.circleRadius * this.circleRadius );
};
// --------------------------------------
World.prototype.addNewPiece = function() {
var p = new Piece();
p.atOrigin = getCircle( new Point2D( 0, 0 ), 30, 6 );
for( var iTarget = 0; iTarget < this.targets.length; ++iTarget )
p.originToTarget[ iTarget ] = new Transform( Math.random() * 2.0 * Math.PI, this.targets[ iTarget ].getCentroid() );
this.pieces.unshift( p ); // add to start of list, so it appears on top
};
// --------------------------------------
World.prototype.deleteSelectedPiece = function() {
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece )
if( this.pieces[ iPiece ].isSelected() )
this.pieces.splice( iPiece, 1 );
};
// --------------------------------------
World.prototype.cloneSelectedPiece = function() {
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece )
if( this.pieces[ iPiece ].isSelected() )
var sourcePiece = this.pieces[ iPiece ];
var p = new Piece();
for( var iPt = 0; iPt < sourcePiece.atOrigin.points.length; ++iPt )
p.atOrigin.points[ iPt ] = new Point2D( sourcePiece.atOrigin.points[ iPt ].x, sourcePiece.atOrigin.points[ iPt ].y );
for( var iTarget = 0; iTarget < sourcePiece.originToTarget.length; ++iTarget )
p.originToTarget[ iTarget ] = new Transform( sourcePiece.originToTarget[ iTarget ].rotate, sourcePiece.originToTarget[ iTarget ].translate );
sourcePiece.state = PieceStateEnum.inactive;
this.pieces.unshift( p ); // add to start of list, so it appears on top
};
// --------------------------------------
World.prototype.clipPiecesAgainstTargets = function() {
for( var iPiece = this.pieces.length-1; iPiece >=0; --iPiece )
{
var piece = this.pieces[ iPiece ];
var pieceDeleted = false;
for( var iTarget = 0; iTarget < piece.originToTarget.length; ++iTarget )
{
var polygonOnTarget = piece.getPolygonOnTarget( iTarget );
for( iPt = polygonOnTarget.points.length-1; iPt >= 0; --iPt )
{
if( !this.isPointInsideTarget( polygonOnTarget.points[ iPt ], iTarget ) )
{
piece.removeVertex( iPt );
if( piece.atOrigin.points.length < 3 )
{
this.pieces.splice( iPiece, 1 );
pieceDeleted = true;
break;
}
}
}
if( pieceDeleted )
break;
}
}
};
// --------------------------------------
World.prototype.clipPiecesAgainstOthers = function() {
for( var iPiece = this.pieces.length-1; iPiece >=0; --iPiece )
{
var piece = this.pieces[ iPiece ];
if( piece.isSelected() )
continue; // don't clip the piece that is currently selected (feels more natural when changing it in auto mode)
var pieceDeleted = false;
for( var iTarget = 0; iTarget < this.targets.length; ++iTarget )
{
var polygonOnTarget = piece.getPolygonOnTarget( iTarget );
for( var iOtherPiece = 0; iOtherPiece < this.pieces.length; ++iOtherPiece )
{
if( iOtherPiece == iPiece )
continue;
var otherPolygonOnTarget = this.pieces[ iOtherPiece ].getPolygonOnTarget( iTarget );
for( iPt = polygonOnTarget.points.length-1; iPt >= 0; --iPt )
{
// check that the point isn't inside the other piece
// and that its edges don't intersect it
var pLeft = polygonOnTarget.points[ (iPt+polygonOnTarget.points.length-1)%polygonOnTarget.points.length ];
var pHere = polygonOnTarget.points[ iPt ];
var pRight = polygonOnTarget.points[ (iPt+1)%polygonOnTarget.points.length ];
if( otherPolygonOnTarget.contains( pHere ) ||
otherPolygonOnTarget.doesLineSegmentIntersect( pLeft, pHere ) ||
otherPolygonOnTarget.doesLineSegmentIntersect( pHere, pRight ) )
{
piece.removeVertex( iPt );
if( piece.atOrigin.points.length < 3 )
{
this.pieces.splice( iPiece, 1 );
pieceDeleted = true;
break;
}
}
}
if( pieceDeleted )
break;
}
if( pieceDeleted )
break;
}
}
};
// --------------------------------------
World.prototype.adaptPieces = function( growStep ) {
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece )
this.pieces[ iPiece ].removeSelfIntersectingVertices();
this.clipPiecesAgainstTargets();
this.clipPiecesAgainstOthers();
var somethingChanged = false;
// move vertices outwards a little on their surface normal for as long as solution remains valid
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece )
{
var piece = this.pieces[ iPiece ];
piece.subdivide( 20 );
piece.removeVerticesCloserThan( 3 );
for( var iPt = 0; iPt < piece.atOrigin.points.length; ++iPt )
{
var oldPos = new Point2D( piece.atOrigin.points[ iPt ].x, piece.atOrigin.points[ iPt ].y );
var move = piece.atOrigin.getNormal( iPt ).mul( growStep );
piece.atOrigin.points[ iPt ].add( move );
var newPosIsOK = true;
if( newPosIsOK )
{
for( var iTarget = 0; iTarget < piece.originToTarget.length; ++iTarget ) {
var pOnTarget = piece.originToTarget[ iTarget ].apply( piece.atOrigin.points[ iPt ] );
// check whether the point is still inside the target shape
if( !this.isPointInsideTarget( pOnTarget, iTarget ) ) {
newPosIsOK = false;
break;
}
// check whether the point doesn't intersect any other shape
for( var iOtherPiece = 0; iOtherPiece < this.pieces.length; ++iOtherPiece ) {
if( iOtherPiece == iPiece )
continue;
var otherPolygonOnTarget = this.pieces[ iOtherPiece ].getPolygonOnTarget( iTarget );
var left = piece.originToTarget[ iTarget ].apply( piece.atOrigin.points[ (iPt+piece.atOrigin.points.length-1)%piece.atOrigin.points.length ] );
var right = piece.originToTarget[ iTarget ].apply( piece.atOrigin.points[ (iPt+1)%piece.atOrigin.points.length ] );
if( otherPolygonOnTarget.doesLineSegmentIntersect( left, pOnTarget ) || otherPolygonOnTarget.doesLineSegmentIntersect( pOnTarget, right ) ) {
newPosIsOK = false;
break;
}
}
if( !newPosIsOK )
break;
}
}
if( !newPosIsOK )
piece.atOrigin.points[ iPt ] = oldPos;
else
somethingChanged = true;
}
piece.recenter();
}
return somethingChanged;
};
// --------------------------------------
World.prototype.subdivideSelectedPiece = function() {
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece )
if( this.pieces[ iPiece ].isSelected() )
this.pieces[ iPiece ].subdivide( 10 );
};
// --------------------------------------
World.prototype.simplifySelectedPiece = function() {
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece )
if( this.pieces[ iPiece ].isSelected() )
this.pieces[ iPiece ].removeVerticesStraighterThan( 0.1 );
};
// --------------------------------------
World.prototype.isAnyPieceSelected = function() {
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece )
if( this.pieces[ iPiece ].isSelected() )
return true;
return false;
};
// --------------------------------------
World.prototype.onMouseMove = function( mousePos ) {
// pass the message to the pieces
for( var iPiece = 0; iPiece < this.pieces.length; ++iPiece )
this.pieces[ iPiece ].onMouseMove( mousePos );
};
// --------------------------------------
World.prototype.onMouseLeftDown = function( mousePos ) {
// was a button pressed?
for( var iButton = 0; iButton < this.buttons.length; ++iButton ) {
if( this.buttons[ iButton ].onMouseLeftDown( mousePos ) ) {
this.doButtonAction( this.buttons[ iButton ].id, this.buttons[ iButton ].label );
return;
}
}
// send the message to the pieces
var iPieceSelected = -1;