Repository navigation
Expand file tree
/
Copy pathlayout.go
More file actions
1725 lines (1610 loc) · 55.3 KB
/
Copy pathlayout.go
File metadata and controls
1725 lines (1610 loc) · 55.3 KB
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
package layout
import (
"cmp"
"math"
"slices"
"github.com/loov/layout/internal/hier"
)
const epsilon = 1e-6
// peripheryGap is the distance between a node's extra outlines
const peripheryGap = 4 * Point
// pointRadius is the default radius of a PointShape node
const pointRadius = 3 * Point
// Hierarchical lays out the graph top-down in ranks (Sugiyama style):
// cycles are broken, nodes are assigned to ranks, ordered within ranks to
// reduce crossings, positioned, and finally edge paths are computed.
//
// The graph is not modified. It fails when an edge refers to a node that
// is not part of the graph.
func Hierarchical(graph *Graph, opts Options) (*Layout, error) {
if err := graph.validate(); err != nil {
return nil, err
}
work := newWorkGraph(graph)
work.ForText = opts.ForText
hierarchical(work, opts)
work.placeEndLabels()
l := work.result()
if !opts.NoCompact && work.Splines == SplinesOrtho && !work.Pinned {
grid := pointGrid(l.Graph)
if work.ForText {
grid = textGrid(l.Graph)
}
compact(l, grid)
if !work.ForText {
slideFieldEnds(l, work.trackSpace())
}
}
return l, nil
}
// Options tunes the hierarchical layout. The zero value gives the defaults.
type Options struct {
// OrderIterations is the number of crossing reduction sweeps;
// 0 uses the default of 24. More sweeps can help on large graphs.
OrderIterations int
// OrderGroups moves whole subtrees while ordering: mirrored, or
// swapped with the one beside them, across all their ranks. It finds
// fewer crossings than sweeps alone, in about twice the time.
OrderGroups bool
// NoRankBalance keeps nodes that could go on several ranks at the
// topmost one instead of spreading them over the least crowded ranks.
NoRankBalance bool
// Align shifts nodes along their ranks, see Align constants.
Align Align
// ForText lays the graph out for format/text: ortho splines, rows
// between ranks for the horizontal runs and arrowheads, and nodes
// sized in character cells, compacted as Compact does unless the
// layout is pinned. Layout.Graph has the changed settings.
ForText bool
// NoCompact leaves the room in the layout. Otherwise, with ortho
// splines, which ForText uses, the layout is compacted after routing:
// nodes, the runs of edges, labels and clusters are pushed together
// along x and then y, while edges stretch and shrink to follow, and
// the nodes of a rank stay in line. Edges keep their crossings and
// nodes their order. Other splines are not compacted: sloped segments
// would have to stay rigid and compact little. For ForText it moves
// objects by whole character cells; format/text draws a layout as it
// is, so one left uncompacted keeps all its room.
NoCompact bool
}
// Align picks how nodes are spread along their ranks. In left-to-right
// and right-to-left layouts, left is the top and right the bottom.
type Align int
const (
// AlignBalanced centers nodes among their neighbors, keeping long
// edges straight and the layout narrow.
AlignBalanced Align = iota
// AlignLeft puts nodes over their first neighbor in the rank before
// and packs the layout to the left.
AlignLeft
// AlignRight puts nodes over their last neighbor in the rank before
// and packs the layout to the right.
AlignRight
)
// Presets for Options: Fast trades crossings for speed on large graphs,
// Quality spends more sweeps and moves subtrees looking for a better order.
var (
Fast = Options{OrderIterations: 4}
Quality = Options{OrderIterations: 96, OrderGroups: true}
)
// labelSide is the side of an edge, in the top to bottom frame, that its
// label goes on: right of downward edges, and above sideways ones, which
// is the left in the frame
func labelSide(dir RankDir) float32 {
if dir.Sideways() {
return -1
}
return 1
}
// compassInRankFrame maps a physical port into the top-to-bottom frame.
func compassInRankFrame(port Compass, dir RankDir) Compass {
compass := [...]Compass{North, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest}
i := slices.Index(compass[:], port)
if i < 0 {
return port // automatic and center ports do not change
}
switch dir {
case LeftToRight:
return compass[(14-i)%8]
case RightToLeft:
return compass[(i+6)%8]
case BottomToTop:
return compass[(12-i)%8]
default:
return port
}
}
// hierarchical lays out the working copy of a validated graph.
func hierarchical(graphdef *lgraph, opts Options) {
if opts.OrderIterations <= 0 {
opts.OrderIterations = hier.DefaultOrderIterations
}
if graphdef.ForText {
graphdef.prepareText()
}
graphdef.assignDefaults()
if graphdef.Pinned {
layoutPinned(graphdef)
return
}
graphdef.resolveFields()
// edges are updated in place below, an edge listed twice only once
edges := uniqueEdges(graphdef.Edges)
// Compass directions are physical directions, so map them into the
// rank frame the layout works in.
for _, edge := range edges {
edge.FromPort = compassInRankFrame(edge.FromPort, graphdef.RankDir)
edge.ToPort = compassInRankFrame(edge.ToPort, graphdef.RankDir)
}
// lay out top to bottom in a transposed/flipped frame, then map back
sideways := graphdef.RankDir.Sideways()
swapRadii := func() {
for _, node := range graphdef.Nodes {
node.Radius.X, node.Radius.Y = node.Radius.Y, node.Radius.X
node.pad.X, node.pad.Y = node.pad.Y, node.pad.X
}
for _, edge := range edges {
edge.LabelRadius.X, edge.LabelRadius.Y = edge.LabelRadius.Y, edge.LabelRadius.X
}
}
if sideways {
swapRadii()
}
defer func() {
// mirror within the bounds, measured in the frame, so that flipped
// layouts keep their margins
lo, hi := graphdef.Bounds()
if sideways {
swapRadii()
}
transform := func(p Vector) Vector {
switch graphdef.RankDir {
case LeftToRight:
return Vector{X: p.Y, Y: p.X}
case RightToLeft:
return Vector{X: lo.Y + hi.Y - p.Y, Y: p.X}
case BottomToTop:
return Vector{X: p.X, Y: lo.Y + hi.Y - p.Y}
}
return p
}
for _, node := range graphdef.Nodes {
node.Center = transform(node.Center)
}
for _, edge := range edges {
for i, p := range edge.Path {
edge.Path[i] = transform(p)
}
edge.LabelPos = transform(edge.LabelPos)
}
for _, cluster := range graphdef.Clusters {
a, b := transform(cluster.TopLeft), transform(cluster.BottomRight)
cluster.TopLeft = Vector{min(a.X, b.X), min(a.Y, b.Y)}
cluster.BottomRight = Vector{max(a.X, b.X), max(a.Y, b.Y)}
}
}()
// the components share it, see lgraph.merged
graphdef.merged = map[*ledge][2]int{}
left := Length(0)
for _, component := range components(graphdef) {
hierarchicalComponent(component, opts)
_, size := component.Bounds()
shift := Vector{X: left}
for _, node := range component.Nodes {
node.Center = node.Center.Add(shift)
}
for _, edge := range uniqueEdges(component.Edges) {
for i, p := range edge.Path {
edge.Path[i] = p.Add(shift)
}
edge.LabelPos = edge.LabelPos.Add(shift)
}
for _, cluster := range component.Clusters {
cluster.TopLeft = cluster.TopLeft.Add(shift)
cluster.BottomRight = cluster.BottomRight.Add(shift)
}
left += size.X + 2*graphdef.NodePadding
}
}
// uniqueEdges returns edges without repeats of the same edge
func uniqueEdges(edges []*ledge) []*ledge {
seen := make(map[*ledge]bool, len(edges))
return slices.DeleteFunc(slices.Clone(edges), func(edge *ledge) bool {
repeat := seen[edge]
seen[edge] = true
return repeat
})
}
// components splits the graph into connected components, each a Graph
// sharing the original nodes, edges and settings. Components are laid out
// independently and then placed side by side.
func components(graphdef *lgraph) []*lgraph {
index := make(map[*lnode]int, len(graphdef.Nodes))
for i, node := range graphdef.Nodes {
index[node] = i
}
parent := make([]int, len(graphdef.Nodes))
for i := range parent {
parent[i] = i
}
findIndex := func(i int) int {
for parent[i] != i {
parent[i] = parent[parent[i]] // path halving
i = parent[i]
}
return i
}
find := func(n *lnode) *lnode { return graphdef.Nodes[findIndex(index[n])] }
union := func(a, b *lnode) { parent[findIndex(index[a])] = findIndex(index[b]) }
for _, edge := range graphdef.Edges {
union(edge.From, edge.To)
}
for _, group := range graphdef.SameRank {
for _, node := range group[1:] {
union(group[0], node)
}
}
for _, cluster := range graphdef.Clusters {
for _, node := range cluster.Nodes[1:] {
union(cluster.Nodes[0], node)
}
}
// min/max pinned nodes share a rank, treat them as connected
for _, pinned := range [][]*lnode{graphdef.MinRank, graphdef.MaxRank} {
for _, node := range pinned {
union(pinned[0], node)
}
}
byRoot := map[*lnode]*lgraph{}
var result []*lgraph
sub := func(node *lnode) *lgraph {
root := find(node)
graph := byRoot[root]
if graph == nil {
part := *graphdef
part.Nodes = nil
part.Edges = nil
part.SameRank = nil
part.MinRank = nil
part.MaxRank = nil
part.Clusters = nil
graph = &part
byRoot[root] = graph
result = append(result, graph)
}
return graph
}
for _, node := range graphdef.Nodes {
g := sub(node)
g.Nodes = append(g.Nodes, node)
}
for _, edge := range graphdef.Edges {
g := sub(edge.From)
g.Edges = append(g.Edges, edge)
}
for _, group := range graphdef.SameRank {
g := sub(group[0])
g.SameRank = append(g.SameRank, group)
}
for _, node := range graphdef.MinRank {
g := sub(node)
g.MinRank = append(g.MinRank, node)
}
for _, node := range graphdef.MaxRank {
g := sub(node)
g.MaxRank = append(g.MaxRank, node)
}
for _, cluster := range graphdef.Clusters {
if len(cluster.Nodes) == 0 {
continue
}
g := sub(cluster.Nodes[0])
g.Clusters = append(g.Clusters, cluster)
}
return result
}
// hierComponent is the state shared by the stages that lay out one
// connected graph, see hierarchicalComponent
type hierComponent struct {
graphdef *lgraph
opts Options
graph *hier.Graph
nodes map[*lnode]hier.ID
reverse map[hier.ID]*lnode
// nodes with self-loops need room on their right for the loop and
// its label
loopWidth, loopHeight Length
loopExtra map[*lnode]Length
loopLeft map[*lnode]Length // loops with ports may also pass the left side
// with packed edge ends, the first end of a node is where its
// edges line up, see packed
pack bool
clusters map[*lcluster]*hier.Cluster
// how far the box of a sideways cluster reaches past its first and
// last ranks for its label, see reserveClusterLabels
labelReach map[*hier.Cluster]float32
// the part of labelReach a box reaches past its first rank, the rest
// past its last; half when missing
labelUp map[*hier.Cluster]float32
labelNode map[*hier.Node][]*ledge // the labels the middle virtual node of an edge carries
parallel map[*ledge]int // which of the parallel hierarchical edges an edge runs as, see build
added map[[2]hier.ID]int // how many hierarchical edges build added by (src, dst)
flatBelow map[*lnode]Length // room below a node for the labels of edges along its rank
align hier.Align
// buffers that route fills again on every call, see route
byRank [][]*lnode
edgePaths map[*hier.Edge]Path
pathBlock Path
}
// hierarchicalComponent lays out one connected graph top to bottom,
// placing it to the right of whatever the previous components occupy.
func hierarchicalComponent(graphdef *lgraph, opts Options) {
c := newHierComponent(graphdef, opts)
c.build()
c.rank()
c.addClusters()
c.fieldPorts()
c.order()
c.reserveEnds()
c.reserveFlatLabels()
c.sizeNodes()
c.reserveClusterLabels()
c.position()
if graphdef.ForText && graphdef.Splines == SplinesOrtho && c.align == hier.Balanced {
c.route()
straightenNodes(c.graph, graphdef, c.route)
}
c.finish()
}
// newHierComponent returns the state for laying out graphdef, with the
// room that self-loops need
func newHierComponent(graphdef *lgraph, opts Options) *hierComponent {
c := &hierComponent{
graphdef: graphdef,
opts: opts,
nodes: map[*lnode]hier.ID{},
reverse: map[hier.ID]*lnode{},
loopExtra: map[*lnode]Length{},
loopLeft: map[*lnode]Length{},
pack: graphdef.PackEdgeEnds && graphdef.Splines == SplinesOrtho,
clusters: map[*lcluster]*hier.Cluster{},
labelNode: map[*hier.Node][]*ledge{},
parallel: map[*ledge]int{},
flatBelow: map[*lnode]Length{},
}
c.loopWidth = max(graphdef.NodePadding, 2*graphdef.EdgePadding)
c.loopHeight = min(c.loopWidth, graphdef.RowPadding)
for _, edge := range graphdef.Edges {
if edge.loop() {
extra := c.loopWidth
if edge.Label != "" {
extra += graphdef.EdgePadding + 2*edge.LabelRadius.X
}
c.loopExtra[edge.From] = max(c.loopExtra[edge.From], extra)
if edge.ported() {
c.loopLeft[edge.From] = max(c.loopLeft[edge.From], extra)
}
}
}
return c
}
// loopShift returns how far left of the center of its widened box a node
// widened for loops sits
func (c *hierComponent) loopShift(node *lnode) Length {
return -(c.loopExtra[node] - c.loopLeft[node]) / 2
}
// packed returns where the edges of a node line up with packed edge ends,
// this far from its center: an edge padding inside its innermost outline
func (c *hierComponent) packed(node *lnode) Length {
if !c.pack || node.Shape == PointShape {
return 0
}
return min(0, c.graphdef.EdgePadding+outlines(node)-node.Radius.X)
}
// labelSpan returns the length of the box side along a cluster's label
func (c *hierComponent) labelSpan(cluster *lcluster) Length {
return 2 * (c.graphdef.textRadius(cluster.Label, "", c.graphdef.FontSize).X + c.graphdef.EdgePadding)
}
// labelRow returns the height of the row a cluster's label takes under its
// top; sideways the label runs along the ranks instead, see labelSpan. In
// text a cluster without a label has a row as tall too, as text draws the
// top on the line above the first node, which leaves no row for the
// arrowheads of edges coming in otherwise
func (c *hierComponent) labelRow(cluster *lcluster) Length {
label := cluster.Label
switch {
case c.graphdef.RankDir.Sideways(), label == "" && !c.graphdef.ForText:
return 0
case label == "":
label = " "
}
return 2 * c.graphdef.textRadius(label, "", c.graphdef.FontSize).Y
}
// outlines returns the room the extra outlines of a node take
func outlines(node *lnode) Length { return Length(max(node.Peripheries-1, 0)) * peripheryGap }
// endSpacing is the least distance between the ends of edges along a
// node's side, see spreadEnds
const endSpacing Length = 9 * Point
// unorderedPair returns a and b in increasing order
func unorderedPair(a, b hier.ID) [2]hier.ID {
if a > b {
a, b = b, a
}
return [2]hier.ID{a, b}
}
// build constructs the hierarchical graph with its rank constraints
func (c *hierComponent) build() {
c.graph = &hier.Graph{}
for _, nodedef := range c.graphdef.Nodes {
node := c.graph.AddNode()
c.nodes[nodedef] = node.ID
c.reverse[node.ID] = nodedef
node.Label = nodedef.ID
}
// parallel edges with the same ends share one hierarchical edge,
// which weighs as much as all of them, so that ordering keeps the
// others off the bundle; the longest wins. Edges to other ports of
// the nodes keep their own, which find their ports, see fieldPorts.
type ends struct {
from, to *lnode
fromField, toField string
fromPort, toPort Compass
}
seen := map[ends]int{} // the parallel edge of the first with those ends
added := map[[2]hier.ID]int{}
c.added = added
drawn := map[[2]hier.ID]bool{}
for _, edge := range c.graphdef.Edges {
from, to := c.hends(edge)
if pair := [2]hier.ID{from.ID, to.ID}; edge.Invisible && !drawn[pair] {
if c.graph.Unseen == nil {
c.graph.Unseen = map[[2]hier.ID]bool{}
}
c.graph.Unseen[pair] = true
} else {
drawn[pair] = true
delete(c.graph.Unseen, pair)
}
k := ends{edge.From, edge.To, edge.FromField, edge.ToField, edge.FromPort, edge.ToPort}
if n, ok := seen[k]; ok {
c.parallel[edge] = n
c.graph.SetWeight(from, to, c.graph.Weight(from, to)+float32(edge.Weight))
c.graph.SetMinLen(from, to, max(int32(edge.MinLen), c.graph.MinLen(from, to)))
continue
}
pair := [2]hier.ID{from.ID, to.ID}
seen[k] = added[pair]
c.parallel[edge] = added[pair]
added[pair]++
if slices.Contains(from.Out, to) {
c.graph.AddEdge(from, to) // weighs as the first
} else {
c.graph.AddWeightedEdge(from, to, float32(edge.Weight))
}
c.graph.SetMinLen(from, to, max(int32(edge.MinLen), c.graph.MinLen(from, to)))
}
for _, nodedef := range c.graphdef.MinRank {
c.graph.MinRank.Append(c.hnode(nodedef))
}
for _, nodedef := range c.graphdef.MaxRank {
c.graph.MaxRank.Append(c.hnode(nodedef))
}
for _, group := range c.graphdef.SameRank {
var members hier.Nodes
for _, nodedef := range group {
members = append(members, c.hnode(nodedef))
}
c.graph.SameRank = append(c.graph.SameRank, members)
}
}
// rank removes cycles, assigns nodes to ranks and adds virtual nodes
// along the edges that cross ranks
func (c *hierComponent) rank() {
// remove cycles
hier.Decycle(c.graph)
// assign nodes to ranks
hier.RankWith(c.graph, !c.opts.NoRankBalance)
// labeled edges need a virtual node to hang the label on; doubling the
// ranks guarantees every edge has one in the middle
if slices.ContainsFunc(c.graphdef.Edges, func(edge *ledge) bool { return edge.Label != "" && !edge.loop() }) {
hier.DoubleRanks(c.graph)
}
for _, edge := range c.graphdef.Edges {
edge.flat = c.hnode(edge.From).Rank == c.hnode(edge.To).Rank
}
c.unmergeReversed()
// create virtual nodes
hier.AddVirtuals(c.graph)
hier.TraceEdges(c.graph)
}
// unmergeReversed gives the edges that decycling merged back their own
// chains: an edge reversed to break a cycle merges into the edges the
// other way between its nodes, but it starts and ends elsewhere on them,
// at its own fields, so it runs and is ordered on its own; parallel edges
// to different fields likewise. The reversed come after the others, see
// hierEdge.
func (c *hierComponent) unmergeReversed() {
for _, src := range c.graph.Nodes {
for _, dst := range slices.Clone(src.Out) {
want := c.added[[2]hier.ID{src.ID, dst.ID}] + c.added[[2]hier.ID{dst.ID, src.ID}]
for have := countOf(src.Out, dst); have < want; have++ {
c.graph.AddEdge(src, dst)
}
}
}
}
// countOf returns how many times node is in nodes
func countOf(nodes hier.Nodes, node *hier.Node) int {
n := 0
for _, x := range nodes {
if x == node {
n++
}
}
return n
}
// hnode returns the hierarchical node of node
func (c *hierComponent) hnode(node *lnode) *hier.Node { return c.graph.Nodes[c.nodes[node]] }
// hends returns the hierarchical nodes at the ends of edge
func (c *hierComponent) hends(edge *ledge) (from, to *hier.Node) {
return c.hnode(edge.From), c.hnode(edge.To)
}
// besideOnRank reports whether a and b are next to each other on a rank
func besideOnRank(a, b *hier.Node) bool {
return a.Rank == b.Rank && posApart(a, b) == 1
}
// posApart returns how many places apart a and b are on their ranks
func posApart(a, b *hier.Node) int {
return max(a.Pos-b.Pos, b.Pos-a.Pos)
}
// hierEdge returns the hierarchical edge that edge runs as, and whether
// it runs backward, see hier.Graph.EdgeBetween
func (c *hierComponent) hierEdge(edge *ledge) (*hier.Edge, bool) {
from, to := c.hends(edge)
e, reversed := c.graph.EdgeBetween(from, to, c.parallel[edge])
if reversed {
// after the edges that run the other way, see unmergeReversed
e, _ = c.graph.EdgeBetween(from, to, c.added[[2]hier.ID{to.ID, from.ID}]+c.parallel[edge])
}
return e, reversed
}
// addClusters adds the borders of the clusters
func (c *hierComponent) addClusters() {
for _, clusterdef := range c.graphdef.Clusters {
cluster := &hier.Cluster{}
if clusterdef.Label != "" && !c.graphdef.RankDir.Sideways() {
// room for the label across the top, with padding beside it;
// sideways the label runs along the ranks, see labelSpan
// across the borders, which the box keeps half of
cluster.MinWidth = float32(c.labelSpan(clusterdef) + c.graphdef.EdgePadding)
}
for _, nodedef := range clusterdef.Nodes {
cluster.Members.Append(c.hnode(nodedef))
}
c.clusters[clusterdef] = cluster
c.graph.Clusters = append(c.graph.Clusters, cluster)
}
for clusterdef, cluster := range c.clusters {
cluster.Parent = c.clusters[clusterdef.Parent]
}
hier.AddClusterBorders(c.graph)
}
// order orders the nodes in ranks, finds the middle virtual node of every
// labeled edge, which carries the labels, and merges edges
func (c *hierComponent) order() {
c.graph.ShiftClusters = c.graphdef.Splines != SplinesOrtho
hier.OrderRanksN(c.graph, c.opts.OrderIterations, c.opts.OrderGroups)
// the middle virtual node of every labeled edge carries its labels
for _, edge := range c.graphdef.Edges {
if edge.Label == "" || edge.loop() {
continue
}
if e, _ := c.hierEdge(edge); e != nil && len(e.Chain) > 0 {
mid := e.Chain[len(e.Chain)/2]
c.labelNode[mid] = append(c.labelNode[mid], edge)
}
}
if c.graphdef.MergeEdges && c.graphdef.Splines == SplinesOrtho {
mergeEdges(c.graphdef.merged, c.graphdef.Edges, func(node *lnode) int { return c.hnode(node).Rank })
}
}
// reserveEnds widens nodes for their edge ends, which need room on each
// side of a node: packed ends an edge padding apart, from an edge padding
// in; for text, a cell each; otherwise endSpacing apart, as spreadEnds
// spreads them, so that a node with many edges has a side long enough
// for them all (Rüegg et al., "Size- and Port-Aware Horizontal Node
// Coordinate Assignment", 2015)
func (c *hierComponent) reserveEnds() {
{
step := endSpacing / 2
switch {
case c.pack:
step = c.graphdef.EdgePadding / 2
case c.graphdef.ForText:
step = c.graphdef.cellWidth() / 2
}
ends := map[*lnode][2]int{} // above and below, by rank
// merged ends take one end a group
type slot struct {
node *lnode
below bool
group int
}
counted := map[slot]bool{}
count := func(ends map[*lnode][2]int, node *lnode, below bool, group int) {
k := slot{node, below, group}
if group != 0 && counted[k] {
return
}
counted[k] = true
// above, or before, at 0 and below, or after, at 1
e := ends[node]
if below {
e[1]++
} else {
e[0]++
}
ends[node] = e
}
// sideways in text, flat edges leave along the top and bottom of
// the drawing, which are the sides of the frame here; they need a
// cell each across the frame, as ends between ranks do along it
flat := map[*lnode][2]int{} // before and after along the rank
for _, edge := range c.graphdef.Edges {
from, to := c.hends(edge)
// in text, ends at ports, and of loops, need a cell each on
// their side too
for i, end := range []struct {
node *lnode
port Compass
}{{edge.From, edge.FromPort}, {edge.To, edge.ToPort}} {
if !c.graphdef.ForText {
break
}
port := end.port // in the rank frame already, see hierarchical
if edge.loop() && port == CompassAuto {
port = East // see loopPath
}
group := c.graphdef.merged[edge][i]
switch port {
case North, NorthEast, NorthWest:
count(ends, end.node, false, group)
case South, SouthEast, SouthWest:
count(ends, end.node, true, group)
case West:
count(flat, end.node, false, group)
case East:
count(flat, end.node, true, group)
}
}
if from.Rank == to.Rank {
if c.graphdef.ForText && c.pack && !edge.loop() {
count(flat, edge.From, from.Pos < to.Pos, c.graphdef.mergeGroup(edge, true))
count(flat, edge.To, to.Pos < from.Pos, c.graphdef.mergeGroup(edge, false))
}
continue // loops and flat edges leave sideways
}
below := from.Rank < to.Rank
if edge.FromPort == CompassAuto {
count(ends, edge.From, below, c.graphdef.mergeGroup(edge, true))
}
if edge.ToPort == CompassAuto {
count(ends, edge.To, !below, c.graphdef.mergeGroup(edge, false))
}
}
for node, e := range flat {
if node.Shape == PointShape {
continue
}
// a line each across the frame, a column sideways
node.reserveHalfHeight(Length(max(e[0], e[1])+1) * c.graphdef.cell().Y / 2)
}
for node, e := range ends {
if node.Shape == PointShape {
continue // edges meet at the dot
}
grow := Length(max(e[0], e[1])+1)*step + outlines(node) - node.Radius.X
if !c.pack && !c.graphdef.ForText {
// at most twice as wide: past that ends crowd rather
// than the node dwarf its neighbors; packed ends and text
// need their room to draw
grow = min(grow, node.Radius.X)
}
if grow <= 0 {
continue
}
pad := Vector{X: grow}
if node.Shape == Circle || node.Shape == Square {
pad.Y = grow
}
node.Radius = node.Radius.Add(pad)
node.pad = node.pad.Add(pad)
}
}
// edges along a rank between the same nodes run side by side, see
// assignPaths, so their nodes need room across the rank for them all
lanes := map[[2]hier.ID]int{}
for _, edge := range c.graphdef.Edges {
from, to := c.hends(edge)
if !edge.loop() && from.Rank == to.Rank {
lanes[unorderedPair(from.ID, to.ID)]++
}
}
spacing := c.laneSpacing()
for pair, n := range lanes {
if n < 2 {
continue
}
for _, id := range pair {
node := c.reverse[id]
if node.Shape == PointShape {
continue
}
need := Length(n+1)*spacing/2 + outlines(node)
if c.graphdef.ForText {
need += spacing / 2 // a cell to spare, which rounding can take
if c.graphdef.RankDir.Sideways() && node.Shape == Octagon {
need += spacing // past the slanted corners on the top and bottom
}
}
node.reserveHalfHeight(need)
}
}
}
// laneSpacing is how far apart edges along a rank between the same nodes
// run, side by side across the rank
func (c *hierComponent) laneSpacing() Length {
if !c.graphdef.ForText {
return 2 * c.graphdef.EdgePadding
}
return c.graphdef.cell().Y // a line apart, a column sideways
}
// reserveFlatLabels makes room for the label of an edge between neighbors
// on a rank: between them, on the right of the left one as for loops, and
// beside the edge within the rank, which it may be taller than, see
// placeFlatLabels
func (c *hierComponent) reserveFlatLabels() {
for _, edge := range c.graphdef.Edges {
from, to := c.hends(edge)
if edge.Label == "" || edge.loop() || !besideOnRank(from, to) {
continue
}
left := edge.From
if to.Pos < from.Pos {
left = edge.To
}
// neighbors are already two node paddings apart
c.loopExtra[left] += max(0, 2*(edge.LabelRadius.X+c.graphdef.EdgePadding-c.graphdef.NodePadding))
below := c.graphdef.EdgePadding + 2*edge.LabelRadius.Y
c.flatBelow[edge.From] = max(c.flatBelow[edge.From], below)
c.flatBelow[edge.To] = max(c.flatBelow[edge.To], below)
}
}
// sizeNodes assigns the sizes of the hierarchical nodes
func (c *hierComponent) sizeNodes() {
defer c.widenParallel()
for id, node := range c.graph.Nodes {
if node.Virtual {
node.Radius.X = float32(c.graphdef.EdgePadding)
if c.graphdef.Splines == SplinesOrtho && !c.graphdef.ForText {
// edges running down side by side a track apart
node.Radius.X = float32(c.graphdef.trackSpace() / 2)
}
node.Radius.Y = float32(c.graphdef.EdgePadding)
if edges, ok := c.labelNode[node]; ok {
var width, height Length
for _, edge := range edges {
width = max(width, edge.LabelRadius.X)
height += edge.LabelRadius.Y
}
node.Radius.X += float32(width + c.graphdef.EdgePadding)
node.Radius.Y = float32(height + c.graphdef.EdgePadding)
// the edge passes on one side, the labels stack on the
// other, see labelSide
node.Anchor = -labelSide(c.graphdef.RankDir) * (node.Radius.X - float32(c.graphdef.EdgePadding))
node.Carrier = true
}
continue
}
nodedef := c.reverse[hier.ID(id)]
node.Radius.X = float32(nodedef.Radius.X + c.graphdef.NodePadding)
// room for loops on the right, and the left with ports: the box
// grows by both, and the node sits left of the box center by the
// difference, where its edges line up with the neighbors
node.Radius.X += float32((c.loopExtra[nodedef] + c.loopLeft[nodedef]) / 2)
node.Anchor = float32(c.loopShift(nodedef) + c.packed(nodedef))
if c.pack && nodedef.Shape != PointShape {
// see the slots of packed ends in orthoEdges
node.EndRoom = float32(2 * (nodedef.Radius.X - min(c.graphdef.EdgePadding, nodedef.Radius.X)))
}
node.Radius.Y = float32(max(nodedef.Radius.Y, c.flatBelow[nodedef]) + c.graphdef.RowPadding)
}
}
// widenParallel widens the virtual nodes of the edges between the same
// two nodes, which share them, by as far as assignPaths spreads the edges
// apart, so that positioning keeps the other edges clear of them
func (c *hierComponent) widenParallel() {
pairs := map[[2]hier.ID]int{}
for _, edge := range c.graphdef.Edges {
if !edge.loop() {
pairs[unorderedPair(c.nodes[edge.From], c.nodes[edge.To])]++
}
}
for _, source := range c.graph.Nodes {
if source.Virtual {
continue
}
for _, out := range source.Out {
target := out.ChainEnd()
n := pairs[unorderedPair(source.ID, target.ID)]
if n <= 1 {
continue
}
for v := range out.Chain() {
v.Radius.X += float32(Length(n-1) * c.graphdef.EdgePadding)
}
}
}
}
// reserveClusterLabels reserves room for the cluster box lines and the
// label strip by making the cluster's first and last border nodes taller
// than their ranks; outer clusters first so nested boxes stack
func (c *hierComponent) reserveClusterLabels() {
grow := func(borders []*hier.Node, rank int, extra float32) {
half := float32(0)
for _, node := range c.graph.ByRank[rank] {
half = max(half, node.Radius.Y)
}
for _, node := range borders {
node.Radius.Y = half + extra
}
}
// span returns how far the box of a cluster will reach along the
// ranks: ranks are stacked their half heights apart, and the box spans
// its members, see the cluster boxes below
span := func(clusterdef *lcluster, cluster *hier.Cluster) Length {
half := func(rank int) float32 {
h := float32(0)
for _, node := range c.graph.ByRank[rank] {
h = max(h, node.Radius.Y)
}
return h
}
center := map[int]float32{cluster.MinRank: 0}
for rank := cluster.MinRank + 1; rank <= cluster.MaxRank; rank++ {
center[rank] = center[rank-1] + half(rank-1) + half(rank)
}
top, bottom := float32(math.Inf(1)), float32(math.Inf(-1))
for _, nodedef := range clusterdef.Nodes {
rank := c.hnode(nodedef).Rank
top = min(top, center[rank]-float32(nodedef.Radius.Y))
bottom = max(bottom, center[rank]+float32(nodedef.Radius.Y))
}
return Length(bottom-top) + c.graphdef.RowPadding
}
for _, clusterdef := range c.graphdef.Clusters {
cluster := c.clusters[clusterdef]
pad := float32(c.graphdef.RowPadding / 2)
top, bottom := pad, pad
top += float32(c.labelRow(clusterdef))
if clusterdef.Label != "" && c.graphdef.RankDir.Sideways() {
// the label runs along the ranks: the box reaches as far on
// both sides, into the ranks next to it where they leave room,
// see clearClusterLabels
if short := float32(max(0, c.labelSpan(clusterdef)-span(clusterdef, cluster))) / 2; short > 0 {
if c.labelReach == nil {
c.labelReach = map[*hier.Cluster]float32{}
}
c.labelReach[cluster] = short
}
}
last := len(cluster.Left) - 1
grow([]*hier.Node{cluster.Left[0], cluster.Right[0]}, cluster.MinRank, top)
grow([]*hier.Node{cluster.Left[last], cluster.Right[last]}, cluster.MaxRank, bottom)
}
}
// position positions the nodes in their ranks
func (c *hierComponent) position() {
c.align = map[Align]hier.Align{AlignBalanced: hier.Balanced, AlignLeft: hier.Left, AlignRight: hier.Right}[c.opts.Align]
if c.pack && !c.graphdef.MergeEdges {
// see the slots of packed ends in orthoEdges; merged ends share one
c.graph.EndGap = float32(c.graphdef.EdgePadding)
if c.graphdef.Splines == SplinesOrtho && !c.graphdef.ForText {
c.graph.EndGap = float32(c.graphdef.trackSpace())
}
}
c.graph.AlignPorts = c.graphdef.Splines == SplinesOrtho && !c.graphdef.ForText
if c.graphdef.ForText && c.graphdef.MergeEdges {
// a cell between the fans of different nodes, as merged edges
// center a node's children on it
c.graph.FamilyGap = float32(c.graphdef.cell().X)