Skip to content

Uniform coordinate space

Michael Wieland edited this page Apr 18, 2018 · 1 revision

Find common anchestor and transform point coordinates to its coordinate space.

// transform to uniform coordinate space
Node parent = findFirstCommonAncestor(startNode, endNode);
Point2D transformedStartPoint = localToAncestor(point, startNode, parent);
Point2D transformedEndPoint = localToAncestor(point, endNode, parent);

private Point2D localToAncestor(Point2D point, Node local, Node ancestor) {
    if (local == ancestor) {
        return point;
    }

    Point2D transformedPoint = local.localToParent(point);
    return localToAncestor(transformedPoint, local.getParent(), ancestor);
}

private Node findFirstCommonAncestor(Node node1, Node node2) {
    if (node1 == null || node2 == null) {
        return null;
    }
    if (isDescendant(node1, node2)) {
        return node2;
    }
    return findFirstCommonAncestor(node1, node2.getParent());
}

private boolean isDescendant(Node candidate, Node node) {
    if (candidate == null) {
        return false;
    } else if (candidate == node) {
        return true;
    }
    return isDescendant(candidate.getParent(), node);
}
Clone this wiki locally