ScopeBox to Sections

# -*- coding: utf-8 -*-
__title__ = 'ScopeBox to Sections'
from Autodesk.Revit.DB import *
from Autodesk.Revit.UI.Selection import *
from pyrevit import forms

doc   = __revit__.ActiveUIDocument.Document #type: Document
uidoc = __revit__.ActiveUIDocument
app   = __revit__.Application




# Define a selection filter class for Scope Boxes
class ScopeBoxSelectionFilter(ISelectionFilter):
    def AllowElement(self, element):
        if element.Category.Id == ElementId(BuiltInCategory.OST_VolumeOfInterest):
            return True

# Pick ScopeBoxes
ref_scope_boxes = uidoc.Selection.PickObjects(ObjectType.Element, ScopeBoxSelectionFilter())
scope_boxes     = [doc.GetElement(ref) for ref in ref_scope_boxes]

#Ensure ScopeBox selected
if not scope_boxes:
    forms.alert('No Box selected. Please Try Again',exitscript=True)


# Transaction 🔓
t = Transaction(doc, 'BB to Sections')
t.Start()


# Iterate through scope boxes
for sbox in scope_boxes:
    BB = sbox.get_BoundingBox(None)

    BB_height = BB.Max.Z - BB.Min.Z

    # Calculate Bottom Points
    pt_1 = XYZ(BB.Min.X, BB.Min.Y, BB.Min.Z)
    pt_2 = XYZ(BB.Max.X, BB.Min.Y, BB.Min.Z)
    pt_3 = XYZ(BB.Max.X, BB.Max.Y, BB.Min.Z)
    pt_4 = XYZ(BB.Min.X, BB.Max.Y, BB.Min.Z)

    # Create Lines
    line_1 = Line.CreateBound(pt_1, pt_2)
    line_2 = Line.CreateBound(pt_2, pt_3)
    line_3 = Line.CreateBound(pt_3, pt_4)
    line_4 = Line.CreateBound(pt_4, pt_1)
    lines = [line_1, line_2, line_3, line_4]

    # Create Sections from Lines
    for line in lines:

        #1️⃣ Calculate Origin + Vector
        pt_start  = line.GetEndPoint(0)   #type: XYZ
        pt_end    = line.GetEndPoint(1)   #type: XYZ
        pt_mid    = (pt_start + pt_end)/2 #type: XYZ
        vector    = pt_end - pt_start     #type: XYZ

        #2️⃣ Create Transform
        trans        = Transform.Identity
        trans.Origin = pt_mid

        vector = vector.Normalize() * -1 # Reverse Vector by *-1

        trans.BasisX = vector
        trans.BasisY = XYZ.BasisZ
        trans.BasisZ = vector.CrossProduct(XYZ.BasisZ)
        #The cross product is defined as the vector which is perpendicular to both vectors

        #3️⃣ Create SectionBox
        section_box = BoundingBoxXYZ() # origin 0,0,0
        offset = 1 #in Feet!


        half            = line.Length/2
        section_box.Min = XYZ(-half - offset ,  0          - offset , 0)
        section_box.Max = XYZ(half + offset  ,  BB_height + offset , line.Length)
        #💡               XYZ(X - Left/Right , Y - Up/Down          , Z - Forward/Backwards)

        section_box.Transform = trans # Apply Transform (Origin + XYZ Vectors)

        #6️⃣ Create Section View
        section_type_id  = doc.GetDefaultElementTypeId(ElementTypeGroup.ViewTypeSection)
        new_section      = ViewSection.CreateSection(doc, section_type_id, section_box)

t.Commit() #🔒

⌨️ Happy Coding!
Erik Frits