-
Notifications
You must be signed in to change notification settings - Fork 8
/
liquidGraph.js
3161 lines (2542 loc) · 89.6 KB
/
liquidGraph.js
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
//Globals
var pointOverlapTolerance = 2;
var endpointPointOverlapTolerance = 1.5;
var globalAnimateSpeed = 0.3;
/*********** CLASSES ********/
function Vertex(x,y,rPoint,parentPoly) {
this.x = x;
this.y = y;
this.rPoint = rPoint;
this.parentPoly = parentPoly;
this.id = polyController.requestId(this);
this.inEdge = null;
this.outEdge = null;
this.isConcave = null;
};
Vertex.prototype.highlight = function() {
this.rPoint.animate({
'r':5,
'stroke':'#000',
'stroke-width':3,
},800,'easeInOut');
};
Vertex.prototype.getOtherEdge = function(edge) {
if (!this.inEdge || !this.outEdge) { throw new Error("null edges!"); }
//this comparison works because the edges aren't typecasted to strings or anything
if (this.inEdge == edge)
{
return this.outEdge;
}
return this.inEdge;
};
Vertex.prototype.concaveTest = function() {
//the concavity test is as follows:
//
//take the cross product of the outward normal vs the
//inward normal. This will be positive if the vector turned "outward",
//but will be negative if the vector turned inward. But before this
//we need to know if the polygon is ordered clockwised or counterclockwise...
var before = this.inEdge.getOtherVertex(this);
var after = this.outEdge.getOtherVertex(this);
var inEdgeNormal = this.inEdge.outwardNormal;
var outEdgeNormal = this.outEdge.outwardNormal;
//we just take the cross here to determine concavity / convexity
if (vecCross(outEdgeNormal,inEdgeNormal) > 0)
{
this.isConcave = !this.parentPoly.CCW;
} else {
this.isConcave = this.parentPoly.CCW;
}
return this.isConcave;
};
//takes in a collection of raphael points,
//validates these points as a valid polygon,
//and then displays on the screen
function Polygon(rPoints,rPath) {
this.rPoints = rPoints;
this.rPath = rPath;
this.fillColor = rPath.attr('fill');
this.vertices = [];
this.concaveVertices = [];
this.edges = [];
this.rPath.toFront();
for (var i = 0; i < this.rPoints.length; i++)
{
var rPoint = this.rPoints[i];
rPoint.toFront();
var x = rPoint.attr('cx');
var y = rPoint.attr('cy');
var vertex = new Vertex(x,y,rPoint,this);
this.vertices.push(vertex);
}
//first validate the polygon
this.validatePolygon();
this.determineOrdering();
this.setBodyDragHandlers();
this.setVertexDragHandlers();
//classify vertices
this.classifyVertices();
};
Polygon.prototype.determineOrdering = function() {
//determine the area of the polygon. aka go around summing up
//triangle areas of each edge,
var totalArea = 0;
for (var i = 0; i < this.edges.length; i++)
{
var thisArea = vecCross(this.edges[i].p1,this.edges[i].p2);
totalArea += thisArea;
}
if (totalArea < 0)
{
this.CCW = true;
}
else
{
this.CCW = false;
}
};
Polygon.prototype.setVertexDragHandlers = function () {
var onDrag = function(dx,dy,x,y,e) {
if (!polyEditor.active)
{
return;
}
if (this.dragPath) { this.dragPath.remove(); }
if (this.dragCircle) { this.dragCircle.remove(); }
if (this.dragOutline) { this.dragOutline.remove(); }
var endPoint = vecMake(x,y);
var startPoint = vecMake(this.startDragX,this.startDragY);
if (!this.dragEndPoint) { //first time
this.parentPoly.rPath.attr('fill','none');
}
this.dragEndPoint = endPoint;
var pathString = constructPathStringFromCoords([startPoint,endPoint]);
this.dragPath = cutePath(pathString,false);
this.dragCircle = cuteSmallCircle(x,y);
//go get all the vertices real quick
var points = [];
var vertices = this.parentPoly.vertices;
for (var i = 0; i < vertices.length; i++)
{
if (vertices[i] != this)
{
points.push(vertices[i]);
} else {
points.push(endPoint);
}
}
pathString = constructPathStringFromCoords(points,true);
this.dragOutline = cutePath(pathString,true,'#FFF',this.parentPoly.fillColor);
};
var onEnd = function(e) {
if (!polyEditor.active)
{
return;
}
if (this.dragPath) { this.dragPath.remove(); }
if (this.dragCircle) { this.dragCircle.remove(); }
if (this.dragOutline) { this.dragOutline.remove(); }
//ok so we need to clone all the vertices, except for this one
var vertices = this.parentPoly.vertices;
var rPoints = [];
for (var i = 0; i < vertices.length; i++)
{
if (vertices[i] != this)
{
rPoints.push(vertices[i].rPoint.clone());
}
else
{
rPoints.push(cuteSmallCircle(this.dragEndPoint.x,this.dragEndPoint.y));
}
}
var newPathString = constructPathStringFromPoints(rPoints,true);
var newPath = cutePath(newPathString,true,'#FFF',this.parentPoly.fillColor);
//temporarily remove the parent poly
polyController.remove(this.parentPoly);
var results = polyController.makePolygon(rPoints,newPath);
if (!results.failed)
{
this.parentPoly.rPath.remove();
$j.each(this.parentPoly.vertices,function(i,vertex) { vertex.rPoint.remove(); });
}
else
{
//it failed so add ourselves back in
polyController.add(this.parentPoly);
this.parentPoly.rPath.attr('fill',this.parentPoly.fillColor);
}
this.dragEndPoint = null;
};
var onStart = function(x,y,e) {
if (!polyEditor.active && !solveController.active)
{
return;
}
if (solveController.active)
{
solveController.vertexClick(this);
return;
}
//this refers to the VERTEX being clicked!!
this.parentPoly.dragVertex = this;
this.startDragX = x;
this.startDragY = y;
};
for (var i = 0; i < this.vertices.length; i++)
{
var v = this.vertices[i];
v.rPoint.drag(onDrag,onStart,onEnd,v,v,v);
}
};
Polygon.prototype.setBodyDragHandlers = function() {
var onDrag = function(dx,dy,x,y,e) {
if (!polyEditor.active)
{
return;
}
this.dragDeltaX = x - this.startDragX;
this.dragDeltaY = y - this.startDragY;
var tString = "T" + String(this.dragDeltaX) + "," + String(this.dragDeltaY);
this.rPath.transform(tString);
$j.each(this.vertices,function(i,vertex) {
vertex.rPoint.attr({
'cx':vertex.x + vertex.parentPoly.dragDeltaX,
'cy':vertex.y + vertex.parentPoly.dragDeltaY
});
});
};
var onEnd = function(e) {
//the delta x is what we need to shift everything by...
//we really need to make a completely new polygon here
var newPoints = [];
for (var i = 0; i < this.vertices.length; i++)
{
newPoints.push(this.vertices[i].rPoint.clone());
}
var newPathString = constructPathStringFromPoints(newPoints,true);
var newPath = cutePath(newPathString,true,'#FFF',this.fillColor);
//we need to temporarily remove ourselves so validation doesnt fail
polyController.remove(this);
var results = polyController.makePolygon(newPoints,newPath);
//if successful, clear ourselves out for good
if (!results.failed)
{
this.rPath.remove();
$j.each(this.vertices,function(i,vertex) { vertex.rPoint.remove(); });
}
else
{
//add ourselves back in
polyController.add(this);
//reset our translation?
this.rPath.transform("");
$j.each(this.vertices,function(i,vertex) {
vertex.rPoint.attr({
'cx':vertex.x,
'cy':vertex.y
});
});
}
};
var onStart = function(x,y,e) {
if (!polyEditor.active)
{
return;
}
this.startDragX = x;
this.startDragY = y;
}
this.rPath.drag(onDrag,onStart,onEnd,this,this,this);
};
Polygon.prototype.classifyVertices = function() {
if (this.vertices.length == 3)
{
//all are convex, its a triangle.
return;
}
for (var i = 0; i < this.vertices.length; i++)
{
var vertex = this.vertices[i];
if (vertex.concaveTest())
{
vertex.highlight();
this.concaveVertices.push(vertex);
}
}
};
Polygon.prototype.validatePolygon = function() {
//make sure no two points on top of each other (or within a few pixels)
this.validatePoints();
//now go make all the edges
this.buildEdges();
//validate edges for intersections
this.validateEdges();
};
Polygon.prototype.validateEdges = function() {
//test all the edges against each other
for (var i = 0; i < this.edges.length; i++)
{
var currEdge = this.edges[i];
if (polyController.doesEdgeIntersectAny(currEdge,this))
{
throw new Error("An edge overlaps another edge in that polygon!");
}
//minor speedup by specifying j = i to start
for (var j = i; j < this.edges.length; j++)
{
if (j == i) { continue; }
testEdge = this.edges[j];
if (currEdge.intersectTest(testEdge))
{
throw new Error("Two edges intersect in that polygon!");
}
}
}
};
Polygon.prototype.buildEdges = function() {
for (var i = 0; i < this.vertices.length; i++)
{
var currPoint = this.vertices[i];
if (i == this.vertices.length - 1)
{
var nextIndex = 0;
}
else
{
var nextIndex = i + 1;
}
var nextPoint = this.vertices[nextIndex];
var edge = new Edge(currPoint,nextPoint,this);
this.edges.push(edge);
//set the edges for the vertices
currPoint.outEdge = edge;
nextPoint.inEdge = edge;
}
};
Polygon.prototype.isPointInside = function(point) {
return this.rPath.isPointInside(point.x,point.y);
};
Polygon.prototype.clear = function() {
this.rPath.remove();
$j.each(this.vertices,function(i,vertex) {
vertex.rPoint.remove();
});
};
Polygon.prototype.validatePoints = function() {
for (var i = 0; i < this.vertices.length; i++)
{
currPoint = this.vertices[i];
if (polyController.isPointInAny(currPoint,this))
{
throw new Error("Invalid Polygon - Point inside other polygon!");
}
for (var j = i; j < this.vertices.length; j++)
{
if (j == i) { continue; }
testPoint = this.vertices[j];
var dist = distBetween(testPoint,currPoint);
if (dist < pointOverlapTolerance)
{
throw new Error("Invalid Polygon -- Two points on top of each other");
}
}
}
};
/**************GLOBAL CONTROL OBJECTS *******************/
//controls the global polygons
function polygonController() {
this.polys = [];
this.allEdges = [];
this.vertexIdToGive = 0;
this.idToVertex = {};
};
//ensures no two vertices have same ID. i used to do this with random
//hashes and checking but that got ugly
polygonController.prototype.requestId = function(vertex) {
this.vertexIdToGive++;
this.idToVertex[this.vertexIdToGive] = vertex;
return this.vertexIdToGive;
};
polygonController.prototype.getVertexById = function(id) {
return this.idToVertex[id];
};
polygonController.prototype.reset = function() {
for (var i = 0; i < this.polys.length; i++)
{
this.polys[i].clear();
}
this.polys = [];
this.allEdges = []; //lol garbage collection
};
//node: we will destroy the points and path here if the polygon fails
//so make sure they are a cloned / duplicate if you want to preserve them
polygonController.prototype.makePolygon = function(rPoints,rPath) {
try {
var poly = new Polygon(rPoints,rPath);
} catch (e) {
topNotifyTemp(String(e));
//we have to color this polygon red and remove it
rPath.animate({'stroke':'#F00','stroke-width':20},800,'easeInOut');
$j.each(rPoints,function(i,point) { point.animate({'r':0,'stroke':'#F00'},800,'easeInOut'); });
//remove it in 1000 ms
setTimeout(function() {
rPath.remove();
for (var i = 0; i < rPoints.length; i++)
{
rPoints[i].remove();
}
}, 1000);
return {
'poly':null,
'failed':true,
};
}
this.add(poly);
return {
'poly':poly,
'failed':false
};
};
polygonController.prototype.add = function(poly) {
this.polys.push(poly);
this.allEdges = this.allEdges.concat(poly.edges);
};
polygonController.prototype.doesEdgeIntersectAny = function(edge,sourcePoly) {
for (var i = 0; i < this.polys.length; i++)
{
//dont check against yourself
if (this.polys[i] == sourcePoly) { continue; }
for (var j = 0; j < this.polys[i].edges.length; j++)
{
if (edge.intersectTest(this.polys[i].edges[j]))
{
return true;
}
}
}
return false;
};
polygonController.prototype.isPointInAny = function(point,sourcePoly) {
for (var i = 0; i < this.polys.length; i++)
{
//dont check against yourself
if (this.polys[i] == sourcePoly) { continue; }
if (this.polys[i].isPointInside(point))
{
return true;
}
}
return false;
};
polygonController.prototype.remove = function(poly) {
//wish JS had a nice list remove like pyton
for (var i = 0; i < this.polys.length; i++)
{
if (poly == this.polys[i])
{
this.polys.splice(i,1);
i--;
//should only be one polygon but just in case
}
}
this.allEdges = [];
//reset edges
for (var i = 0; i < this.polys.length; i++)
{
this.allEdges = this.allEdges.concat(this.polys[i].edges);
}
};
function particleController() {
this.particles = [];
this.wantsPaths = true;
};
particleController.prototype.add = function(part) {
this.particles.push(part);
};
particleController.prototype.clearAll = function() {
$j.each(this.particles,function(i,particle) {
if (particle.clearAll) {
particle.clearAll();
}
});
this.particles = [];
};
particleController.prototype.makeParticle = function(kState,accel,beginState) {
var particle = new Particle(kState,accel,beginState);
this.particles.push(particle);
particle.settle();
if (this.wantsPaths)
{
particle.drawEntirePath();
}
particle.animate();
return particle;
};
particleController.prototype.togglePathPreference = function() {
if (this.wantsPaths)
{
$j.each(this.particles,function(i,particle) {
particle.clearPath();
});
this.wantsPaths = false;
}
else
{
$j.each(this.particles,function(i,particle) {
particle.drawEntirePath();
});
this.wantsPaths = true;
}
};
function parametricQuadSolver(a,b,c) {
var solutions = solveQuadraticEquation(a,b,c);
if (!solutions.results)
{
return [];
}
var ans1 = solutions.plusAns;
var ans2 = solutions.negAns;
//basically return the non-negative ones
var answers = [];
if (ans1 >= 0)
{
answers.push(ans1);
}
if (ans2 >= 0)
{
answers.push(ans2);
}
return answers;
};
function solveQuadraticEquation(a,b,c) {
//if denom is invalid
var denom = 2 * a;
if (denom == 0)
{
return {results:false};
}
var underRoot = b*b - 4*a*c;
if (underRoot < 0)
{
return {results:false};
}
var sqrRoot = Math.sqrt(underRoot);
var numPlus = -b + sqrRoot;
var numNeg = -b - sqrRoot;
var plusAns = numPlus / denom;
var negAns = numNeg / denom;
return {results:true,
plusAns:plusAns,
negAns:negAns
};
};
function pointTheSame(p1,p2) {
return p1.x == p2.x && p1.y == p2.y;
};
function distBetween(p1,p2) {
return Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y);
};
function Edge(p1,p2,parentPoly,outwardNormal) {
this.p1 = p1;
this.p2 = p2;
this.parentPoly = parentPoly;
this.midPoint = vecAdd(vecScale(this.p1,0.5),vecScale(this.p2,0.5));
this.edgeSlope = vecSubtract(this.p2,this.p1);
if (distBetween(p1,p2) < pointOverlapTolerance)
{
throw new Error("Invalid Polygon -- Edge with two points on top of each other!");
}
if (this.parentPoly && !outwardNormal)
{
this.outwardNormal = this.getOutwardNormal();
}
else
{
this.outwardNormal = outwardNormal;
}
};
Edge.prototype.getOtherVertex = function(vertex) {
if (!vertex || !this.p1 || !this.p2) { throw new Error("null arguments!"); }
if (this.p1 == vertex)
{
return this.p2;
}
return this.p1;
};
Edge.prototype.getOutwardNormal = function() {
//ok this is a bit hacked up but get avg point, get a given normal, displace a bit, and test
//for inclusion in the polygon. i know i know this sucks but normal computational
//geometry people get clockwise ordered vertices so it's easy, not for me with those
//tricky users!!
var midPoint = this.midPoint;
var edgeSlope = this.edgeSlope;
var aNormal = {
'x':edgeSlope.y * -1,
'y':edgeSlope.x
};
aNormal = vecNormalize(aNormal);
//displace by a bit
var testPoint = vecAdd(midPoint,vecScale(aNormal,0.01));
//if this is inside, then negate!
if (this.parentPoly.isPointInside(testPoint))
{
aNormal = vecNegate(aNormal);
}
//for debug, make an arrow
if (debug)
{
new rArrow(midPoint,vecScale(aNormal,100));
new rArrow(midPoint,edgeSlope);
}
return aNormal;
};
Edge.prototype.highlight = function() {
var pathStr = constructPathStringFromCoords([this.p1,this.p2]);
this.path = p.path(pathStr);
this.path.glow();
this.path.attr({
'stroke':'#F00',
'stroke-width':3
});
};
//returns true if two edges intersect in a point that is within both edges
//and not defined by their endpoints
Edge.prototype.intersectTest = function(otherEdge) {
//first get the point of line intersection between these two
var intersectPoint = lineLineIntersection(this.p1,this.p2,otherEdge.p1,otherEdge.p2);
if (!intersectPoint)
{
//no intersection point at all, so either these edges are parallel or colinear.
//
//lets first check for colinearity. if the 'center point' of edge1 is within
//edge2 or the 'center point' of edge2 is within edge1, then return true because
//they are on top of each other. otherwise return false
var myCenter = centerPoint(this.p1,this.p2);
var otherCenter = centerPoint(otherEdge.p1,otherEdge.p2);
if (otherEdge.containsInsideEndpoints(myCenter) || this.containsInsideEndpoints(otherCenter))
{
return true;
}
return false;
}
//check that this intersection point is within both edges
var withinTest = this.pointWithin(intersectPoint) && otherEdge.pointWithin(intersectPoint);
if (!withinTest)
{
//no the intersection point isnt within the edges, don't worry about it
return false;
}
//finally, both edges must contain these points for it to be a true intersection
return this.containsInsideEndpoints(intersectPoint) && otherEdge.containsInsideEndpoints(intersectPoint);
};
Edge.prototype.containsInsideEndpoints = function(testPoint) {
//first check if its within, then do the tolerance check against the endpoints
if (!this.pointWithin(testPoint))
{
return false;
}
//now check min distance thing
var minDist = Math.min(distBetween(this.p1,testPoint),distBetween(this.p2,testPoint));
var tol = endpointPointOverlapTolerance;
if (minDist < tol)
{
//just a point point intersect
return false;
}
//truly within and not on top
return true;
};
//returns true when the testPoint lies within our edge endpoints
Edge.prototype.pointWithin = function(testPoint) {
//to do this, make a vector from edgePoint1 to testPoint.
//then make a vector from edgePoint1 to edgePoint 2.
var p1ToTest = makeVec(this.p1,testPoint);
var p1ToP2 = makeVec(this.p1,this.p2);
//take the dot between these two vectors. we already know they are colinear, so
//we don't have to worry about the cosine angle stuff. if this dot product is not positive
//(aka they are facing opposite directions), then return false
var dotProduct = vecDot(p1ToTest,p1ToP2);
if (dotProduct <= 0)
{
return false;
}
//next, if they are facing in the same direction, take the length of the first vec
//and compare it to the second
if (vecLength(p1ToTest) <= vecLength(p1ToP2))
{
return true;
}
return false;
};
Edge.prototype.validateSolutionPoint = function(parabola,tValue) {
var ax, ay, vx, vy, px, py;
//the px and py are relative
px = parabola.pos.x - this.p1.x;
py = parabola.pos.y - this.p1.y;
ax = parabola.accel.x; ay = parabola.accel.y;
vx = parabola.vel.x; vy = parabola.vel.y;
var solutionPoint = {
x: parabola.pos.x + tValue * vx + 0.5 * tValue * tValue * ax,
y: parabola.pos.y + tValue * vy + 0.5 * tValue * tValue * ay
};
//if we don't contain this point, get pissed because it was deceiving
//and return
if (!this.pointWithin(solutionPoint))
{
//not really on this edge...
return null;
}
//there is a solution, and it lies within our endpoint! wahoo
return {solutionPoint:solutionPoint,tValue:tValue};
};
Edge.prototype.parabolaIntersection = function(parabola) {
//a parabola is defined as:
//
// pos -> starting point of parabola (vec)
// vel -> starting velocity (vec)
// accel -> acceleration direction (vec)
var ax, ay, vx, vy, px, py;
//the px and py are relative
px = parabola.pos.x - this.p1.x;
py = parabola.pos.y - this.p1.y;
ax = parabola.accel.x; ay = parabola.accel.y;
vx = parabola.vel.x; vy = parabola.vel.y;
//we solve this via a clever parametric equation taken into a cross product
//of the vector of our endpoints
var ourVec = makeVec(this.p1,this.p2);
var a = (0.5 * ax * ourVec.y - 0.5 * ay * ourVec.x);
if (a == 0)
{
//one tricky thing happens when you have completely vertical accel
//and completely vertical edges. the denom goes to 0 because
//there might be an infinite number of solutions; however for us,
//we just want one, so perturb ax and ay a bit
ax += 0.001;
ay += 0.001;
a = (0.5 * ax * ourVec.y - 0.5 * ay * ourVec.x);
}
var b = (vx * ourVec.y - vy * ourVec.x);
var c = (px * ourVec.y - py * ourVec.x);
var tValues = parametricQuadSolver(a,b,c);
if (tValues.length == 0)
{
//no solution to this
return null;
}
//sort the tValues
//WOW ARE YOU KIDDING MEEeeee javascript your sort function fails
//so badly. this caused a huge bug
tValues.sort(function(a,b) { return a - b; });
//now loop through them.
//
/*
* The reason why we have to loop through them (rather than just taking the
* smallest one) is because we are solving a parabola / LINE intersection.
* Hence, in certain cases, there would be two solutions to the parabola
* and the line defined by this edge. Unfortunately, the first solution would
* be a point on the parabola that was not on the edge and the second
* solution would be a point that was on the edge. so originally the
* parametric quad solver would throw out the higher solution and
* the lower solution would get rejected at the validation step.
* This was really tricky to find. I fixed it by instead looping
* Through them in order so you consider all positive results.
*
*/
for (var i = 0; i < tValues.length; i++)
{
var tValue = tValues[i];
var results = this.validateSolutionPoint(parabola,tValue);
if (results)
{
return results;
}
}
return null;
};
function Parabola(pos,vel,accel,shouldDraw) {
if (!pos || !vel || !accel)
{
throw new Error("undefined parameters!");
}
this.pos = pos;
this.vel = vel;
this.accel = accel;
this.path = null;
this.clickFunction = null;
this.pointYielder = this.getPointYielder();
this.slopeYielder = this.getSlopeYielder();
//go draw ourselves
if (shouldDraw) {
this.drawParabolaPath(-1);
}
};
Parabola.prototype.drawParabolaPath = function(tVal) {
var hue = velocityHue(this.vel);
//fix!! sometimes with VERY straight paths you get numerical imprecision
//and the parabola line goes off the screen because the control point is so far away...
//fix this via:
var v1 = vecNormalize(this.vel);
var v2 = vecNormalize(this.accel);
var shouldGoBezier = true;
if (vecDot(v1,v2) > 0.99)
{
//just make it from points
var p1 = this.pointYielder(0);
var p2 = this.pointYielder(tVal);
var pString = constructPathStringFromCoords([p1,p2]);
this.path = cutePath(pString);
this.path.attr({
'stroke-width':3,
'stroke':hue
});
return;
}
//convert this parabola into a quadratic bezier path
this.path = this.getQuadraticBezierPath(tVal);
this.path.attr({
'stroke-width':3,
'stroke':hue
});
if (this.clickFunction)
{
this.path.click(this.clickFunction);