Search code examples
geometryrevit-apirevit

Revit API. How can I get bounding box for several elements?


I need to find an outline for many elements (>100'000 items). Target elements come from a FilteredElementCollector. As usual I'm looking for the fastest possible way.

For now I tried to iterate over all elements to get its BoudingBox.Min and BoudingBox.Max and find out minX, minY, minZ, maxX, maxY, maxZ. It works pretty accurate but takes too much time.


The problem is described above is a part of a bigger one. I need to find all the intersections of ducts, pipes and other curve-based elements from a link model with walls, ceilings, columns, etc. in the general model and then place openings in a intersection.

I tried to use a combination of ElementIntersectElement filter and IntersectSolidAndCurve method to find a part of curve inside element.

First with an ElementIntersectElement I tried to reduce a collection for further use of IntersectSolidAndCurve .IntersectSolidAndCurve takes two argument: solid and curve and have to work in two nested one in the other loops. So, it takes for 54000 walls (after filtering) and 18000 pipes in my case 972'000'000 operation.

With the number of operations 10 ^ 5, the algorithm shows an acceptable time. I decided to reduce the number of elements by dividing the search areas by levels. This works well for high-rise buildings, but still bad for extended low structures. I decided to divide the building by length, but I did not find a method that finds boundaries for several elements (the whole building).

I seem to go in a wrong way. Is there are right way to make it with revit api instrument


Solution

  • To find boundaries we can take advantage of the binary search idea.

    The difference from the classic binary search algorithm is there is no an array, and we should find two number instead of a one.

    Elements in Geometry space could be presented as a 3-dimensional sorted array of XYZ points.

    Revit api provides excellent Quick Filter: BoundingBoxIntersectsFilter that takes an instance of an Outline

    So, let’s define an area that includes all the elements for which we want to find the boundaries. For my case, for example 500 meters, and create min and max point for the initial outline

        double b = 500000 / 304.8;
        XYZ min = new XYZ(-b, -b, -b);
        XYZ max = new XYZ(b, b, b);
    

    Below is an implementation for one direction, however, you can easily use it for three directions by calling and feeding the result of the previous iteration to the input

         double precision = 10e-6 / 304.8;
         var bb = new BinaryUpperLowerBoundsSearch(doc, precision);
    
         XYZ[] rx = bb.GetBoundaries(min, max, elems, BinaryUpperLowerBoundsSearch.Direction.X);
         rx = bb.GetBoundaries(rx[0], rx[1], elems, BinaryUpperLowerBoundsSearch.Direction.Y);
         rx = bb.GetBoundaries(rx[0], rx[1], elems, BinaryUpperLowerBoundsSearch.Direction.Z);
    

    The GetBoundaries method returns two XYZ points: lower and upper, which change only in the target direction, the other two dimensions remain unchanged

        public class BinaryUpperLowerBoundsSearch
        {
            private Document doc;
    
            private double tolerance;
            private XYZ min;
            private XYZ max;
            private XYZ direction;
    
            public BinaryUpperLowerBoundsSearch(Document document, double precision)
            {
                doc = document;
                this.tolerance = precision;
            }
    
            public enum Direction
            {
                X,
                Y,
                Z
            }
    
            /// <summary>
            /// Searches for an area that completely includes all elements within a given precision.
            /// The minimum and maximum points are used for the initial assessment. 
            /// The outline must contain all elements.
            /// </summary>
            /// <param name="minPoint">The minimum point of the BoundBox used for the first approximation.</param>
            /// <param name="maxPoint">The maximum point of the BoundBox used for the first approximation.</param>
            /// <param name="elements">Set of elements</param>
            /// <param name="axe">The direction along which the boundaries will be searched</param>
            /// <returns>Returns two points: first is the lower bound, second is the upper bound</returns>
            public XYZ[] GetBoundaries(XYZ minPoint, XYZ maxPoint, ICollection<ElementId> elements, Direction axe)
            {
                // Since Outline is not derived from an Element class there 
                // is no possibility to apply transformation, so
                // we have use as a possible directions only three vectors of basis 
                switch (axe)
                {
                    case Direction.X:
                        direction = XYZ.BasisX;
                        break;
                    case Direction.Y:
                        direction = XYZ.BasisY;
                        break;
                    case Direction.Z:
                        direction = XYZ.BasisZ;
                        break;
                    default:
                        break;
                }
    
                // Get the lower and upper bounds as a projection on a direction vector
                // Projection is an extention method
                double lowerBound = minPoint.Projection(direction);
                double upperBound = maxPoint.Projection(direction);
    
                // Set the boundary points in the plane perpendicular to the direction vector. 
                // These points are needed to create BoundingBoxIntersectsFilter when IsContainsElements calls.
                min = minPoint - lowerBound * direction;
                max = maxPoint - upperBound * direction;
    
    
                double[] res = UpperLower(lowerBound, upperBound, elements);
                return new XYZ[2]
                {
                    res[0] * direction + min,
                    res[1] * direction + max,
                };
            }
    
            /// <summary>
            /// Check if there are any elements contains in the segment [lower, upper]
            /// </summary>
            /// <returns>True if any elements are in the segment</returns>
            private ICollection<ElementId> IsContainsElements(double lower, double upper, ICollection<ElementId> ids)
            {
                var outline = new Outline(min + direction * lower, max + direction * upper);
                return new FilteredElementCollector(doc, ids)
                    .WhereElementIsNotElementType()
                    .WherePasses(new BoundingBoxIntersectsFilter(outline))
                    .ToElementIds();
            }
    
    
            private double[] UpperLower(double lower, double upper, ICollection<ElementId> ids)
            {
                // Get the Midpoint for segment mid = lower + 0.5 * (upper - lower)
                var mid = Midpoint(lower, upper);
    
                // Сheck if the first segment contains elements 
                ICollection<ElementId> idsFirst = IsContainsElements(lower, mid, ids);
                bool first = idsFirst.Any();
    
                // Сheck if the second segment contains elements 
                ICollection<ElementId> idsSecond = IsContainsElements(mid, upper, ids);
                bool second = idsSecond.Any();
    
                // If elements are in both segments 
                // then the first segment contains the lower border 
                // and the second contains the upper
                // ---------**|***--------
                if (first && second)
                {
                    return new double[2]
                    {
                        Lower(lower, mid, idsFirst),
                        Upper(mid, upper, idsSecond),
                    };
                }
    
                // If elements are only in the first segment it contains both borders. 
                // We recursively call the method UpperLower until 
                // the lower border turn out in the first segment and 
                // the upper border is in the second
                // ---*****---|-----------
                else if (first && !second)
                    return UpperLower(lower, mid, idsFirst);
    
                // Do the same with the second segment
                // -----------|---*****---
                else if (!first && second)
                    return UpperLower(mid, upper, idsSecond);
    
                // Elements are out of the segment
                // ** -----------|----------- **
                else
                    throw new ArgumentException("Segment is not contains elements. Try to make initial boundaries wider", "lower, upper");
            }
    
            /// <summary>
            /// Search the lower boundary of a segment containing elements
            /// </summary>
            /// <returns>Lower boundary</returns>
            private double Lower(double lower, double upper, ICollection<ElementId> ids)
            {
                // If the boundaries are within tolerance return lower bound
                if (IsInTolerance(lower, upper))
                    return lower;
    
                // Get the Midpoint for segment mid = lower + 0.5 * (upper - lower)
                var mid = Midpoint(lower, upper);
    
                // Сheck if the segment contains elements 
                ICollection<ElementId> idsFirst = IsContainsElements(lower, mid, ids);
                bool first = idsFirst.Any();
    
                // ---*****---|-----------
                if (first)
                    return Lower(lower, mid, idsFirst);
                // -----------|-----***---
                else
                    return Lower(mid, upper, ids);
    
            }
    
            /// <summary>
            /// Search the upper boundary of a segment containing elements
            /// </summary>
            /// <returns>Upper boundary</returns>
            private double Upper(double lower, double upper, ICollection<ElementId> ids)
            {
                // If the boundaries are within tolerance return upper bound
                if (IsInTolerance(lower, upper))
                    return upper;
    
                // Get the Midpoint for segment mid = lower + 0.5 * (upper - lower)
                var mid = Midpoint(lower, upper);
    
                // Сheck if the segment contains elements 
                ICollection<ElementId> idsSecond = IsContainsElements(mid, upper, ids);
                bool second = idsSecond.Any();
    
                // -----------|----*****--
                if (second)
                    return Upper(mid, upper, idsSecond);
                // ---*****---|-----------
                else
                    return Upper(lower, mid, ids);
            }
    
            private double Midpoint(double lower, double upper) => lower + 0.5 * (upper - lower);
            private bool IsInTolerance(double lower, double upper) => upper - lower <= tolerance;
    
        }
    

    Projection is an extention method for vector to determine the length of projection one vector for another

        public static class PointExt
        {
            public static double Projection(this XYZ vector, XYZ other) =>
                vector.DotProduct(other) / other.GetLength();
        }