-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathPackedLayout.cs
More file actions
2104 lines (1924 loc) · 80 KB
/
PackedLayout.cs
File metadata and controls
2104 lines (1924 loc) · 80 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
/*
* Copyright (c) Northwoods Software Corporation. All Rights Reserved.
*/
/*
* This is an extension and not part of the main GoDiagram library.
* Note that the API for this class may change with any version, even point releases.
* If you intend to use an extension in production, you should copy the code to your own source directory.
* Extensions can be found in the GoDiagram repository (https://github.com/NorthwoodsSoftware/GoDiagram/tree/main/Extensions).
* See the Extensions intro page (https://godiagram.com/intro/extensions.html) for more information.
*/
using System;
using System.Collections.Generic;
namespace Northwoods.Go.Layouts.Extensions {
internal class FuncComparer<T> : Comparer<T> {
private readonly Func<T, T, double> _Func;
public FuncComparer(Func<T, T, double> func) {
_Func = func;
}
public override int Compare(T x, T y) {
return (int)_Func(x, y);
}
}
/// <summary>
/// Used to represent the perimeter of the currently packed
/// shape when packing rectangles. Segments are always assumed
/// to be either horizontal or vertical, and store whether or
/// not their first point is concave (this makes sense in the
/// context of representing a perimeter, as the next segment
/// will always be connected to the last).
/// </summary>
internal class Segment {
public double X1;
public double Y1;
public double X2;
public double Y2;
public bool P1Concave;
public bool IsHorizontal; // if the segment is not horizontal, it is assumed to be vertical
/// <summary>
/// Constructs a new Segment. Segments are assumed to be either
/// horizontal or vertical, and the given coordinates should
/// reflect that.
/// </summary>
/// <param name="x1">the x coordinate of the first point</param>
/// <param name="y1">the y coordinate of the first point</param>
/// <param name="x2">the x coordinate of the second point</param>
/// <param name="y2">the y coordinate of the second point</param>
/// <param name="p1Concave">whether or not the first point is concave</param>
public Segment(double x1, double y1, double x2, double y2, bool p1Concave) {
X1 = x1;
Y1 = y1;
X2 = x2;
Y2 = y2;
P1Concave = p1Concave;
IsHorizontal = Math.Abs(y2 - y1) < 1e-7;
}
}
/// <summary>
/// Defines the possible orientations that two adjacent
/// horizontal/vertical segments can form.
/// </summary>
internal enum Orientation {
NE,
NW,
SW,
SE
}
/// <summary>
/// Structure for storing possible placements when packing
/// rectangles. Fits have a cost associated with them (lower
/// cost placements are preferred), and can be placed relative
/// to either one or two segments. If the fit is only placed
/// relative to one segment, s2 will be undefined. Fits placed
/// relative to multiple segments will hereafter be referred to
/// as "skip fits".
/// </summary>
internal class Fit {
public Rect Bounds;
public double Cost;
public PackedLayout.ListNode<Segment> S1;
public PackedLayout.ListNode<Segment> S2;
/// <summary>
/// Constructs a new Fit.
/// </summary>
/// <param name="bounds">the boundaries of the placement, including defined x and y coordinates</param>
/// <param name="cost">the cost of the placement, lower cost fits will be preferred</param>
/// <param name="s1">the segment that the placement was made relative to</param>
/// <param name="s2">the second segment that the placement was made relative to, if the fit is a skip fit</param>
public Fit(Rect bounds, double cost, PackedLayout.ListNode<Segment> s1, PackedLayout.ListNode<Segment> s2 = null) {
Bounds = bounds;
Cost = cost;
S1 = s1;
S2 = s2;
}
}
/// <summary>
/// A custom layout which attempts to pack nodes as close together as possible
/// without overlap.
/// </summary>
/// <remarks>
/// Each node is assumed to be either rectangular or
/// circular (dictated by the <see cref="HasCircularNodes"/> property). This layout
/// supports packing nodes into either a rectangle or an ellipse, with the
/// shape determined by the PackShape property and the aspect ratio determined
/// by either the AspectRatio property or the specified width and height
/// (depending on the PackMode).
///
/// Nodes with 0 width or height cannot be packed, so they are treated by this
/// layout as having a width or height of 0.1 instead.
/// </remarks>
/// @category Layout Extension
public class PackedLayout : Layout {
/// <summary>
/// Constructs a new PackedLayout.
/// </summary>
public PackedLayout() : base() { }
/// <summary>
/// Copies properties to a cloned Layout.
/// </summary>
[Undocumented]
protected override void CloneProtected(Layout c) {
if (c == null) return;
base.CloneProtected(c);
var copy = (PackedLayout)c;
copy.PackShape = PackShape;
copy.PackMode = PackMode;
copy.SortMode = SortMode;
copy.SortOrder = SortOrder;
copy.Comparer = Comparer;
copy.AspectRatio = AspectRatio;
copy.Size = Size;
copy.Spacing = Spacing;
copy.HasCircularNodes = HasCircularNodes;
copy.ArrangesToOrigin = ArrangesToOrigin;
}
/// <summary>
/// Gets or sets the shape that nodes will be packed into. Valid values are
/// <see cref="PackShape.Elliptical"/>, <see cref="PackShape.Rectangular"/>, and
/// <see cref="PackShape.Spiral"/>.
/// </summary>
/// <remarks>
/// In <see cref="PackShape.Spiral"/> mode, nodes are not packed into a particular
/// shape, but rather packed consecutively one after another in a spiral fashion.
/// The <see cref="AspectRatio"/> property is ignored in this mode, and
/// the <see cref="Size"/> property (if provided) is expected to be square.
/// If it is not square, the largest dimension given will be used. This mode
/// currently only works with circular nodes, so setting it cause the assume that
/// layout to assume that <see cref="HasCircularNodes"/> is true.
///
/// Note that this property sets only the shape, not the aspect ratio. The aspect
/// ratio of this shape is determined by either <see cref="AspectRatio"/>
/// or <see cref="Size"/>, depending on the <see cref="PackMode"/>.
///
/// When the <see cref="PackMode"/> is <see cref="PackMode.Fit"/> or
/// <see cref="PackMode.ExpandToFit"/> and this property is set to true, the
/// layout will attempt to make the diameter of the enclosing circle of the
/// layout approximately equal to the greater dimension of the given
/// <see cref="Size"/> property.
///
/// The default value is <see cref="PackShape.Elliptical"/>.
/// </remarks>
public PackShape PackShape {
get {
return _PackShape;
}
set {
if (_PackShape != value && (value == PackShape.Elliptical || value == PackShape.Rectangular || value == PackShape.Spiral)) {
_PackShape = value;
InvalidateLayout();
}
}
}
/// <summary>
/// Gets or sets the mode that the layout will use to determine its size.
/// </summary>
/// <remarks>
/// The default value is <see cref="PackMode.AspectOnly"/>. In this mode, the layout will simply
/// grow as needed, attempting to keep the aspect ratio defined by <see cref="AspectRatio"/>.
/// </remarks>
public PackMode PackMode {
get {
return _PackMode;
}
set {
if (value == PackMode.AspectOnly || value == PackMode.Fit || value == PackMode.ExpandToFit) {
_PackMode = value;
InvalidateLayout();
}
}
}
/// <summary>
/// Gets or sets the method by which nodes will be sorted before being packed. To change
/// the order, see <see cref="SortOrder"/>.
/// </summary>
/// <remarks>
/// The default value is <see cref="SortMode.None"/>, in which nodes will not be sorted at all.
/// </remarks>
public SortMode SortMode {
get {
return _SortMode;
}
set {
if (value == SortMode.None || value == SortMode.MaxSide || value == SortMode.Area) {
_SortMode = value;
InvalidateLayout();
}
}
}
/// <summary>
/// Gets or sets the order that nodes will be sorted in before being packed. To change
/// the sort method, see <see cref="SortMode"/>.
/// </summary>
/// <remarks>
/// The default value is <see cref="SortOrder.Descending"/>
/// </remarks>
public SortOrder SortOrder {
get {
return _SortOrder;
}
set {
if (value == SortOrder.Descending || value == SortOrder.Ascending) {
_SortOrder = value;
InvalidateLayout();
}
}
}
/// <summary>
/// Gets or sets the comparison function used for sorting nodes.
/// </summary>
/// <remarks>
/// By default, the comparison function is set according to the values of <see cref="SortMode"/>
/// and <see cref="SortOrder"/>.
///
/// Whether this comparison function is used is determined by the value of <see cref="SortMode"/>.
/// Any value except <see cref="SortMode.None"/> will result in the comparison function being used.
/// <code language="cs">
/// myDiagram.Layout = new VirtualizedPackedLayout {
/// SortMode = SortMode.Area,
/// Comparer = (na, nb) => {
/// var na = na.Data;
/// var nb = nb.Data;
/// if (da.SomeProperty < db.SomeProperty) return -1;
/// if (da.SomeProperty > db.SomeProperty) return 1;
/// return 0;
/// }
/// };
/// </code>
/// </remarks>
public Comparison<Node> Comparer {
get {
return _Comparer;
}
set {
if (value != null) {
_Comparer = value;
}
}
}
/// <summary>
/// Gets or sets the aspect ratio for the shape that nodes will be packed into.
/// </summary>
/// <remarks>
/// The provided aspect ratio should be a nonzero postive number.
///
/// Note that this only applies if the <see cref="PackMode"/> is
/// <see cref="PackMode.AspectOnly"/>. Otherwise, the <see cref="Size"/>
/// will determine the aspect ratio of the packed shape.
///
/// The default value is 1.
/// </remarks>
public double AspectRatio {
get {
return _AspectRatio;
}
set {
if (Util.IsFinite(value) && value > 0) {
_AspectRatio = value;
InvalidateLayout();
}
}
}
/// <summary>
/// Gets or sets the size for the shape that nodes will be packed into.
/// </summary>
/// <remarks>
/// To fill the viewport, set a size with a width and height of NaN. Size
/// values of 0 are considered for layout purposes to instead be 1.
///
/// If the width and height are set to NaN (to fill the viewport), but this
/// layout has no diagram associated with it, the default value of size will
/// be used instead.
///
/// Note that this only applies if the <see cref="PackMode"/> is
/// <see cref="PackMode.Fit"/> or <see cref="PackMode.ExpandToFit"/>.
///
/// The default value is 500x500.
/// </remarks>
public Size Size {
get {
return _Size;
}
set {
if (double.IsNaN(value.Width) && double.IsNaN(value.Height)) {
_Size = value;
_FillViewport = true;
InvalidateLayout();
} else if (Util.IsFinite(value.Width) && value.Width >= 0 &&
Util.IsFinite(value.Height) && value.Height >= 0) {
_Size = value;
InvalidateLayout();
}
}
}
/// <summary>
/// Gets or sets the spacing between nodes.
/// </summary>
/// <remarks>
/// This value can be set to any
/// real double (a negative spacing will compress nodes together, and a
/// positive spacing will leave space between them).
///
/// Note that the spacing value is only respected in the <see cref="PackMode.Fit"/>
/// <see cref="PackMode"/> if it does not cause the layout to grow outside
/// of the specified bounds. In the <see cref="PackMode.ExpandToFit"/>
/// <see cref="PackMode"/>, this property does not do anything.
///
/// The default value is 0.
/// </remarks>
public double Spacing {
get {
return _Spacing;
}
set {
if (Util.IsFinite(value)) {
_Spacing = value;
InvalidateLayout();
}
}
}
/// <summary>
/// Gets or sets whether or not to assume that nodes are circular. This changes
/// the packing algorithm to one that is much more efficient for circular nodes.
/// </summary>
/// <remarks>
/// As this algorithm expects circles, it is assumed that if this property is set
/// to true that the given nodes will all have the same height and width. All
/// calculations are done using the width of the given nodes, so unexpected results
/// may occur if the height differs from the width.
///
/// The default value is false.
/// </remarks>
public bool HasCircularNodes {
get {
return _HasCircularNodes;
}
set {
if (value != _HasCircularNodes) {
_HasCircularNodes = value;
InvalidateLayout();
}
}
}
/// <summary>
/// This read-only property is the effective spacing calculated after <see cref="DoLayout"/>.
/// </summary>
/// <remarks>
/// If the <see cref="PackMode"/> is <see cref="PackMode.AspectOnly"/>, this will simply be the
/// <see cref="Spacing"/> property. However, in the <see cref="PackMode.Fit"/> and
/// <see cref="PackMode.ExpandToFit"/> modes, this property will include the forced spacing added by
/// the modes themselves.
///
/// Note that this property will only return a valid value after a layout has been performed. Before
/// then, its behavior is undefined.
/// </remarks>
public double ActualSpacing {
get {
return Spacing + _FixedSizeModeSpacing;
}
}
/// <summary>
/// This read-only property returns the actual rectangular bounds occupied by the packed nodes.
/// </summary>
/// <remarks>
/// This property does not take into account any kind of spacing around the packed nodes.
///
/// Note that this property will only return a valid value after a layout has been performed. Before
/// then, its behavior is undefined.
/// </remarks>
public Rect ActualBounds {
get {
return _ActualBounds;
}
}
/// <summary>
/// This read-only property returns the smallest enclosing circle around the packed nodes.
/// </summary>
/// <remarks>
/// It makes use of the <see cref="HasCircularNodes"/> property to determine whether or not to make
/// enclosing circle calculations for rectangles or for circles. This property does not take into
/// account any kind of spacing around the packed nodes. The enclosing circle calculation is
/// performed the first time this property is retrieved, and then cached to prevent slow accesses
/// in the future.
///
/// Note that this property will only return a valid value after a layout has been performed. Before
/// then, its behavior is undefined.
///
/// This property is included as it may be useful for some data visualizations.
/// </remarks>
public Rect EnclosingCircle {
get {
if (_EnclosingCircle == null) {
if (HasCircularNodes || PackShape == PackShape.Spiral) { // remember, spiral mode assumes HasCircularNodes
var circles = new List<Circle>();
foreach (var bounds in _NodeBounds) {
var r = bounds.Width / 2;
circles.Add(new Circle(bounds.X + r, bounds.Y + r, r));
}
_EnclosingCircle = Enclose(circles);
} else {
var points = new List<Point>(); // TODO: make this work with segments, not the whole nodebounds list
var segment = _Segments.Start;
if (segment != null) {
do {
points.Add(new Point(segment.Data.X1, segment.Data.Y1));
segment = segment.Next;
} while (segment != _Segments.Start);
}
_EnclosingCircle = Enclose(points);
}
}
return _EnclosingCircle.Value;
}
}
/// <summary>
/// Gets or sets whether or not to use the <see cref="Layout.ArrangementOrigin"/>
/// property when placing nodes.
/// </summary>
/// <remarks>
/// The default value is true.
/// </remarks>
public bool ArrangesToOrigin {
get {
return _ArrangesToOrigin;
}
set {
if (value != _ArrangesToOrigin) {
_ArrangesToOrigin = value;
InvalidateLayout();
}
}
}
// configuration defaults
private PackShape _PackShape = PackShape.Elliptical;
private PackMode _PackMode = PackMode.AspectOnly;
private SortMode _SortMode = SortMode.None;
private SortOrder _SortOrder = SortOrder.Descending;
private Comparison<Node> _Comparer = null;
private double _AspectRatio = 1;
private Size _Size = new(500, 500);
private Size _DefaultSize = new(500, 500);
private bool _FillViewport = false; // true if size is (NaN, NaN)
private double _Spacing = 0;
private bool _HasCircularNodes = false;
private bool _ArrangesToOrigin = true;
/// <summary>
/// The forced spacing value applied in the <see cref="PackMode.Fit"/>
/// and <see cref="PackMode.ExpandToFit"/> modes.
/// </summary>
private double _FixedSizeModeSpacing = 0;
/// <summary>
/// The actual target aspect ratio, set from either <see cref="AspectRatio"/>
/// or from the <see cref="Size"/>, depending on the <see cref="PackMode"/>.
/// </summary>
private double _EAspectRatio = 1;
// layout state
private Point _Center = new();
private Rect _Bounds = new();
private Rect _ActualBounds = new();
private Rect? _EnclosingCircle = null;
private Segment _MinXSegment = null;
private Segment _MinYSegment = null;
private Segment _MaxXSegment = null;
private Segment _MaxYSegment = null;
private readonly Quadtree<Segment> _Tree = new();
// saved node bounds and segment list to use to calculate enclosing circle in the enclosingCircle getter
private List<Rect> _NodeBounds = new();
private CircularDoublyLinkedList<Segment> _Segments = new();
private readonly Random _Rand = new();
/// <summary>
/// Performs the PackedLayout.
/// </summary>
public override void DoLayout(IEnumerable<Part> coll = null) {
HashSet<Part> allparts;
if (coll != null) {
allparts = CollectParts(coll);
} else if (Group != null) {
allparts = CollectParts(Group);
} else if (Diagram != null) {
allparts = CollectParts(Diagram);
} else {
return; // Nothing to layout!
}
if (Diagram != null) Diagram.StartTransaction("Layout");
_Bounds = new Rect();
_EnclosingCircle = null;
_FixedSizeModeSpacing = 0;
// push all nodes in parts iterator to an array for easy sorting
var nodes = new List<Node>();
var averageSize = 0.0;
var maxSize = 0.0;
foreach (var part in allparts) {
if (part is Node node) {
nodes.Add(node);
averageSize += node.ActualBounds.Width + node.ActualBounds.Height;
if (node.ActualBounds.Width > maxSize) {
maxSize = node.ActualBounds.Width;
} else if (node.ActualBounds.Height > maxSize) {
maxSize = node.ActualBounds.Height;
}
}
}
averageSize /= (nodes.Count * 2);
if (averageSize < 1) {
averageSize = 1;
}
ArrangementOrigin = InitialOrigin(ArrangementOrigin);
if (SortMode != SortMode.None) {
if (Comparer == null) {
var sortOrder = SortOrder;
var sortMode = SortMode;
Comparer = (a, b) => {
var sortVal = sortOrder == SortOrder.Ascending ? 1 : -1;
if (sortMode == SortMode.MaxSide) {
var aMax = Math.Max(a.ActualBounds.Width, a.ActualBounds.Height);
var bMax = Math.Max(b.ActualBounds.Width, b.ActualBounds.Height);
if (aMax > bMax) {
return sortVal;
} else if (bMax > aMax) {
return -sortVal;
}
return 0;
} else if (sortMode == SortMode.Area) {
var area1 = a.ActualBounds.Width * a.ActualBounds.Height;
var area2 = b.ActualBounds.Width * b.ActualBounds.Height;
if (area1 > area2) {
return sortVal;
} else if (area2 > area1) {
return -sortVal;
}
return 0;
}
return 0;
};
}
nodes.Sort(Comparer);
}
var targetWidth = Size.Width != 0 ? Size.Width : 1;
var targetHeight = Size.Height != 0 ? Size.Height : 1;
if (_FillViewport && Diagram != null) {
targetWidth = Diagram.ViewportBounds.Width != 0 ? Diagram.ViewportBounds.Width : 1;
targetHeight = Diagram.ViewportBounds.Height != 0 ? Diagram.ViewportBounds.Height : 1;
} else if (_FillViewport) {
targetWidth = _DefaultSize.Width != 0 ? _DefaultSize.Width : 1;
targetHeight = _DefaultSize.Height != 0 ? _DefaultSize.Height : 1;
}
// set the target aspect ratio using the given bounds if necessary
if (PackMode == PackMode.Fit || PackMode == PackMode.ExpandToFit) {
_EAspectRatio = targetWidth / targetHeight;
} else {
_EAspectRatio = AspectRatio;
}
var fits = HasCircularNodes || PackShape == PackShape.Spiral ? FitCircles(nodes) : FitRects(nodes);
// in the Fit and ExpandToFit modes, we need to run the packing another time to figure out what the correct
// _FixedModeSpacing should be. Then the layout is run a final time with the correct spacing.
if (PackMode == PackMode.Fit || PackMode == PackMode.ExpandToFit) {
var bounds0 = _Bounds;
_Bounds = new Rect();
_FixedSizeModeSpacing = Math.Floor(averageSize);
fits = HasCircularNodes || PackShape == PackShape.Spiral ? FitCircles(nodes) : FitRects(nodes);
if ((HasCircularNodes || PackShape == PackShape.Spiral) && PackShape == PackShape.Spiral) {
var targetDiameter = Math.Max(targetWidth, targetHeight);
var oldDiameter = targetDiameter == targetWidth ? bounds0.Width : bounds0.Height;
var newDiameter = targetDiameter == targetWidth ? _Bounds.Width : _Bounds.Height;
var diff = (newDiameter - oldDiameter) / _FixedSizeModeSpacing;
_FixedSizeModeSpacing = (targetDiameter - oldDiameter) / diff;
} else {
var dx = (_Bounds.Width - bounds0.Width) / _FixedSizeModeSpacing;
var dy = (_Bounds.Height - bounds0.Height) / _FixedSizeModeSpacing;
var paddingX = (targetWidth - bounds0.Width) / dx;
var paddingY = (targetHeight - bounds0.Height) / dy;
_FixedSizeModeSpacing = Math.Abs(paddingX) > Math.Abs(paddingY) ? paddingX : paddingY;
}
if (PackMode == PackMode.Fit) {
// make sure that the spacing is not positive in this mode
_FixedSizeModeSpacing = Math.Min(_FixedSizeModeSpacing, 0);
}
if (_FixedSizeModeSpacing == double.PositiveInfinity) {
_FixedSizeModeSpacing = -maxSize;
}
_Bounds = new Rect();
fits = HasCircularNodes || PackShape == PackShape.Spiral ? FitCircles(nodes) : FitRects(nodes);
}
// move the nodes and calculate the ActualBounds property
if (ArrangesToOrigin) {
_ActualBounds = new Rect(ArrangementOrigin.X, ArrangementOrigin.Y, 0, 0);
}
var nodeBounds = new List<Rect>(nodes.Count);
for (var i = 0; i < nodes.Count; i++) {
var fit = fits[i];
var node = nodes[i];
if (ArrangesToOrigin) {
// translate coordinates to respect this.ArrangementOrigin
// this.ArrangementOrigin should be the top left corner of the bounding box around the layout
fit.X = fit.X - _Bounds.X + ArrangementOrigin.X;
fit.Y = fit.Y - _Bounds.Y + ArrangementOrigin.Y;
}
node.Move(fit.X, fit.Y);
nodeBounds.Add(node.ActualBounds);
_ActualBounds = _ActualBounds.Union(node.ActualBounds);
}
_NodeBounds = nodeBounds; // save node bounds in case we want to calculate the smallest enclosing circle later
// can be overriden to change layout behavior, doesn't do anything by default
CommitLayout();
if (Diagram != null) Diagram.CommitTransaction("Layout");
IsValidLayout = true;
}
/// <summary>
/// This method is called at the end of <see cref="DoLayout"/>, but
/// before the layout transaction is committed. It can be overriden and
/// used to customize layout behavior. By default, the method does nothing.
/// </summary>
public virtual void CommitLayout() { }
/// <summary>
/// Runs a circle packing algorithm on the given array of nodes. The
/// algorithm used is a slightly modified version of the one proposed
/// by Wang et al. in "Visualization of large hierarchical data by
/// circle packing", 2006.
/// </summary>
/// <param name="nodes">the array of Nodes to pack</param>
/// <returns>an array of positioned rectangles corresponding to the nodes argument</returns>
private List<Rect> FitCircles(List<Node> nodes) {
Rect place(Rect a, Rect b, Rect c) {
var ax = a.CenterX;
var ay = a.CenterY;
var da = (b.Width + c.Width) / 2;
var db = (a.Width + c.Width) / 2;
var dx = b.CenterX - ax;
var dy = b.CenterY - ay;
var dc = dx * dx + dy * dy;
if (dc != 0) {
var x = 0.5 + ((db *= db) - (da *= da)) / (2 * dc);
var y = Math.Sqrt(Math.Max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
c.X = (ax + x * dx + y * dy) - (c.Width / 2);
c.Y = (ay + x * dy - y * dx) - (c.Height / 2);
} else {
c.X = ax + db;
c.Y = ay;
}
return c;
}
bool intersects(Rect a, Rect b) {
var ar = a.Height / 2;
var br = b.Height / 2;
var dist = Math.Sqrt(a.Center.DistanceSquared(b.Center));
var difference = dist - (ar + br);
return difference < -0.0000001;
}
var aspect = _EAspectRatio;
var shape = PackShape;
double score(ListNode<Rect> n) {
var a = n.Data;
var b = n.Next.Data;
var ar = a.Width / 2;
var br = b.Width / 2;
var ab = ar + br;
var dx = (a.CenterX * br + b.CenterX * ar) / ab;
var dy = (a.CenterY * br + b.CenterY * ar) / ab * aspect;
return shape == PackShape.Elliptical ? dx * dx + dy * dy : Math.Max(dx * dx, dy * dy);
}
var sideSpacing = (Spacing + _FixedSizeModeSpacing) / 2;
var fits = new List<Rect>();
var frontChain = new CircularDoublyLinkedList<Rect>();
if (nodes.Count == 0) return fits;
var r1 = nodes[0].ActualBounds.Inflate(sideSpacing, sideSpacing);
r1 = new Rect(0, 0, r1.Width == 0 ? 0.1 : r1.Width, r1.Height == 0 ? 0.1 : r1.Height);
fits.Add(r1);
_Bounds = _Bounds.Union(r1);
if (nodes.Count < 2) return fits;
var r2 = nodes[1].ActualBounds.Inflate(sideSpacing, sideSpacing);
r2 = new Rect(0, 0, r2.Width == 0 ? 0.1 : r2.Width, r2.Height == 0 ? 0.1 : r2.Height);
r2 = new Rect(-r2.Width, r1.CenterY - r2.Width / 2, r2.Width, r2.Height);
fits.Add(r2);
_Bounds = _Bounds.Union(r2);
if (nodes.Count < 3) return fits;
var r3 = nodes[2].ActualBounds.Inflate(sideSpacing, sideSpacing);
r3 = new Rect(0, 0, r3.Width == 0 ? 0.1 : r3.Width, r3.Height == 0 ? 0.1 : r3.Height);
r3 = place(r2, r1, r3);
fits.Add(r3);
_Bounds = _Bounds.Union(r3);
var n2 = frontChain.Push(r2);
var n3 = frontChain.Push(r3);
var n1 = frontChain.Push(r1);
for (var i = 3; i < nodes.Count; i++) {
r3 = nodes[i].ActualBounds.Inflate(sideSpacing, sideSpacing);
r3 = new Rect(0, 0, r3.Width == 0 ? 0.1 : r3.Width, r3.Height == 0 ? 0.1 : r3.Height);
r3 = place(n1.Data, n2.Data, r3);
var j = n2.Next;
var k = n1.Prev;
var sj = n2.Data.Width / 2;
var sk = n1.Data.Width / 2;
var skip = false;
do {
if (sj <= sk) {
if (intersects(j.Data, r3)) {
n2 = frontChain.RemoveBetween(n1, j); i--;
skip = true; break;
}
sj += j.Data.Width / 2; j = j.Next;
} else {
if (intersects(k.Data, r3)) {
frontChain.RemoveBetween(k, n2);
n1 = k; i--;
skip = true; break;
}
sk += k.Data.Width / 2; k = k.Prev;
}
} while (j != k.Next);
if (skip) continue;
fits.Add(r3);
_Bounds = _Bounds.Union(r3);
n2 = n3 = frontChain.InsertAfter(r3, n1);
if (PackShape != PackShape.Spiral) {
var aa = score(n1);
while ((n3 = n3.Next) != n2) {
var ca = score(n3);
if (ca < aa) {
n1 = n3; aa = ca;
}
}
n2 = n1.Next;
}
}
return fits;
}
/// <summary>
/// Runs a rectangle packing algorithm on the given array of nodes.
/// </summary>
/// <remarks>
/// The algorithm presented is original, and operates by maintaining
/// a representation (with segments) of the perimeter of the already
/// packed shape. The perimeter of segments is stored in both a linked
/// list (for ordered iteration) and a quadtree (for fast intersection
/// detection). Similar to the circle packing algorithm presented
/// above, this is a greedy algorithm.
///
/// For each node, a large list of possible placements is created,
/// each one relative to a segment on the perimeter. These placements
/// are sorted according to a cost function, and then the lowest cost
/// placement with no intersections is picked. The perimeter
/// representation is then updated according to the new placement.
///
/// However, in addition to placements made relative to a single segment
/// on the perimeter, the algorithm also attempts to make placements
/// between two nonsequential segments ("skip fits"), closing gaps in the
/// packed shape. If a placement made in this way has no intersections
/// and a lower cost than any of the original placements, it is picked
/// instead. This step occurs simultaneously to checking intersections on
/// the original placement list.
///
/// Intersections for new placements are checked only against the current
/// perimeter of segments, rather than the entire packed shape.
/// Additionally, before the quadtree is queried at all, a few closely
/// surrounding segments to the placement are checked in case an
/// intersection can be found more quickly. The combination of these two
/// strategies enables intersection checking to take place extremely
/// quickly, when it would normally be the slowest part of the entire
/// algorithm.
/// </remarks>
/// <param name="nodes">the array of Nodes to pack</param>
/// <returns>an array of positioned rectangles corresponding to the nodes argument</returns>
private List<Rect> FitRects(List<Node> nodes) {
var sideSpacing = (Spacing + _FixedSizeModeSpacing) / 2;
var fits = new List<Rect>();
var segments = new CircularDoublyLinkedList<Segment>();
// reset layout state
_Tree.Clear();
_MinXSegment = null;
_MaxXSegment = null;
_MinYSegment = null;
_MaxYSegment = null;
if (nodes.Count < 1) {
return fits;
}
// place first node at 0, 0
var bounds0 = nodes[0].ActualBounds;
fits.Add(new Rect(sideSpacing, sideSpacing, bounds0.Width, bounds0.Height));
fits[0] = fits[0].Inflate(sideSpacing, sideSpacing);
fits[0] = new Rect(0, 0, fits[0].Width == 0 ? 0.1 : fits[0].Width, fits[0].Height == 0 ? 0.1 : fits[0].Height);
_Bounds = _Bounds.Union(fits[0]);
_Center = fits[0].Center;
var s1 = new Segment(0, 0, fits[0].Width, 0, false);
var s2 = new Segment(fits[0].Width, 0, fits[0].Width, fits[0].Height, false);
var s3 = new Segment(fits[0].Width, fits[0].Height, 0, fits[0].Height, false);
var s4 = new Segment(0, fits[0].Height, 0, 0, false);
_Tree.Add(s1, RectFromSegment(s1));
_Tree.Add(s2, RectFromSegment(s2));
_Tree.Add(s3, RectFromSegment(s3));
_Tree.Add(s4, RectFromSegment(s4));
segments.Push(s1, s2, s3, s4);
FixMissingMinMaxSegments(true);
for (var i = 1; i < nodes.Count; i++) {
var node = nodes[i];
var bounds = node.ActualBounds.Inflate(sideSpacing, sideSpacing);
bounds = new Rect(0, 0, bounds.Width == 0 ? 0.1 : bounds.Width, bounds.Height == 0 ? 0.1 : bounds.Height);
var possibleFits = new List<Fit>(segments.Length);
var j = 0;
var s = segments.Start as ListNode<Segment>;
do {
// make sure segment is perfectly straight (fixing some floating point error)
var sdata = s.Data;
sdata.X1 = s.Prev.Data.X2;
sdata.Y1 = s.Prev.Data.Y2;
if (sdata.IsHorizontal) {
sdata.Y2 = sdata.Y1;
} else {
sdata.X2 = sdata.X1;
}
var fitBounds = GetBestFitRect(s, bounds.Width, bounds.Height);
var cost = PlacementCost(fitBounds);
possibleFits.Add(new Fit(fitBounds, cost, s));
s = s.Next;
j++;
} while (s != segments.Start);
possibleFits.Sort(new FuncComparer<Fit>((a, b) => {
return a.Cost - b.Cost;
}));
/* scales the cost of skip fits. a number below
* one makes skip fits more likely to appear,
* which is preferable because they are more
* aesthetically pleasing and reduce the total
* double of segments.
*/
var skipFitScaleFactor = 0.98;
Fit bestFit = null;
var onlyCheckSkipFits = false;
foreach (var fit in possibleFits) {
if (bestFit != null && bestFit.Cost <= fit.Cost) {
onlyCheckSkipFits = true;
}
var hasIntersections = true; // set initially to true to make skip fit checking work when onlyCheckSkipFits = true
if (!onlyCheckSkipFits) {
hasIntersections = FastFitHasIntersections(fit) || FitHasIntersections(fit);
if (!hasIntersections) {
bestFit = fit;
continue;
}
}
// check skip fits
if (hasIntersections && !fit.S1.Data.P1Concave && (fit.S1.Next.Data.P1Concave || fit.S1.Next.Next.Data.P1Concave)) {
(var nextSegment, var usePreviousSegment) = FindNextOrientedSegment(fit, fit.S1.Next);
var nextSegmentTouchesFit = false;
while (hasIntersections && nextSegment != null) {
fit.Bounds = RectAgainstMultiSegment(fit.S1, nextSegment, bounds.Width, bounds.Height);
hasIntersections = FastFitHasIntersections(fit) || FitHasIntersections(fit);
nextSegmentTouchesFit = SegmentIsOnFitPerimeter(nextSegment.Data, fit.Bounds);
if (hasIntersections || !nextSegmentTouchesFit) {
(nextSegment, usePreviousSegment) = FindNextOrientedSegment(fit, nextSegment);
}
}
if (!hasIntersections && nextSegment != null && nextSegmentTouchesFit) {
fit.Cost = PlacementCost(fit.Bounds) * skipFitScaleFactor;
if (bestFit == null || fit.Cost <= bestFit.Cost) {
bestFit = fit;
bestFit.S2 = nextSegment;
if (usePreviousSegment) {
bestFit.S1 = bestFit.S1.Prev;
}
}
}
}
}
if (bestFit != null) {
UpdateSegments(bestFit, segments);
fits.Add(bestFit.Bounds);
_Bounds = _Bounds.Union(bestFit.Bounds);
}
}
// save segments in case we want to calculate the enclosing circle later
_Segments = segments;
return fits;
}
/// <summary>
/// Attempts to find a segment which can be used to create a new skip fit
/// between fit.S1 and the found segment. A number of conditions are checked
/// before returning a segment, ensuring that if the skip fit *does* intersect
/// with the already packed shape, it will do so along the perimeter (so that it
/// can be detected with only knowledge about the perimeter). Multiple oriented
/// segments can be found for a given fit, so this function starts searching at
/// the segment after the given lastSegment parameter.
///
/// Oriented segments can be oriented with either fit.S1, or fit.S1.Prev. The
/// second return value (usePreviousSegment) indicates which the found segment is.
/// </summary>
/// <param name="fit">the fit to search for a new segment for</param>
/// <param name="lastSegment">the last segment found.</param>