Beispiel #1
0
    def create_widnow_for_panel(self, panel_dict, panel_params, panel=None):
        """
        Создать окна в панели.
        """
        for i in panel_dict['components']['componentRefs']:
            window_type = self.all_windows[i["id"]]
            symb = self.window_family[window_type[0]]
            add_point = XYZ(i['point']['x'], i['point']['y'], i['point']['z']) / 304.8
            c_window = self.doc.Create.NewFamilyInstance(
                add_point,
                symb,
                self.default_level,
                StructuralType.Column)
            c_window = Precast_window(c_window, doc=self.doc, panel=panel)
            c_window["Рзм.Ширина"] = i["length"] / 304.8
            new_point = c_window.element.Location.Point
            new_point = new_point + XYZ(i["length"] / 304.8 / 2, 0, 0)
            # new_point = new_point + XYZ(i["length"] / 304.8 / 2, 0, 0)
            c_window.element.Location.Point = new_point
            axis = Line.CreateBound(c_window.element.Location.Point, c_window.element.Location.Point + XYZ(0,0,10))
            c_window.element.Location.Rotate(axis, math.pi)
            if window_type[1] == "left":
                plane = Plane.CreateByNormalAndOrigin(XYZ(1,0,0), c_window.element.Location.Point)
                new_win = ElementTransformUtils.MirrorElement(self.doc, c_window.element.Id, plane)

                self.doc.Delete(c_window.element.Id)
Beispiel #2
0
 def around_axis(self):
     """Method used to rotate elements around selected axis"""
     with rpw.db.Transaction("Rotate around axis", doc):
         axis = axis_selection()
         ElementTransformUtils.RotateElements(doc, self.selection, axis,
                                              self.angles)
     uidoc.Selection.SetElementIds(rotate_elements.selection)
Beispiel #3
0
def copy_paste_elements_btwn_views(src_view, dest_view):
    elements_to_copy = get_copyable_elements(src_view)
    if len(elements_to_copy) >= 1:
        # copying and pasting elements
        trans_name = 'Copy and Paste elements'
        try:
            with Transaction(doc, trans_name) as t:
                t.Start()

                failure_ops = t.GetFailureHandlingOptions()
                failure_ops.SetFailuresPreprocessor(ViewConverterFailurePreProcessor(trans_name, src_view.ViewName))
                # failure_ops.SetForcedModalHandling(False)
                t.SetFailureHandlingOptions(failure_ops)

                options = CopyPasteOptions()
                options.SetDuplicateTypeNamesHandler(CopyUseDestination())
                copied_element = ElementTransformUtils.CopyElements(src_view,
                                                                    List[ElementId](elements_to_copy),
                                                                    dest_view,
                                                                    None,
                                                                    options)

                # matching element graphics overrides and view properties
                if len(copied_element) != len(elements_to_copy):
                    logger.error('Some elements were not copied from view: {}'.format(src_view.ViewName))
                for dest, src in zip(copied_element, elements_to_copy):
                    dest_view.SetElementOverrides(dest, src_view.GetElementOverrides(src))

                t.Commit()
                return len(copied_element)
        except Exception as err:
            logger.error('Error occured while copying elements from {} | {}'.format(src_view.ViewName, err))
            return 0
    else:
        print('No copyable elements where found.')
Beispiel #4
0
def match_elevation(e1,e2):
    """Match Elevation of Elements"""
    element1location = e1.Location.Curve.GetEndPoint(1)
    element2location = e2.Location.Curve.GetEndPoint(1)
    vector_z = element1location[2] - element2location[2] 
    vector = XYZ(0,0,vector_z) 
    return ElementTransformUtils.MoveElement(doc, e2.Id, vector)
Beispiel #5
0
def create_dimension(element, point1, point2, reference_names_list, view, direction_to_move=XYZ(0, 0, 0)):
    line = Line.CreateBound(point1, point2)
    refArray = ReferenceArray()
    for ref in reference_names_list:
        refArray.Append(element.GetReferenceByName(ref))
    dim = doc.Create.NewDimension(view, line, refArray)
    ElementTransformUtils.MoveElement(doc, dim.Id, direction_to_move)
    return dim
Beispiel #6
0
def move_element_schedule(scheduleview_port, view, value_x, value_y):
    bb_vp = scheduleview_port.get_BoundingBox(view)
    if bb_vp:
        x = UnitUtils.ConvertToInternalUnits(value_x, DisplayUnitType.DUT_MILLIMETERS)
        y = UnitUtils.ConvertToInternalUnits(value_y, DisplayUnitType.DUT_MILLIMETERS)
        new_x = x - bb_vp.Max.X - bb_vp.Min.X
        pt3 = XYZ(new_x, y, 0)
        point = ElementTransformUtils.MoveElement(doc, scheduleview_port.Id, pt3)
        return point
Beispiel #7
0
 def copy_els_form_source(cls, doc, source, els):
     """Копирует значения из dict источника в документ."""
     els = List[ElementId](els.values())
     new_filters = {}
     for i in ElementTransformUtils.CopyElements(source, els, doc,
                                                 Transform.Identity,
                                                 CopyPasteOptions()):
         new_filters.update({doc.GetElement(i).Name: i})
     return new_filters
Beispiel #8
0
 def around_itself(self):
     """Method used to rotate elements on themselves"""
     with rpw.db.Transaction("Rotate around itself", doc):
         for elid in self.selection:
             el_axis = xyz_axis(elid)
             for i in range(3):
                 if self.angles[i] == 0:
                     pass
                 else:
                     ElementTransformUtils.RotateElement(
                         doc, elid, el_axis[i], self.angles[i])
Beispiel #9
0
def rotate_element(elem, degrees_to_rotate):
    #>>>>>>>>>> GET CENTER POINT
    bounding_box = elem.get_BoundingBox(doc.ActiveView)
    point = (bounding_box.Min + bounding_box.Max) / 2

    #>>>>>>>>>> AXIS LINE
    axis_line = Line.CreateBound(
        point, point + XYZ.BasisZ)  #fixme will not rotate 2D in secitons

    #>>>>>>>>>> ROTATE
    ElementTransformUtils.RotateElement(doc, elem.Id, axis_line,
                                        math.radians(degrees_to_rotate))
Beispiel #10
0
def copy(source_doc, elem):
    """
    Copy elem from source_doc to active document
    :param source_doc: Autodesk.Revit.DB.Document
    :param elem: Autodesk.Revit.DB.Element
    :return: None
    """
    copypasteoptions = CopyPasteOptions()
    id_list = List[ElementId]()
    id_list.Add(elem.Id)

    with rpw.db.Transaction("Copy pipe type", doc):
        ElementTransformUtils.CopyElements(source_doc, id_list, doc,
                                           Transform.Identity,
                                           copypasteoptions)
Beispiel #11
0
if source_template_id:
    with Transaction(active_doc, 'Обновить шаблон') as t:
        t.Start()
        source_template = source_doc.GetElement(source_template_id)
        echo("Найден соответствующий шаблон " + source_template.Title)
        cur_time = '_old_' + datetime.now().strftime("%y%m%d%H%M%S")

        source_template_filter_names = { source_doc.GetElement(i).Name: i for i in source_doc.GetElement(source_template_id).GetFilters()}
        for i in FilteredElementCollector(active_doc).OfClass(ParameterFilterElement).ToElements():
            if i.Name in source_template_filter_names.keys():
                i.Name += cur_time
        template_name.Set(template_name.AsString() + cur_time)

        new_template = List[ElementId]([source_template_id])
        new_template = ElementTransformUtils.CopyElements(source_doc, new_template, active_doc, Transform.Identity, CopyPasteOptions())
        for i in new_template:
            new_template_name = active_doc.GetElement(i).get_Parameter(BuiltInParameter.VIEW_NAME)
            new_template_name_str = file_with_template.rename_template(new_template_name.AsString())
            new_template_name.Set(new_template_name_str)
            echo("Скопирован шаблон " + new_template_name_str)
            for k in view_with_templates:
                k.ViewTemplateId = i
            break
        t.Commit()
else:
    echo("Соответствующий шаблон не найден. Необходимо задать сопоставления в " + comparison_paths)
# with Transaction(active_doc, 'Обновить шаблон') as t:
#     t.Start()
#     if active_view:
#
Beispiel #12
0
def run(sel, location_option):
    logger.info("Location option: %s " % location_option)
    docs = __revit__.Application.Documents
    # where to copy
    src_doc = __revit__.ActiveUIDocument.Document
    docs = filter(lambda d: not d.IsLinked and d != src_doc, docs)
    trg_docs = forms.SelectFromList.show(docs,
                                         name_attr='Title',
                                         title='Documents to paste selection',
                                         button_name='Paste',
                                         multiselect=True)
    null_point_src = None
    null_point_cat = None
    if location_option == "Project Base Point":
        null_point_cat = BuiltInCategory.OST_SharedBasePoint
    elif location_option == "Shared Site Point":
        null_point_cat = BuiltInCategory.OST_ProjectBasePoint

    if null_point_cat:
        null_point_src = FilteredElementCollector(
            src_doc).WhereElementIsNotElementType().OfCategory(
                null_point_cat).WhereElementIsNotElementType().ToElements()
        if len(null_point_src) == 0:
            logger.warning(
                "Point for location option wasn't found in source document. Default alignment will be used"
            )

    for trg_doc in trg_docs:
        logger.debug(trg_doc)
        logger.debug(len(trg_doc.Title))
        s = "Copy %d elements from %s to %s" % (len(sel), src_doc.Title,
                                                trg_doc.Title)
        print(s)
        # logger.info(s) # TODO Fix - cannot log cyrylic project name

        # Transform
        transform_vector = None
        if null_point_src:
            null_point_trg = FilteredElementCollector(
                trg_doc).WhereElementIsNotElementType().OfCategory(
                    null_point_cat).WhereElementIsNotElementType().ToElements(
                    )
            if len(null_point_trg) == 0:
                logger.warning(
                    "Point for location option wasn't found in target document. Document will be skipped"
                )
                continue
            # _transform_vector = null_point_trg[0].GetTransform().BasisX - null_point_src[0].GetTransform().BasisX
            print(null_point_trg[0].BoundingBox[null_point_trg[0]])
            transform_vector = Transform.CreateTranslation(
                null_point_trg[0].BoundingBox.Min -
                null_point_src[0].BoundingBox.Min)

        t = Transaction(
            trg_doc,
            __title__ + " - %d elements from %s" % (len(sel), src_doc.Title))
        t.Start()
        try:
            ElementTransformUtils.CopyElements(src_doc, List[ElementId](sel),
                                               trg_doc, transform_vector, None)
            t.Commit()
        except Exception as exc:
            t.RollBack()
            logger.error(exc)
Beispiel #13
0
t.Start()

# Check for all views that has a view template
vTIds = []
viewsWVT = checkViewT(docViewsCollector)
viewsFail = []
viewsSuccess = []
for vT in vTemplates:
    vTId = List[ElementId]()
    for pro in selProject:
        if pro.Title in vT:
            vTId.Add(viewTemplates[vT].Id)
            # Check if view template is used in current doc
            if vT.replace(" - " + pro.Title, "") not in docTemplates.keys():
                # If not, copy the selected View Template to current project
                ElementTransformUtils.CopyElements(pro, vTId, doc, transIdent,
                                                   copyPasteOpt)
            # View templates are already in use in the current project
            else:
                vToApplyVT = []
                # Loop through each view template in use in the current document
                for k in viewsWVT.keys():
                    views = viewsWVT[k]
                    # Helper variable to mark the first time to run the script
                    flag = True
                    # Assign new view template to each view
                    for v in views:
                        # Retrieve view template for first time use
                        if flag:
                            elName = doc.GetElement(v.ViewTemplateId).Name
                            if elName in vT:
                                doc.Delete(v.ViewTemplateId)
Beispiel #14
0
 def copy_templates(self, doc, source, templates):
     els = List[ElementId](templates.values())
     ElementTransformUtils.CopyElements(source, els, doc,
                                        Transform.Identity,
                                        CopyPasteOptions())
Beispiel #15
0
from pyrevit import revit, DB

__context__ = 'selection'
__doc__ = 'Randomly rotates selected elements.'

# reference the current open revit model to work with:
doc = __revit__.ActiveUIDocument.Document

# get selected element
selection = revit.get_selection()
elements = selection.elements

degrees_to_rotate = 45.0
# Convert the user input from degrees to radians.
converted_value = float(degrees_to_rotate) * (math.pi / 180.0)

# entering a transaction to modify the revit model database
# start transaction
tx = Transaction(doc, "check type against parameter value")
tx.Start()

for element in elements:
    origin = element.Location.Point
    line_z = Line.CreateBound(origin, XYZ(origin.X, origin.Y, origin.Z + 1))
    ElementTransformUtils.RotateElement(doc, element.Id, line_z,
                                        random.uniform(0, (math.pi * 2)))

# commit the changes to the revit model database
# end transaction
tx.Commit()
Beispiel #16
0
 def copy_by_normal_length(self, vect):
     """Копировать арматуру по вектору"""
     return self.__class__(doc.GetElement(ElementTransformUtils.CopyElement(doc, self.rebar.Id, vect)[0]))
Beispiel #17
0
            draftingType = v
            break
    draftingView = ViewDrafting.Create(doc, draftingType.Id)
    # draftingView.Name = name + draftingView.Name
    return draftingView


FindSheetFromDoc(doc, "View \"Sheet: A102 - Site Plan")
sheets = SheetWorksetCollector(doc)

# Location and Copy Paste Options
trans = None
op = CopyPasteOptions()

# Copy Loop
for sheet in sheets:
    elements = SheetElementCheck(doc, sheet, targetCate)
    # Check if there are elements to copy
    if elements:
        sheetName = sheet.Name
        print(sheetName)
        origin = FindSheetFromDoc(doc, sheetName)
        print(origin, View)
        originSheetName = origin.LookupParameter('Sheet Name').AsString()
        t = Transaction(doc, 'Copy ' + sheetName + ' to drafting')
        t.Start()
        dView = CreateDrafting(doc)
        dView.Name = originSheetName + ' ' + dView.Name
        ElementTransformUtils.CopyElements(origin, elements, dView, trans, op)
        t.Commit()
Beispiel #18
0
        if isinstance(el, Element) and el.Category:
            elements_to_copy.append(el.Id)
        else:
            logger.debug('Skipping Element with id: {0}'.format(el.Id))
    if len(elements_to_copy) < 1:
        logger.debug('Skipping {0}. No copyable elements where found.'.format(
            src_view.ViewName))
        continue

    # start creating views and copying elements
    with Transaction(doc, 'Duplicate Drafting as Legend') as t:
        t.Start()

        # copying and pasting elements
        dest_view = doc.GetElement(
            baseLegendView.Duplicate(ViewDuplicateOption.Duplicate))
        options = CopyPasteOptions()
        options.SetDuplicateTypeNamesHandler(CopyUseDestination())
        copied_element = ElementTransformUtils.CopyElements(
            src_view, List[ElementId](elements_to_copy), dest_view, None,
            options)

        # matching element graphics overrides and view properties
        for dest, src in zip(copied_element, elements_to_copy):
            dest_view.SetElementOverrides(dest,
                                          src_view.GetElementOverrides(src))
        dest_view.ViewName = src_view.ViewName
        dest_view.Scale = src_view.Scale

        t.Commit()
Beispiel #19
0
try:
    source_doc = form.values["source"]
    target_doc = form.values["target"]
except KeyError:
    logger.debug('No input or incorrect inputs')
    import sys
    sys.exit()

copypasteoptions = CopyPasteOptions()

source_viewtype_id_list = get_all_viewfamilytype_ids(source_doc)

source_doc_dict = view_type_name_template_name_dict(source_doc)

with rpw.db.Transaction(doc=target_doc, name="Copy view types"):
    # Copy view type
    ElementTransformUtils.CopyElements(source_doc, source_viewtype_id_list,
                                       target_doc, Transform.Identity,
                                       copypasteoptions)

    # Assign Default Template to ViewType
    target_doc_dict = view_template_name_to_id_dict(target_doc)
    for viewtype in FilteredElementCollector(target_doc).OfClass(
            ViewFamilyType):
        try:
            default_template_name = source_doc_dict[name(viewtype)]
            default_template_id = target_doc_dict[default_template_name]
            viewtype.DefaultTemplateId = default_template_id
        except KeyError:
            logger.debug("{} has no view template".format(name(viewtype)))
Beispiel #20
0
        # destination = FilteredElementCollector(doc, desview.Id).OfClass(ImportInstance).ToElementIds()
        elementspool = FilteredElementCollector(
            recoverdoc, recoverview.Id).OfClass(ImportInstance).ToElements()
        elements = FilteredElementCollector(
            recoverdoc, recoverview.Id).OfClass(ImportInstance).ToElementIds()
        # print(len(elements))
        count = 0
        for ele in elementspool:
            a = ele.IsLinked
            if a:
                elements.Remove(ele.Id)
            else:
                count += 1
        if desview:
            print("found " + str(len(elements)) + " elements")
            if elements:
                trans = None
                op = CopyPasteOptions()
                ElementTransformUtils.CopyElements(recoverview, elements,
                                                   desview, trans, op)
                print("copied " + i.ToString())
            else:
                print("failed State no Elements" + i.ToString())
        else:
            print("failed State view not valid" + i.ToString())
    except:
        print("failed State final script fail " + i.ToString())

# recoverdoc.Close(False)
t.Commit()
Beispiel #21
0
# Scenario 4
                elif (not CloseNumber(proj_start.X, line_start.X) \
                     or not CloseNumber(proj_start.Y, line_start.Y)) \
                     and (not CloseNumber(proj_end.X, line_end.X) \
                     or not CloseNumber(proj_end.Y, line_end.Y)):
                    print('4')
                    t = Transaction(doc, 'Correct Lines 4')
                    t.Start()
                    try:
                        newLine1 = Line.CreateBound(proj_start, line_start)
                        line.SetGeometryCurve(newLine1, True)
                    except:
                        print('Fail 411')

                    newLine2 = Line.CreateBound(proj_end, line_end)
                    line2 = ElementTransformUtils.CopyElement(
                        doc, line.Id, XYZ(0.1, 0.1, 0.1))
                    doc.GetElement(line2[0]).SetGeometryCurve(newLine2, True)
                    print('Correction Successful')
                    '''
                    except:
                        print('Fail 412')
                        # print("Wall" + format(outprint.linkify(wall.Id)))
                        # print("Line" + format(outprint.linkify(line.Id)))
                    '''
                    t.Commit()
                else:
                    print('Error 5')
                print("---------------")
            except:
                print('Error 6')
# t.Commit()
Beispiel #22
0
                                   AssemblyDetailViewOrientation.ElevationBack,
                                   assembly_sheet,
                                   pt_right_view,
                                   'ARH_БезЗаголовка',
                                   'ARH_Section')

# Создание вида сверху
pt_top_view = XYZ(0.491049476255798, 0.243470403613338, 0)
top_view = create_detail_section(assembly,
                                 AssemblyDetailViewOrientation.ElevationTop,
                                 assembly_sheet,
                                 pt_top_view,
                                 'ARH_БезЗаголовка',
                                 'ARH_Section')
center = top_view[1].GetBoxCenter()
ElementTransformUtils.MoveElement(doc, top_view[1].Id, pt_top_view - center)
TransactionManager.Instance.ForceCloseTransaction()

TransactionManager.Instance.EnsureInTransaction(doc)
assembly.AssemblyTypeName = elem_name
# Размеры-------------------------------------------------------------------------------------
create_dimension_on_view(elem, 'horizontal', right_view[0])
create_dimension_on_view(elem, 'vertical', right_view[0])
create_dimension_on_view(elem, 'horizontal', right_view[0])
create_dimension_on_view(elem, 'vertical', right_view[0])
create_dimension_on_view(elem, 'horizontal', section_view[0])
create_dimension_on_view(elem, 'vertical', section_view[0])
create_dimension_on_view(elem, 'horizontal', top_view[0])
create_dimension_on_view(elem, 'vertical', top_view[0])
TransactionManager.Instance.TransactionTaskDone()
TransactionManager.Instance.ForceCloseTransaction()