Refactor ElkSharp hybrid routing and document speed path
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
namespace StellaOps.ElkSharp;
|
||||
|
||||
internal static class ElkCompoundLayout
|
||||
internal static partial class ElkCompoundLayout
|
||||
{
|
||||
internal static ElkLayoutResult Layout(
|
||||
ElkGraph graph,
|
||||
@@ -298,560 +297,4 @@ internal static class ElkCompoundLayout
|
||||
};
|
||||
}
|
||||
|
||||
private static ElkNode[][] OptimizeLayerOrderingForHierarchy(
|
||||
ElkNode[][] initialLayers,
|
||||
IReadOnlyDictionary<string, List<string>> incomingNodeIds,
|
||||
IReadOnlyDictionary<string, List<string>> outgoingNodeIds,
|
||||
IReadOnlyDictionary<string, int> inputOrder,
|
||||
int iterationCount,
|
||||
ElkCompoundHierarchy hierarchy,
|
||||
IReadOnlySet<string> dummyNodeIds)
|
||||
{
|
||||
var layers = initialLayers
|
||||
.Select(layer => layer.ToList())
|
||||
.ToArray();
|
||||
var effectiveIterations = Math.Max(1, iterationCount);
|
||||
|
||||
for (var iteration = 0; iteration < effectiveIterations; iteration++)
|
||||
{
|
||||
for (var layerIndex = 1; layerIndex < layers.Length; layerIndex++)
|
||||
{
|
||||
OrderLayerWithHierarchy(layers, layerIndex, incomingNodeIds, inputOrder, hierarchy, dummyNodeIds);
|
||||
}
|
||||
|
||||
for (var layerIndex = layers.Length - 2; layerIndex >= 0; layerIndex--)
|
||||
{
|
||||
OrderLayerWithHierarchy(layers, layerIndex, outgoingNodeIds, inputOrder, hierarchy, dummyNodeIds);
|
||||
}
|
||||
}
|
||||
|
||||
return layers
|
||||
.Select(layer => layer.ToArray())
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static void OrderLayerWithHierarchy(
|
||||
IReadOnlyList<List<ElkNode>> layers,
|
||||
int layerIndex,
|
||||
IReadOnlyDictionary<string, List<string>> adjacentNodeIds,
|
||||
IReadOnlyDictionary<string, int> inputOrder,
|
||||
ElkCompoundHierarchy hierarchy,
|
||||
IReadOnlySet<string> dummyNodeIds)
|
||||
{
|
||||
var currentLayer = layers[layerIndex];
|
||||
if (currentLayer.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var positions = ElkNodeOrdering.BuildNodeOrderPositions(layers);
|
||||
var layerNodesById = currentLayer.ToDictionary(node => node.Id, StringComparer.Ordinal);
|
||||
var realNodeIdsInLayer = currentLayer
|
||||
.Where(node => !dummyNodeIds.Contains(node.Id))
|
||||
.Select(node => node.Id)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
var orderedRealIds = OrderNodesForSubtree(
|
||||
null,
|
||||
hierarchy,
|
||||
realNodeIdsInLayer,
|
||||
adjacentNodeIds,
|
||||
positions,
|
||||
inputOrder);
|
||||
var orderedDummies = currentLayer
|
||||
.Where(node => dummyNodeIds.Contains(node.Id))
|
||||
.OrderBy(node => ElkNodeOrdering.ResolveOrderingRank(node.Id, adjacentNodeIds, positions))
|
||||
.ThenBy(node => positions[node.Id])
|
||||
.ThenBy(node => inputOrder[node.Id])
|
||||
.ToArray();
|
||||
|
||||
currentLayer.Clear();
|
||||
foreach (var nodeId in orderedRealIds)
|
||||
{
|
||||
currentLayer.Add(layerNodesById[nodeId]);
|
||||
}
|
||||
|
||||
currentLayer.AddRange(orderedDummies);
|
||||
}
|
||||
|
||||
private static List<string> OrderNodesForSubtree(
|
||||
string? parentNodeId,
|
||||
ElkCompoundHierarchy hierarchy,
|
||||
IReadOnlySet<string> realNodeIdsInLayer,
|
||||
IReadOnlyDictionary<string, List<string>> adjacentNodeIds,
|
||||
IReadOnlyDictionary<string, int> positions,
|
||||
IReadOnlyDictionary<string, int> inputOrder)
|
||||
{
|
||||
var blocks = new List<HierarchyOrderBlock>();
|
||||
foreach (var childNodeId in hierarchy.GetChildIds(parentNodeId))
|
||||
{
|
||||
if (realNodeIdsInLayer.Contains(childNodeId))
|
||||
{
|
||||
blocks.Add(BuildBlock([childNodeId]));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!hierarchy.IsCompoundNode(childNodeId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var descendantNodeIds = OrderNodesForSubtree(
|
||||
childNodeId,
|
||||
hierarchy,
|
||||
realNodeIdsInLayer,
|
||||
adjacentNodeIds,
|
||||
positions,
|
||||
inputOrder);
|
||||
if (descendantNodeIds.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
blocks.Add(BuildBlock(descendantNodeIds));
|
||||
}
|
||||
|
||||
return blocks
|
||||
.OrderBy(block => block.Rank)
|
||||
.ThenBy(block => block.MinCurrentPosition)
|
||||
.ThenBy(block => block.MinInputOrder)
|
||||
.SelectMany(block => block.NodeIds)
|
||||
.ToList();
|
||||
|
||||
HierarchyOrderBlock BuildBlock(IReadOnlyList<string> nodeIds)
|
||||
{
|
||||
var ranks = new List<double>();
|
||||
foreach (var nodeId in nodeIds)
|
||||
{
|
||||
var nodeRank = ElkNodeOrdering.ResolveOrderingRank(nodeId, adjacentNodeIds, positions);
|
||||
if (!double.IsInfinity(nodeRank))
|
||||
{
|
||||
ranks.Add(nodeRank);
|
||||
}
|
||||
}
|
||||
|
||||
ranks.Sort();
|
||||
var rank = ranks.Count switch
|
||||
{
|
||||
0 => double.PositiveInfinity,
|
||||
_ when ranks.Count % 2 == 1 => ranks[ranks.Count / 2],
|
||||
_ => (ranks[(ranks.Count / 2) - 1] + ranks[ranks.Count / 2]) / 2d,
|
||||
};
|
||||
return new HierarchyOrderBlock(
|
||||
nodeIds,
|
||||
rank,
|
||||
nodeIds.Min(nodeId => positions.GetValueOrDefault(nodeId, int.MaxValue)),
|
||||
nodeIds.Min(nodeId => inputOrder.GetValueOrDefault(nodeId, int.MaxValue)));
|
||||
}
|
||||
}
|
||||
|
||||
private static ElkRoutedEdge[] InsertCompoundBoundaryCrossings(
|
||||
IReadOnlyCollection<ElkRoutedEdge> routedEdges,
|
||||
IReadOnlyDictionary<string, ElkPositionedNode> positionedNodes,
|
||||
ElkCompoundHierarchy hierarchy)
|
||||
{
|
||||
return routedEdges
|
||||
.Select(edge =>
|
||||
{
|
||||
var path = ExtractPath(edge);
|
||||
if (path.Count < 2)
|
||||
{
|
||||
return edge;
|
||||
}
|
||||
|
||||
var lcaNodeId = hierarchy.GetLowestCommonAncestor(edge.SourceNodeId, edge.TargetNodeId);
|
||||
var sourceAncestorIds = hierarchy.GetAncestorIdsNearestFirst(edge.SourceNodeId)
|
||||
.TakeWhile(ancestorNodeId => !string.Equals(ancestorNodeId, lcaNodeId, StringComparison.Ordinal))
|
||||
.ToArray();
|
||||
var targetAncestorIds = hierarchy.GetAncestorIdsNearestFirst(edge.TargetNodeId)
|
||||
.TakeWhile(ancestorNodeId => !string.Equals(ancestorNodeId, lcaNodeId, StringComparison.Ordinal))
|
||||
.ToArray();
|
||||
if (sourceAncestorIds.Length == 0 && targetAncestorIds.Length == 0)
|
||||
{
|
||||
return edge;
|
||||
}
|
||||
|
||||
var rebuiltPath = path.ToList();
|
||||
var startSegmentIndex = 0;
|
||||
foreach (var ancestorNodeId in sourceAncestorIds)
|
||||
{
|
||||
if (!positionedNodes.TryGetValue(ancestorNodeId, out var ancestorNode))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TryFindBoundaryTransitionFromStart(rebuiltPath, ancestorNode, startSegmentIndex, out var insertIndex, out var boundaryPoint))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
rebuiltPath.Insert(insertIndex, boundaryPoint);
|
||||
startSegmentIndex = insertIndex;
|
||||
}
|
||||
|
||||
var endSegmentIndex = rebuiltPath.Count - 2;
|
||||
foreach (var ancestorNodeId in targetAncestorIds)
|
||||
{
|
||||
if (!positionedNodes.TryGetValue(ancestorNodeId, out var ancestorNode))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TryFindBoundaryTransitionFromEnd(rebuiltPath, ancestorNode, endSegmentIndex, out var insertIndex, out var boundaryPoint))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
rebuiltPath.Insert(insertIndex, boundaryPoint);
|
||||
endSegmentIndex = insertIndex - 2;
|
||||
}
|
||||
|
||||
return BuildEdgeWithPath(edge, rebuiltPath);
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static List<ElkPoint> ExtractPath(ElkRoutedEdge edge)
|
||||
{
|
||||
var path = new List<ElkPoint>();
|
||||
foreach (var section in edge.Sections)
|
||||
{
|
||||
AppendPoint(path, section.StartPoint);
|
||||
foreach (var bendPoint in section.BendPoints)
|
||||
{
|
||||
AppendPoint(path, bendPoint);
|
||||
}
|
||||
|
||||
AppendPoint(path, section.EndPoint);
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
private static ElkRoutedEdge BuildEdgeWithPath(ElkRoutedEdge edge, IReadOnlyList<ElkPoint> path)
|
||||
{
|
||||
var normalizedPath = NormalizePath(path);
|
||||
if (normalizedPath.Count < 2)
|
||||
{
|
||||
return edge;
|
||||
}
|
||||
|
||||
return edge with
|
||||
{
|
||||
Sections =
|
||||
[
|
||||
new ElkEdgeSection
|
||||
{
|
||||
StartPoint = normalizedPath[0],
|
||||
EndPoint = normalizedPath[^1],
|
||||
BendPoints = normalizedPath.Count > 2
|
||||
? normalizedPath.Skip(1).Take(normalizedPath.Count - 2).ToArray()
|
||||
: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
private static bool TryFindBoundaryTransitionFromStart(
|
||||
IReadOnlyList<ElkPoint> path,
|
||||
ElkPositionedNode boundaryNode,
|
||||
int startSegmentIndex,
|
||||
out int insertIndex,
|
||||
out ElkPoint boundaryPoint)
|
||||
{
|
||||
insertIndex = -1;
|
||||
boundaryPoint = default!;
|
||||
for (var segmentIndex = Math.Max(0, startSegmentIndex); segmentIndex < path.Count - 1; segmentIndex++)
|
||||
{
|
||||
var from = path[segmentIndex];
|
||||
var to = path[segmentIndex + 1];
|
||||
if (!IsInsideOrOn(boundaryNode, from) || IsInsideOrOn(boundaryNode, to))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TryResolveBoundaryTransition(boundaryNode, from, to, exitBoundary: true, out boundaryPoint))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
insertIndex = segmentIndex + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryFindBoundaryTransitionFromEnd(
|
||||
IReadOnlyList<ElkPoint> path,
|
||||
ElkPositionedNode boundaryNode,
|
||||
int startSegmentIndex,
|
||||
out int insertIndex,
|
||||
out ElkPoint boundaryPoint)
|
||||
{
|
||||
insertIndex = -1;
|
||||
boundaryPoint = default!;
|
||||
for (var segmentIndex = Math.Min(startSegmentIndex, path.Count - 2); segmentIndex >= 0; segmentIndex--)
|
||||
{
|
||||
var from = path[segmentIndex];
|
||||
var to = path[segmentIndex + 1];
|
||||
if (IsInsideOrOn(boundaryNode, from) || !IsInsideOrOn(boundaryNode, to))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TryResolveBoundaryTransition(boundaryNode, from, to, exitBoundary: false, out boundaryPoint))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
insertIndex = segmentIndex + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryResolveBoundaryTransition(
|
||||
ElkPositionedNode boundaryNode,
|
||||
ElkPoint from,
|
||||
ElkPoint to,
|
||||
bool exitBoundary,
|
||||
out ElkPoint boundaryPoint)
|
||||
{
|
||||
boundaryPoint = default!;
|
||||
if (!Clip(boundaryNode, from, to, out var enterScale, out var exitScale))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var scale = exitBoundary ? exitScale : enterScale;
|
||||
scale = Math.Clamp(scale, 0d, 1d);
|
||||
boundaryPoint = new ElkPoint
|
||||
{
|
||||
X = from.X + ((to.X - from.X) * scale),
|
||||
Y = from.Y + ((to.Y - from.Y) * scale),
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool Clip(
|
||||
ElkPositionedNode node,
|
||||
ElkPoint from,
|
||||
ElkPoint to,
|
||||
out double enterScale,
|
||||
out double exitScale)
|
||||
{
|
||||
enterScale = 0d;
|
||||
exitScale = 1d;
|
||||
|
||||
var deltaX = to.X - from.X;
|
||||
var deltaY = to.Y - from.Y;
|
||||
return ClipTest(-deltaX, from.X - node.X, ref enterScale, ref exitScale)
|
||||
&& ClipTest(deltaX, (node.X + node.Width) - from.X, ref enterScale, ref exitScale)
|
||||
&& ClipTest(-deltaY, from.Y - node.Y, ref enterScale, ref exitScale)
|
||||
&& ClipTest(deltaY, (node.Y + node.Height) - from.Y, ref enterScale, ref exitScale);
|
||||
|
||||
static bool ClipTest(double p, double q, ref double enter, ref double exit)
|
||||
{
|
||||
if (Math.Abs(p) <= 0.0001d)
|
||||
{
|
||||
return q >= -0.0001d;
|
||||
}
|
||||
|
||||
var ratio = q / p;
|
||||
if (p < 0d)
|
||||
{
|
||||
if (ratio > exit)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ratio > enter)
|
||||
{
|
||||
enter = ratio;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ratio < enter)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ratio < exit)
|
||||
{
|
||||
exit = ratio;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsInsideOrOn(ElkPositionedNode node, ElkPoint point)
|
||||
{
|
||||
const double tolerance = 0.01d;
|
||||
return point.X >= node.X - tolerance
|
||||
&& point.X <= node.X + node.Width + tolerance
|
||||
&& point.Y >= node.Y - tolerance
|
||||
&& point.Y <= node.Y + node.Height + tolerance;
|
||||
}
|
||||
|
||||
private static List<ElkPoint> NormalizePath(IReadOnlyList<ElkPoint> path)
|
||||
{
|
||||
var normalized = new List<ElkPoint>(path.Count);
|
||||
foreach (var point in path)
|
||||
{
|
||||
AppendPoint(normalized, point);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static void AppendPoint(ICollection<ElkPoint> path, ElkPoint point)
|
||||
{
|
||||
if (path.Count > 0 && path.Last() is { } previousPoint && AreSamePoint(previousPoint, point))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
path.Add(new ElkPoint { X = point.X, Y = point.Y });
|
||||
}
|
||||
|
||||
private static bool AreSamePoint(ElkPoint left, ElkPoint right) =>
|
||||
Math.Abs(left.X - right.X) <= 0.01d
|
||||
&& Math.Abs(left.Y - right.Y) <= 0.01d;
|
||||
|
||||
private static Dictionary<string, ElkPositionedNode> BuildCompoundPositionedNodes(
|
||||
IReadOnlyCollection<ElkNode> graphNodes,
|
||||
ElkCompoundHierarchy hierarchy,
|
||||
IReadOnlyDictionary<string, ElkPositionedNode> positionedVisibleNodes,
|
||||
ElkLayoutOptions options)
|
||||
{
|
||||
var nodesById = graphNodes.ToDictionary(node => node.Id, StringComparer.Ordinal);
|
||||
var compoundNodes = new Dictionary<string, ElkPositionedNode>(StringComparer.Ordinal);
|
||||
foreach (var pair in positionedVisibleNodes)
|
||||
{
|
||||
if (!hierarchy.IsLayoutVisibleNode(pair.Key))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
compoundNodes[pair.Key] = pair.Value;
|
||||
}
|
||||
|
||||
foreach (var nodeId in hierarchy.GetNonLeafNodeIdsByDescendingDepth())
|
||||
{
|
||||
var childBounds = hierarchy.GetChildIds(nodeId)
|
||||
.Select(childNodeId => compoundNodes[childNodeId])
|
||||
.ToArray();
|
||||
var contentLeft = childBounds.Min(node => node.X);
|
||||
var contentTop = childBounds.Min(node => node.Y);
|
||||
var contentRight = childBounds.Max(node => node.X + node.Width);
|
||||
var contentBottom = childBounds.Max(node => node.Y + node.Height);
|
||||
|
||||
var desiredWidth = (contentRight - contentLeft) + (options.CompoundPadding * 2d);
|
||||
var desiredHeight = (contentBottom - contentTop) + options.CompoundHeaderHeight + (options.CompoundPadding * 2d);
|
||||
var width = Math.Max(nodesById[nodeId].Width, desiredWidth);
|
||||
var height = Math.Max(nodesById[nodeId].Height, desiredHeight);
|
||||
var x = contentLeft - options.CompoundPadding - ((width - desiredWidth) / 2d);
|
||||
var y = contentTop - options.CompoundHeaderHeight - options.CompoundPadding - ((height - desiredHeight) / 2d);
|
||||
|
||||
compoundNodes[nodeId] = ElkLayoutHelpers.CreatePositionedNode(
|
||||
nodesById[nodeId],
|
||||
x,
|
||||
y,
|
||||
options.Direction) with
|
||||
{
|
||||
Width = width,
|
||||
Height = height,
|
||||
};
|
||||
}
|
||||
|
||||
return compoundNodes;
|
||||
}
|
||||
|
||||
private static bool TryResolveNegativeCoordinateShift(
|
||||
IReadOnlyDictionary<string, ElkPositionedNode> positionedNodes,
|
||||
out double shiftX,
|
||||
out double shiftY)
|
||||
{
|
||||
shiftX = 0d;
|
||||
shiftY = 0d;
|
||||
if (positionedNodes.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var minX = positionedNodes.Values.Min(node => node.X);
|
||||
var minY = positionedNodes.Values.Min(node => node.Y);
|
||||
if (minX >= -0.01d && minY >= -0.01d)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
shiftX = minX < 0d ? -minX : 0d;
|
||||
shiftY = minY < 0d ? -minY : 0d;
|
||||
return shiftX > 0d || shiftY > 0d;
|
||||
}
|
||||
|
||||
private static Dictionary<string, ElkPositionedNode> ShiftNodes(
|
||||
IReadOnlyCollection<ElkNode> sourceNodes,
|
||||
IReadOnlyDictionary<string, ElkPositionedNode> positionedNodes,
|
||||
double shiftX,
|
||||
double shiftY,
|
||||
ElkLayoutDirection direction)
|
||||
{
|
||||
var sourceNodesById = sourceNodes.ToDictionary(node => node.Id, StringComparer.Ordinal);
|
||||
return positionedNodes.ToDictionary(
|
||||
pair => pair.Key,
|
||||
pair =>
|
||||
{
|
||||
var shifted = ElkLayoutHelpers.CreatePositionedNode(
|
||||
sourceNodesById[pair.Key],
|
||||
pair.Value.X + shiftX,
|
||||
pair.Value.Y + shiftY,
|
||||
direction);
|
||||
return shifted with
|
||||
{
|
||||
Width = pair.Value.Width,
|
||||
Height = pair.Value.Height,
|
||||
};
|
||||
},
|
||||
StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
private static ElkRoutedEdge[] ShiftEdges(
|
||||
IReadOnlyCollection<ElkRoutedEdge> routedEdges,
|
||||
double shiftX,
|
||||
double shiftY)
|
||||
{
|
||||
return routedEdges
|
||||
.Select(edge => new ElkRoutedEdge
|
||||
{
|
||||
Id = edge.Id,
|
||||
SourceNodeId = edge.SourceNodeId,
|
||||
TargetNodeId = edge.TargetNodeId,
|
||||
SourcePortId = edge.SourcePortId,
|
||||
TargetPortId = edge.TargetPortId,
|
||||
Kind = edge.Kind,
|
||||
Label = edge.Label,
|
||||
Sections = edge.Sections.Select(section => new ElkEdgeSection
|
||||
{
|
||||
StartPoint = new ElkPoint { X = section.StartPoint.X + shiftX, Y = section.StartPoint.Y + shiftY },
|
||||
EndPoint = new ElkPoint { X = section.EndPoint.X + shiftX, Y = section.EndPoint.Y + shiftY },
|
||||
BendPoints = section.BendPoints
|
||||
.Select(point => new ElkPoint { X = point.X + shiftX, Y = point.Y + shiftY })
|
||||
.ToArray(),
|
||||
}).ToArray(),
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private readonly record struct HierarchyOrderBlock(
|
||||
IReadOnlyList<string> NodeIds,
|
||||
double Rank,
|
||||
int MinCurrentPosition,
|
||||
int MinInputOrder);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user