This repository was archived by the owner on Sep 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgraph.js
1342 lines (1206 loc) · 38.6 KB
/
graph.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
// GRAPH JS =================================================================================================================
// By Andy Graulund + David Kofoed Wind
// Basic stuff --------------------------------------------------------------------------------------------------------------
var n = "number",
s = "string",
o = "object",
b = "boolean",
u = "undefined",
uimode = 0,
dragging = false, moved = false, dp = [null,null], dontclick = false,
selected = [],
hovered = null,
modal = null
var touch = "createTouch" in document
var w = 640,
h = 480,
cid = 100
var click = touch ? "tap" : "click"
var vertices = [],
edges = [],
graphs = [],
states = [], // For undos/redos
gi = 0 // Current graph (index)
var ce = null,
canvas = null,
cx = null
// UI panels/elements
var ui = { properties: null, styles: null, elements: null, graphs: null }
// Constants ----------------------------------------------------------------------------------------------------------------
// (Defined as variables. Don't change them.)
var GJ_TOOL_SELECT = 0,
GJ_TOOL_ADD_EDGE = 1,
GJ_TOOL_ADD_VERTEX = 2,
GJ_TOOL_SELECT_VERTEX = 3,
GJ_TOOL_SELECT_VERTICES = 4,
GJ_TOOL_SELECT_EDGE = 5,
GJ_TOOL_SELECT_EDGES = 6
// Utility functions --------------------------------------------------------------------------------------------------------
function iu(x){ return typeof x == u }
function dlog(x){ if("console" in window && window.console.log){ console.log(x) } }
function oc(a){ var o = {}; for(var i=0;i<a.length;i++){ o[a[i]] = ""; } return o }
function he(str){ return str.toString().replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">") } // Special HTML chars encode
function re(str){ return str.toString().replace(/"/g, "\"").replace(/'/, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&") } // Special HTML chars decode
function ucf(str){ str += ""; var f = str.charAt(0).toUpperCase(); return f + str.substr(1) } // Upper case first letter
function is_numeric(mixed_var){ return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var); } // Kudos, PHPJS
function trimArray(array){ var a = []; for(var e in array){ if(typeof array[e] != u){ a.push(array[e]) } } return a }
function noevt(evt){ evt.preventDefault() }
function inArray(v, array){
for(var e in array){
if(array[e] === v){
return true
}
}
return false
}
function listRemove(list, val){
for(var i = 0; i < list.length; i++){
if(list[i] == val){
list.splice(i, 1)
}
}
} // oh god what did i do i am a terrible person
// Style --------------------------------------------------------------------------------------------------------------------
function ElementStyle(strokecolor, fillcolor, strokewidth, vertexradius){
if(typeof strokewidth != n || strokewidth <= 0){ strokewidth = 1.2 }
if(typeof vertexradius != n || vertexradius <= 0){ vertexradius = 4 }
this.id = ++cid
this.shape = "circle"
this.strokecolor = strokecolor
this.fillcolor = fillcolor
this.strokewidth = strokewidth
this.vertexradius = vertexradius
this.toTikZ = function(){
// TODO: convert colors
return "\\tikzstyle{style" + this.id + "}=[" + this.shape + ",fill=" + this.fillcolor + ",draw=" + this.strokecolor + ",line width=" + this.strokewidth + "]"
}
}
function styleContext(cx, style, fill){
if(typeof fill != b){ fill = true }
cx.strokeStyle = style.strokecolor
if(fill){ cx.fillStyle = style.fillcolor }
cx.lineWidth = style.strokewidth
}
var defaultStyle = new ElementStyle("#000", "#fff")
var selectedStyle = new ElementStyle("rgba(39,166,255,0.5)", "transparent", 4)
var labelStyle = new ElementStyle("transparent", "#fff", 0)
// The classes --------------------------------------------------------------------------------------------------------------
function Graph(vertices, edges){
if(typeof vertices == u){ vertices = [] }
if(typeof vertices != o){ return false }
if(typeof edges == u){ edges = [] }
if(typeof edges != o){ return false }
this.vertices = vertices
this.edges = edges
this.x = 0 // An offset?
this.y = 0
this.visible = true
this.cmpltd = false
this.draw = function(cx){
if(cx != null){
//dlog(["Drawing graph"])
var edgegroups = this.edgeGroups(), g
//dlog(edgegroups)
for(var s in edgegroups){
g = edgegroups[s]
for(var i in g){
g[i].draw(cx, g.length, i)
}
}
for(var i in this.vertices){
this.vertices[i].draw(cx)
}
/*if(selected.length <= 0 || selected[0] == this || selected[0] == null){
displayInfo(ui.properties, null, cx)
}*/
}
}
this.attach = function(){
this.visible = true
graphs.push(this)
}
this.detach = function(){
this.visible = false
listRemove(graphs, this)
}
this.toJSON = function(){
var o = { vertices: [], edges: [], x: this.x, y: this.y }
for(var i in this.vertices){
o.vertices.push(this.vertices[i].toJSON())
}
for(var i in this.edges){
o.edges.push(this.edges[i].toJSON())
}
return o
}
this.toTikZ = function(){
var o = "\\begin{tikzpicture}\n"
var maxY = 0
for(var i in this.vertices){
if(this.vertices[i].y > maxY){
maxY = this.vertices[i].y
}
}
for(var i in this.vertices){
o += "\t" + this.vertices[i].toTikZ(100, maxY) + "\n"
}
for(var i in this.edges){
o += "\t" + this.edges[i].toTikZ() + "\n"
}
o += "\\end{tikzpicture}"
return o
}
this.degreeSeq = function(){
var seq = [], v
for(var i in this.vertices){
v = this.vertices[i]
if(v instanceof Vertex){
seq.push(v.degree)
}
}
return seq
}
this.addVertex = function(v, cx){
if(v instanceof Array && v.length == 2){
v = new Vertex(cid++, "", v[0], v[1])
}
if(!(v instanceof Vertex)){
v = new Vertex(cid++, "", (w/2 + Math.floor(Math.random()*10)), (h/2 + Math.floor(Math.random()*10)))
}
this.vertices.push(v)
v.update(this)
this.draw(cx)
this.cmpltd = false
return v
}
this.addEdge = function(e, cx){
if(e instanceof Array && e.length == 2){
e = new Edge(cid++, "", e[0], e[1])
}
if(e instanceof Edge){
if(inArray(e.from, this.vertices) && inArray(e.to, this.vertices)){
this.edges.push(e)
e.update(this)
this.draw(cx)
this.cmpltd = false
return e
}
}
return null
}
this.detachChild = function(el){
var list, edges = []
if(el instanceof Vertex){ list = this.vertices; edges = el.edges }
else if(el instanceof Edge){ list = this.edges }
else { return null }
/*if(edges.length > 0){
for(var i in edges){
this.detachChild(edges[i])
}
}*/
while(edges.length > 0){
this.detachChild(edges[0])
}
el.detach()
listRemove(list, el)
return el
}
this.contractEdge = function(e){
e.contract(this)
}
this.adjacencyList = function(){
var l = [], e
for(var i in this.edges){
e = this.edges[i]
l.push([e.from, e.to])
}
return l
}
this.adjacencyMatrix = function(mobj){
var M = [], v, u, r
// TODO: Better support for directed graphs and multigraphs
for(var i in this.vertices){
v = this.vertices[i]
r = []
for(var j in this.vertices){
u = this.vertices[j]
//r.push(v.isNeighbour(u) ? 1 : 0)
r.push(v.edgeMultiplicity(u))
}
M.push(r)
}
return mobj ? $M(M.length > 0 ? M : [0]) : M
}
this.degreeMatrix = function(mobj){
// Requires Sylvester
var ds = this.degreeSeq()
var dl = (ds.length > 0)
var DM = dl ? Matrix.Diagonal(ds) : $M([0])
return mobj ? DM : (dl ? DM.elements : [])
}
this.laplacianMatrix = function(mobj){
// Requires Sylvester
var AM = this.adjacencyMatrix(true)
var DM = this.degreeMatrix(true)
var LM = DM.subtract(AM)
return mobj ? LM : LM.elements
}
this.spanningTreeCount = function(){
// Requires Sylvester
var LM = this.laplacianMatrix(true)
var n = LM.rows() - 1
if(n > 1){
return Math.round(LM.minor(1, 1, n, n).determinant())
} else if(n == 1){
return Math.round(Math.abs(LM.elements[0][0]))
}
return 0
}
this.edgeGroups = function(groupname){
var l = {}, e, name
for(var i in this.edges){
e = this.edges[i]
name = e.groupName()
if(!(name in l)){ l[name] = [] }
l[name].push(e)
}
if(groupname){
return groupname in l ? l[groupname] : null
}
return l
}
this.isWeighted = function(){
if(this.edges.length <= 0){ return false }
for(var i in this.edges){
if(!is_numeric(this.edges[i].value)){
return false
}
}
return true
}
this.isComplete = function(){
// Autocompleted? Yes.
if(this.cmpltd){ return true }
// Might still be...
var n = this.vertices.length
if(this.edges.length == ((n*(n-1))/2)){
var seq = this.degreeSeq()
for(var i in seq){
if(seq[i] != n-1){
return false
}
}
return true
}
return false
}
this.elementsWithinRect = function(x1, y1, x2, y2){
var xh = Math.max(x1, x2),
xl = Math.min(x1, x2),
yh = Math.max(y1, y2),
yl = Math.min(y1, y2), a,
els = []
// Vertices
for(var i in this.vertices){
a = this.vertices[i]
if(a.x <= xh && a.x >= xl && a.y <= yh && a.y >= yl){
els.push(a)
}
}
// Edges
// ????
return els
}
this.complete = function(cx){
this.edges = []
for(var i in this.vertices){
v = this.vertices[i]
if(v instanceof Vertex){
v.edges = []
v.update(this)
}
}
for(var i in this.vertices){
v = this.vertices[i]
if(v instanceof Vertex){
for(var j in this.vertices){
u = this.vertices[j]
if(u instanceof Vertex){
if(!v.isNeighbour(u) && v !== u){
this.addEdge([v,u], cx)
}
}
}
}
}
this.cmpltd = true
}
this.attach()
}
function Vertex(id, value, x, y){
if(typeof id != n){ return false }
if(typeof value != n && typeof value != s){ return false }
if(typeof x != n || typeof y != n){ return false }
this.id = id
this.value = value
this.x = Math.round(x)
this.y = Math.round(y)
this.degree = 0
this.edges = []
this.visible = true
this.style = defaultStyle
this.draw = function(cx){
this._draw(cx, this.style, true)
}
this.drawSel = function(cx){
this._draw(cx, selectedStyle, false)
}
this._draw = function(cx, style, label){
styleContext(cx, style)
cx.beginPath()
cx.arc(this.x, this.y, style.vertexradius, 0, 2*Math.PI, true)
cx.closePath()
cx.fill()
cx.stroke()
if(label && (typeof this.value == s || typeof this.value == n) && this.value !== ""){
drawLabel(this.value, this.x, this.y - 14)
}
}
this.update = function(graph){
// Update various properties
this.degree = this.edges.length
}
this.attach = function(){
this.visible = true
vertices.push(this)
}
this.detach = function(graph){
if(graph instanceof Graph){
graph.detachChild(this)
} else {
this.visible = false
listRemove(vertices, this)
if(this.id in selected){ delete selected[this.id] } //listRemove(selected, this)
for(var i in this.edges){
this.edges[i].detach()
}
}
}
this.toJSON = function(){
return { id: this.id, value: this.value, x: this.x, y: this.y } // No style support yet
}
this.toTikZ = function(size, maxY){
if(typeof size != n){ size = 1 }
var y = (typeof maxY == n && maxY > 0) ? maxY/size - this.y/size : this.y/size
return "\\draw (" + this.x/size + "," + y + ") node(v" + this.id + ") {};"
}
this.isNeighbour = function(v){
var e
for(var i in this.edges){
e = this.edges[i]
if(
(e.from === this && e.to === v) ||
(e.to === this && e.from === v)
){
return true
}
}
return false
}
this.edgeMultiplicity = function(v){
var e, c = 0
for(var i in this.edges){
e = this.edges[i]
if(
(e.from === this && e.to === v) ||
(e.to === this && e.from === v)
){
c++
}
}
return c
}
this.neighbours = function(){
var n = [], e
for(var i in this.edges){
e = this.edges[i]
if(e.from === this){
n.push(e.to)
} else if(e.to === this){
n.push(e.from)
}
}
return n
}
this.edgeGroupName = function(to){
var a = this.id, b = this.to.id
var c = (a <= b)
return (c ? a : b) + "," + (c ? b : a)
}
this.attach()
}
function Edge(id, value, from, to, directed){
if(typeof id != n){ return false }
if(typeof value != n && typeof value != s){ value = "" }
if(typeof from != o || typeof to != o){ return false }
if(typeof directed != b){ directed = false }
this.id = id
this.value = value
this.from = from
this.to = to
this.visible = true
this.style = defaultStyle
this.directed = directed
this.draw = function(cx, total, i){
this._draw(cx, this.style, true, total, i)
}
this.drawSel = function(cx, total, i){
this._draw(cx, selectedStyle, false, total, i)
}
this._draw = function(cx, style, label, total, i){
if(this.visible){
if(typeof total == u || total <= 0){ total = 1 }
if(typeof i == u || i < 0){ i = 0 }
// Edge curvature
var space = 50
var span = (total-1) * space
var t = -span/2 + i*space
//dlog(["Drawing", total, i, t])
// Draw!
// Edge goes from a to b, and a is to the left of b (this has do be rewritten when we introduced directed edges)
if(this.from.x < this.to.x) {
var ax = this.from.x
var ay = this.from.y
var bx = this.to.x
var by = this.to.y
} else {
var ax = this.to.x
var ay = this.to.y
var bx = this.from.x
var by = this.from.y
}
styleContext(cx, style, false)
cx.beginPath()
cx.moveTo(ax, ay)
if(t == 0){
// Straight edge
cx.lineTo(bx, by)
} else {
// Curved edge, part of multiedge
// Curve from a to b, over alpha.
// m is the midpoint of ab
var mx = ax + 0.5 * (bx - ax)
var my = ay + 0.5 * (by - ay)
// Length of am, since we need to normalize it
var l = Math.sqrt((ay-by)*(ay-by) + (bx-ax)*(bx-ax))
// Find the center point of the quadrature
var alphax = mx + t * (-my+ay)/l
var alphay = my + t * (mx-ax)/l
cx.quadraticCurveTo(alphax, alphay, bx, by)
}
cx.stroke()
//TODO: Draw arrowhead
if(label && (typeof this.value == s || typeof this.value == n) && this.value !== ""){
var mid = this.midpoint()
drawLabel(this.value, mid[0], mid[1])
}
}
}
this.update = function(graph){
}
this.attach = function(){
this.visible = true
edges.push(this)
this.from.edges.push(this)
this.to.edges.push(this)
this.from.degree++
this.to.degree++
}
this.detach = function(graph){
if(graph instanceof Graph){
graph.detachChild(this)
} else {
this.visible = false
listRemove(edges, this)
if(this.id in selected){ delete selected[this.id] } //listRemove(selected, this)
listRemove(this.from.edges, this)
listRemove(this.to.edges, this)
this.from.degree--
this.to.degree--
}
}
this.contract = function(graph){
var e, m = this.midpoint()
this.detach(graph)
dlog(this.from.edges)
for(var i in this.to.edges){
e = this.to.edges[i]
if(e.to == this.to){
e.to = this.from
}
if(e.from == this.to){
e.from = this.from
}
if(e.from == e.to){ // Contracted into nonexistance
this.to.edges.splice(i, 1)
e.detach(graph)
i--
}
this.from.edges.push(e)
}
dlog(this.from.edges)
this.to.edges = []
this.to.update()
this.to.detach(graph)
dlog([[this.from.x, this.from.y],[this.to.x, this.to.y],m])
this.from.x = m[0]
this.from.y = m[1]
this.from.update()
}
this.toJSON = function(){
return { id: this.id, value: this.value, from: this.from.id, to: this.to.id, directed: this.directed } // No style support yet
}
this.toTikZ = function(){
var n = ""
if(this.value !== ""){
n = " node {" + this.value + "}"
}
return "\\path[draw] (v" + this.from.id + ") -" + (this.directed ? ">" : "-") + n + " (v" + this.to.id + ");"
}
this.midpoint = function(){
return [(this.from.x + this.to.x)/2, (this.from.y + this.to.y)/2]
}
this.groupName = function(){
var a = this.from.id, b = this.to.id
var c = (a <= b)
return (c ? a : b) + "," + (c ? b : a)
}
this.attach()
}
// Graph manipulation methods -----------------------------------------------------------------------------------------------
function graphFromJSON(json){
if(typeof json != s){ return null }
try {
var o = JSON.parse(json)
} catch(e){
return null
}
var vertices = [], edges = [], j, v, from, to
for(var i in o.vertices){
j = o.vertices[i]
vertices.push(new Vertex(j.id, j.value, j.x, j.y))
// { id: this.id, value: this.value, x: this.x, y: this.y }
}
for(var i in o.edges){
j = o.edges[i]
for(var i in vertices){
v = vertices[i]
if(v.id == j.from){
from = v
}
if(v.id == j.to){
to = v
}
}
edges.push(new Edge(j.id, j.value, from, to, j.directed))
// { id: this.id, value: this.value, from: this.from.id, to: this.to.id }
}
var g = new Graph(vertices, edges)
g.x = o.x
g.y = o.y
return g
}
// Interface methods --------------------------------------------------------------------------------------------------------
// The canvas coordinates
function getElement(x, y){
var el, r
// Check if there's an element on the given coordinates; traverse in reverse order so we get the newest first
// Vertices
for(var i = vertices.length - 1; i >= 0; i--){
el = vertices[i]
r = el.style.vertexradius * (touch ? 3 : 1.5)
//w = el.style.strokewidth
if(
x >= el.x - r && x <= el.x + r &&
y >= el.y - r && y <= el.y + r
){
return el // This is the one!
}
}
// Edges
// New approach because of bezier curves
// Toletance tol (max distance from check point to mouse)
var tol = 3
var edgegroups = graphs[0].edgeGroups()
// We find points on e with distance h (in pixels)
var h = 5
for(var s in edgegroups){
//alert("Here")
g = edgegroups[s]
for(var i in g){
// Now we have edge e
var e = g[i]
// There is "total" edges in this group
var total = g.length
// This is number "i" of them
// Edge curvature
var space = 50
var span = (total-1) * space
var bend = -span/2 + i*space
// Curved edge, part of multiedge
// Curve from a to b, with control point alpha.
// m is the midpoint of ab
if(e.from.x < e.to.x) {
var ax = e.from.x
var ay = e.from.y
var bx = e.to.x
var by = e.to.y
} else {
var ax = e.to.x
var ay = e.to.y
var bx = e.from.x
var by = e.from.y
}
var mx = ax + 0.5 * (bx - ax)
var my = ay + 0.5 * (by - ay)
// Length of am, since we need to normalize it
var l = Math.sqrt((ay-by)*(ay-by) + (bx-ax)*(bx-ax))
// Find the center point of the quadrature
var alphax = mx + bend * (-my+ay)/l
var alphay = my + bend * (mx-ax)/l
// Now we have the following function of the quadratic curve Q(t)
// Q(t) = (1-t)^2 a + 2(1-t)t alpha + t^2 b, where t = 0..1
// Compute each of the d points
var n = l*2 // length of ab
// Take n/h steps of length h
for (var j = 0; j < n; j += h) {
// Find the corresponding value for t
var t = j/n
// Compute coordinates of Q(t) = [Qx,Qy]
var Qx = (1-t)*(1-t) * ax + 2*(1-t)*t * alphax + t*t * bx
var Qy = (1-t)*(1-t) * ay + 2*(1-t)*t * alphay + t*t * by
distToMouse = Math.sqrt((Qy-y)*(Qy-y) + (Qx-x)*(Qx-x))
if (distToMouse < tol) {
return e
}
}
}
}
return null // None found
}
function evtPosition(evt, ce){
var o = ce.offset()
// Previously layerX and layerY
var x = (iu(evt.clientX) ? (iu(evt.offsetX) ? evt.x : evt.offsetX) : evt.clientX) - o.left
var y = (iu(evt.clientY) ? (iu(evt.offsetY) ? evt.y : evt.offsetY) : evt.clientY) - o.top
return [x,y]
}
// Drawing
function drawAll(cx){
if(!cx){ cx = window.cx }
//dlog("DRAWING ALL")
var el
cx.clearRect(0, 0, w, h)
for(var i = 0; i < graphs.length; i++){
graphs[i].draw(cx)
}
// Selected item
if(selected.length > 0){
var graph = graphs[gi]
for(var n in selected){
el = selected[n]
if(el instanceof Vertex){// || el instanceof Edge){
el.drawSel(cx)
}
if(el instanceof Edge){
// Get edgegroup
var g = graphs[gi].edgeGroups(el.groupName())
for(var i in g){
if(g[i] == el){
g[i].drawSel(cx, g.length, i)
}
}
}
}
}
}
function drawLabel(label, x, y){
if((typeof label == s || typeof label == n) && label !== ""){
styleContext(cx, labelStyle)
cx.beginPath()
cx.arc(x, y, labelStyle.vertexradius*2, 0, 2*Math.PI, true)
cx.closePath()
cx.fill()
cx.stroke()
cx.fillStyle = "#000"
cx.fillText(label, x, y)
}
}
// Canvas events
function canvasMove(evt){
var p = evtPosition(evt, ce), el
var x = p[0]
var y = p[1]
if(dragging && uimode == GJ_TOOL_SELECT){
// Set dragging position
if(dp[0] == null){
dp = [x,y]
// Simulated hovering on touch devices
//if(touch){
hovered = getElement(x,y)
//}
}
// We're trying to drag an element
if(hovered != null){
// Set selection
if(!inArray(hovered, selected)){
setSelected(hovered, evt, cx)
dp = [x,y]
}
// Drag each selected element
for(var n in selected){
el = selected[n]
if(el instanceof Vertex){
// Set original vertex position
if(dp[0] == x && dp[1] == y){
el.ox = el.x
el.oy = el.y
}
// New coordinates
el.x = el.ox + (x - dp[0])
el.y = el.oy + (y - dp[1])
}
}
updateState() // <-- Inefficient
} else {
// We're dragging a rectangle of selection
var selection = graphs[gi].elementsWithinRect(dp[0], dp[1], x, y)
//selected = evt.shiftKey ? selected.concat(selection) : selection
if(!evt.shiftKey){ selected = [] }
for(var i in selection){
selected[selection[i].id] = selection[i]
}
drawAll()
cx.strokeStyle = "rgba(153,153,153,0.5)"
cx.lineWidth = 1
cx.strokeRect(dp[0], dp[1], x-dp[0], y-dp[1])
}
dontclick = true // Prevent click event on mouseup
} else {
//hovered = getElement(x,y)
if(uimode == GJ_TOOL_ADD_EDGE){
hovered = getElement(x,y)
if(touch && hovered instanceof Vertex){
dp[(dp[0] == null) ? 0 : 1] = hovered
selected = [hovered]
canvasFinishAddEdge(cx)
}
} else {
dp = [null,null]
}
}
}
function canvasClick(evt){
dlog(["CLICK", dragging, dontclick])
if(!dragging && !dontclick){
var p = evtPosition(evt, ce)
var x = p[0]
var y = p[1]
var el = getElement(x,y)
var alt = (evt.altKey || evt.ctrlKey)
dlog([el, uimode, $("#vertexautocomplete")])
if(uimode == GJ_TOOL_SELECT){
dlog(1)
setSelected(el, evt, cx)
updateState()
}
if(uimode == GJ_TOOL_SELECT && alt && evt.shiftKey && el instanceof Vertex){
dlog(2)
canvasStartAddEdge(cx)
}
if(uimode == GJ_TOOL_ADD_EDGE && el instanceof Vertex){
dlog(3)
dp[(dp[0] == null) ? 0 : 1] = el
selected = [el]
canvasFinishAddEdge(cx)
}
if((uimode == GJ_TOOL_ADD_VERTEX || (uimode == GJ_TOOL_SELECT && alt && !evt.shiftKey)) && el == null){
dlog(4)
canvasFinishAddVertex(x, y, cx)
}
}
if(dontclick){ dontclick = false }
}
function canvasKey(evt){
if(evt.target.tagName == "HTML"){
var k = evt.keyCode || evt.which
var up = 38, down = 40, left = 37, right = 39, s
if((k == up || k == down || k == left || k == right) && (selected.length > 0 && selected[0] != null)){
evt.preventDefault()
var inc = (k == down || k == right),
x = (k == left || k == right)
for(var i in selected){
s = selected[i]
if(s.x && s.y && !isNaN(s.x) && !isNaN(s.y)){
if(x){
s.x = inc ? s.x + 1 : s.x - 1
} else {
s.y = inc ? s.y + 1 : s.y - 1
}
}
}
drawAll()
displayInfo(ui.properties, selected)
}
}
}
// Touch events
function touchMove(evt){
if(evt.touches.length == 1 && evt.touches[0].target == canvas){
evt.preventDefault()
moved = true
var ct = evt.changedTouches
canvasMove({
layerX: ct[0].pageX,
layerY: ct[0].pageY
})
}
}
function touchEnd(evt){
//evt.preventDefault()
dragging = false
dp = [null,null]
var ct = evt.changedTouches
if(!moved && ct.length == 1 && ct[0].target == canvas){
canvasClick({
layerX: ct[0].pageX,
layerY: ct[0].pageY
})
}
moved = false
}
function touchStart(evt) {
if(evt.touches.length == 1 && evt.touches[0].target == canvas){
evt.preventDefault()
dragging = true
moved = false
var ct = evt.changedTouches
for(var i = 0; i < ct.length; i++){
var touch = ct[i]
canvasMove({
layerX: touch.pageX,
layerY: touch.pageY
})
return
}
}