def get_title_block_placement(viewport): """Search for a TitleBlock on a viewport sheet. Returns TitleBlock location on sheet if there is exactly one. Args: viewport (DB.Viewport): viewport to get sheet from Returns: DB.XYZ: TitleBlock location or DB.XYZ.Zero """ sheet = viewport.Document.GetElement(viewport.SheetId) cl = DB.FilteredElementCollector(sheet.Document, sheet.Id). \ WhereElementIsNotElementType(). \ OfCategory(DB.BuiltInCategory.OST_TitleBlocks) title_blocks = cl.ToElements() if len(title_blocks) == 1: return title_blocks[0].Location.Point else: return DB.XYZ.Zero
def LoadFamily(familyPath, MatId): with revit.Transaction("LoadRevitFamily"): r = clr.Reference[DB.Family]() doc.LoadFamily(familyPath, r) familySymbolIds = r.GetFamilySymbolIds() for i in familySymbolIds: familySymbol = doc.GetElement(i) familySymbol.Activate() material = familySymbol.GetParameters("Material") #TODO only for one material print(material[0].Set(MatId)) break if isFraming: st = DB.Structure.StructuralType.Beam else: st = DB.Structure.StructuralType.NonStructural newFamily = doc.Create.NewFamilyInstance(DB.XYZ(), familySymbol, st)
def selectsheets2print(): all_sheets = DB.FilteredElementCollector(doc).OfClass(DB.ViewSheet) \ .WhereElementIsNotElementType().ToElements() all_sheets = [i for i in all_sheets if not i.IsPlaceholder] sortlist = sorted([SheetOption(x) for x in all_sheets], key=lambda x: x.number) selsheet = SelectFromCheckBoxes(sortlist, title="Select Sheets", width=500, height=400, button_name="Select / PRINT") selsheet.ShowDialog( ) #.Net Method, Modal Window, no other window is active write_dic(selsheet.dic_dlgval) if selsheet.response: return ([i.item for i in selsheet.response if i.state], selsheet.dic_dlgval) else: sys.exit() #selsheet.response does not exist
def copy_viewport_types(activedoc, vport_type, vport_typename, dest_doc, newvport): dest_vport_typenames = [DBElement.Name.GetValue(dest_doc.GetElement(x)) for x in newvport.GetValidTypes()] cp_options = DB.CopyPasteOptions() cp_options.SetDuplicateTypeNamesHandler(CopyUseDestination()) if vport_typename not in dest_vport_typenames: with revit.Transaction('Copy Viewport Types', doc=dest_doc, swallow_errors=True): DB.ElementTransformUtils.CopyElements( activedoc, List[DB.ElementId]([vport_type.Id]), dest_doc, None, cp_options, )
def remove_all_view_templates(): """Remove All View Templates""" def confirm_removal(v): if isinstance(v, DB.View) \ and v.IsTemplate \ and v.ViewType not in READONLY_VIEWS: return True else: return False cl = DB.FilteredElementCollector(revit.doc) views = set( cl.OfClass(DB.View).WhereElementIsNotElementType().ToElements()) print_header('REMOVING ALL VIEW TEMPLATES') remove_action('Remove All View Templates', 'View Templates', views, validity_func=confirm_removal)
def FindWallFace(self): normalFaces = List[DB.Face]() opt = DB.Options() opt.ComputeReferences = True opt.DetailLevel = DB.ViewDetailLevel.Fine e = self.Wall.get_Geometry(opt) print(e) for obj in e: solid = obj if solid != None and solid.Faces.Size > 0: for face in solid.Faces: pf = face if pf != None: normalFaces.Add(pf) return normalFaces
def get_view_contents(dest_doc, source_view): view_elements = DB.FilteredElementCollector(dest_doc, source_view.Id)\ .WhereElementIsNotElementType()\ .ToElements() elements_ids = [] for element in view_elements: if (element.Category and element.Category.Name == 'Title Blocks') \ and not OPTION_SET.op_copy_titleblock: continue elif isinstance(element, DB.ScheduleSheetInstance) \ and not OPTION_SET.op_copy_schedules: continue elif isinstance(element, DB.Viewport) \ or 'ExtentElem' in element.Name: continue else: elements_ids.append(element.Id) return elements_ids
def export_pattern(self, export_dir): patname = self.pat_name_cb.SelectedItem existing_pats = DB.FilteredElementCollector(revit.doc)\ .OfClass(DB.FillPatternElement)\ .ToElements() fillpats = [x.GetFillPattern() for x in existing_pats] target_type = \ DB.FillPatternTarget.Model \ if self.is_model_pat else DB.FillPatternTarget.Drafting searchpats = [x for x in fillpats if x.Target == target_type] for fillpat in searchpats: if fillpat.Name == patname: patmaker.export_pattern(export_dir, patname, [], ((0, 0), (1, 1)), fillgrids=fillpat.GetFillGrids(), scale=self.export_scale, model_pattern=self.is_model_pat) forms.alert('Pattern {} exported.'.format(patname))
def removeallemptyelevationmarkers(): with revit.Transaction('Remove All Elevation Markers'): print('REMOVING ELEVATION MARKERS...\n') elevmarkers = DB.FilteredElementCollector(revit.doc)\ .OfClass(DB.ElevationMarker)\ .WhereElementIsNotElementType()\ .ToElements() for em in elevmarkers: if em.CurrentViewCount == 0: emtype = revit.doc.GetElement(em.GetTypeId()) print('ID: {0}\tELEVATION TYPE: {1}'.format( em.Id, revit.query.get_name(emtype))) try: revit.doc.Delete(em.Id) except Exception as e: logger.error('Error removing marker: {} | {}'.format( em.Id, e)) continue
def FindSingleIntersection(_win, _host_win, _elements, _current_view, _location_pt, _direction): # line = DB.Line.CreateBound(_location_pt, _location_pt + 2 * _direction) # Keep for visual debugging # CreateLine(revit.doc, line, DB.XYZ(1, 0, 0)) # Keep for visual debugging (change plane dir) try: element_ids = CleanElementIds(_elements, _win, _host_win) # Get the clean list of Ids target = DB.FindReferenceTarget.All # Any intersection for the time being, can test more ref_int = DB.ReferenceIntersector(element_ids, target, _current_view) # The Intersector nearest_up = ref_int.FindNearest(_location_pt, _direction) # Find only the nearest shot = nearest_up.GetReference( ) # We got a shot! TO DO: Check if no intersection return shot except: pass
def get_symbol_id(symbol_name): # translate family-symbol formatted name and find the loaded symbol # current implementation matches the repr to how Revit shows the value # famil-name : symbol-name if FAMILY_SYMBOL_SEPARATOR not in symbol_name: logger.warning( 'Family type parameter value must be formatted as ' '<family-name> : <symbol-name> | incorrect format: %s', symbol_name) return fam_name, sym_name = symbol_name.split(FAMILY_SYMBOL_SEPARATOR) for fsym in DB.FilteredElementCollector(revit.doc)\ .OfClass(DB.FamilySymbol)\ .ToElements(): famname = revit.query.get_name(fsym.Family) symname = revit.query.get_name(fsym) if famname == fam_name and symname == sym_name: return fsym.Id
def allign_Z(tagType, starting_pt): """Main renumbering routine for elements of given category.""" # all actions under one transaction with revit.TransactionGroup("Allign tags horizontally"): # make sure target elements are easily selectable # with EasilySelectableElements(revit.active_view, BIC.OST_Tags): # ask user to pick a tag and allign them for picked_element in revit.get_picked_elements_by_category( revit.query.get_category(tagType), message="Select a tag to allign"): # need nested transactions to push revit to update view # on each allignment with revit.Transaction("Allign tag \'{}\' by Z".format( picked_element.Id)): # actual allignment cPosition = picked_element.TagHeadPosition picked_element.TagHeadPosition = DB.XYZ( cPosition.X, cPosition.Y, starting_pt.Z)
def remove_all_sheets(): """Remove All Sheets (except open sheets)""" cl = DB.FilteredElementCollector(revit.doc) sheets = cl.OfCategory(DB.BuiltInCategory.OST_Sheets)\ .WhereElementIsNotElementType()\ .ToElements() open_UIViews = revit.uidoc.GetOpenUIViews() open_views = [ov.ViewId.IntegerValue for ov in open_UIViews] def confirm_removal(sht): return isinstance(sht, DB.ViewSheet) \ and sht.Id.IntegerValue not in open_views print_header('REMOVING SHEETS') remove_action('Remove All Sheets', 'Sheet', sheets, validity_func=confirm_removal)
def get_sketch_elements(wall): # delete the element and roll back, while catching the IDs of deleted elements t1 = DB.Transaction(revit.doc, "del el") t1.Start() all_ids = revit.doc.Delete(wall.Id) t1.RollBack() profile = None curves = [] # pick only sketch elements for id in all_ids: el = revit.doc.GetElement(id) if isinstance(el, DB.Sketch): profile = el.Profile # formatting: iterate through sketch curve arrays and gather curves for curve_arr in profile: for curve in curve_arr: curves.append(curve) return List[DB.Curve](curves)
def get_worksetcleaners(): workset_funcs = [] # if model is workshared, get a list of current worksets if revit.doc.IsWorkshared: cl = DB.FilteredWorksetCollector(revit.doc) worksetlist = cl.OfKind(DB.WorksetKind.UserWorkset) # duplicate the workset element remover function for each workset for workset in worksetlist: # copying functions is not implemented in IronPython 2.7.3 # this method initially used copy_func to create a func for # each workset but now passes on the template func # with appropriate arguments docstr = WORKSET_FUNC_DOCSTRING_TEMPLATE.format(workset.Name) workset_funcs.append( WorksetFuncData(func=template_workset_remover, docstring=docstr, args=(workset.Name, ))) return workset_funcs
def bb_corners(box, transform): b_ll = box.Min #lower left b_lr = DB.XYZ(box.Max.X, box.Min.Y, box.Min.Z) # lower right b_ul = DB.XYZ(box.Min.X, box.Max.Y, box.Min.Z) # upper left b_ur = DB.XYZ(box.Max.X, box.Max.Y, box.Min.Z) # upper right t_ur = box.Max # upper right t_ul = DB.XYZ(box.Min.X, box.Max.Y, box.Max.Z) # upper left t_lr = DB.XYZ(box.Max.X, box.Min.Y, box.Max.Z) # lower right t_ll = DB.XYZ(box.Min.X, box.Min.Y, box.Max.Z) # lower left out = [b_ll, b_lr, b_ul, b_ur, t_ur, t_ul, t_lr, t_ll] for index, o in enumerate(out): out[index] = box.Transform.OfPoint(out[index]) out[index] = transform.Inverse.OfPoint(out[index]) return out
def listdwgs(current_view_only=False): dwgs = DB.FilteredElementCollector(revit.doc)\ .OfClass(DB.ImportInstance)\ .WhereElementIsNotElementType()\ .ToElements() dwgInst = defaultdict(list) workset_table = revit.doc.GetWorksetTable() output.print_md("## LINKED AND IMPORTED DWG FILES:") output.print_md('By: [{}]({})'.format(__author__, __contact__)) for dwg in dwgs: if dwg.IsLinked: dwgInst["LINKED DWGs:"].append(dwg) else: dwgInst["IMPORTED DWGs:"].append(dwg) for link_mode in dwgInst: output.print_md("####{}".format(link_mode)) for dwg in dwgInst[link_mode]: dwg_id = dwg.Id dwg_name = \ dwg.Parameter[DB.BuiltInParameter.IMPORT_SYMBOL_NAME].AsString() dwg_workset = workset_table.GetWorkset(dwg.WorksetId).Name dwg_instance_creator = \ DB.WorksharingUtils.GetWorksharingTooltipInfo(revit.doc, dwg.Id).Creator if current_view_only \ and revit.active_view.Id != dwg.OwnerViewId: continue print('\n\n') output.print_md("**DWG name:** {}\n\n" "- DWG created by:{}\n\n" "- DWG id: {}\n\n" "- DWG workset: {}\n\n" .format(dwg_name, dwg_instance_creator, output.linkify(dwg_id), dwg_workset))
def is_referenced(v): view_refs = DB.FilteredElementCollector(revit.doc)\ .OfCategory(DB.BuiltInCategory.OST_ReferenceViewer)\ .WhereElementIsNotElementType()\ .ToElements() view_refs_names = set() for view_ref in view_refs: ref_param = view_ref.LookupParameter('Target view') view_refs_names.add(ref_param.AsValueString()) refsheet = v.LookupParameter('Referencing Sheet') refviewport = v.LookupParameter('Referencing Detail') refprefix = VIEWREF_PREFIX.get(v.ViewType, '') if refsheet \ and refviewport \ and refsheet.AsString() != '' \ and refviewport.AsString() != '' \ or (refprefix + v.ViewName) in view_refs_names: return True
def hide_all_elements(view): """Hides all elements visible in provided view. Args: view (DB.View): view to search on Returns: list[DB.ElementId]: list of hidden element ids """ # hide all elements in the view cl_view_elements = DB.FilteredElementCollector(view.Document, view.Id) \ .WhereElementIsNotElementType() elements_to_hide = [el.Id for el in cl_view_elements.ToElements() if not el.IsHidden(view) and el.CanBeHidden(view)] if elements_to_hide: try: view.HideElements(List[DB.ElementId](elements_to_hide)) except Exception as exc: mlogger.warn(exc) return elements_to_hide
def create_sheets(self, sender, args): self.Close() if self._process_sheet_code(): if self.sheet_cb.IsChecked: create_func = self._create_sheet transaction_msg = 'Batch Create Sheets' if not self._ask_for_titleblock(): script.exit() else: create_func = self._create_placeholder transaction_msg = 'Batch Create Placeholders' with DB.TransactionGroup(revit.doc, transaction_msg) as tg: tg.Start() for sheet_num, sheet_name in self._sheet_dict.items(): logger.debug('Creating Sheet: {}:{}'.format( sheet_num, sheet_name)) create_func(sheet_num, sheet_name) tg.Assimilate()
def WallFinishType(self): try: WallFinishName = self.WrapedRoom.parameters[ ParameterName.Room_Wall_Finish].value param_id = DB.ElementId(DB.BuiltInParameter.SYMBOL_NAME_PARAM) parameter_filter = db.ParameterFilter(param_id, equals=WallFinishName) WallType = db.Collector(of_category='OST_Walls', parameter_filter=parameter_filter, is_type=True).get_first() WallType = WallType.unwrap() return WallType except Exception as e: print("{roomname} 没有设置墙体类型,使用默认墙体".format(roomname=self.RoomName)) defaultWallTypeId = doc.GetDefaultElementTypeId( DB.ElementTypeGroup.WallType) WallType = doc.GetElement(defaultWallTypeId) return WallType
def viewTypeId(): # Collect all viewType elevCollector = DB.FilteredElementCollector(doc).OfClass(DB.ViewFamilyType) elevs = [ x for x in elevCollector if x.LookupParameter("Family Name").AsString() == "Elevation" ] # Check if user's input is required if len(elevs) > 1: elevNames = sorted([ElevForm(x) for x in elevs], key=lambda x: x.FamilyName) # Prompt selection list return forms.SelectFromList.show(elevNames, "Elevation Type", 600, 300).Id elif len(elevs) == 1: return elevs[0].Id else: alert( "No Elevation Marker has been defined in the project. Please create an Elevation Marker." )
def find_workset(workset_name_or_list, doc=None, partial=True): workset_clctr = \ DB.FilteredWorksetCollector(doc or HOST_APP.doc).ToWorksets() if type(workset_name_or_list) == list: for workset in workset_clctr: for workset_name in workset_name_or_list: if workset_name in workset.Name: return workset elif type(workset_name_or_list) == str: workset_name = workset_name_or_list if partial: for workset in workset_clctr: if workset_name in workset.Name: return workset else: for workset in workset_clctr: if workset_name == workset.Name: return workset
def make_floor(): Floor_CurveArray = DB.CurveArray() for boundary_segment in self.RoomBoundary()[0]: Floor_CurveArray.Append(boundary_segment.GetCurve()) #Floor_CurveArray.Append(Wall_curves) FloorType = self.FloorFinishType level = self.RoomLevel _doc = pyrevit._HostApplication(__revit__).doc.Create try: self.NewFloor = _doc.NewFloor(Floor_CurveArray, FloorType, level, None) self.NewFloor.get_Parameter( DB.BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).Set( self.RoomBase) print("{RoomName}建筑楼板被创建".format(RoomName=self.RoomName)) except Exception as e: self.NewFloor = None print("{RoomName}建筑楼板未能被创建:{Problem}".format( RoomName=Room.RoomName, Problem=e.__traceback__))
def create_tag_schedule(tag, category, src_schedule): """Create a schedule, listing elements of the given tag and category. Args: tag (Tag): tag to create schedule for category (DB.Category): element category to filter the elements by src_schedule (DB.ViewSchedule): source schedule to match style and schema Returns: DB.ViewSchedule: newly created schedule """ doc = src_schedule.Document newsched_name = '{} ({})'.format(tag.name, category.Name) newsched = query.get_view_by_name(newsched_name) if not newsched: newsched_id = src_schedule.Duplicate(DB.ViewDuplicateOption.Duplicate) newsched = doc.GetElement(newsched_id) if newsched: param_id = _get_tag_paramid() tagfield = query.get_schedule_field(newsched, tagscfg.get_tags_param()) if not tagfield: tagfield = \ newsched.Definition.AddField(DB.ScheduleFieldType.Instance, param_id) tagfield.IsHidden = True tagfilter_indices = \ query.get_schedule_filters(newsched, tagscfg.get_tags_param(), return_index=True) if tagfilter_indices: for idx in tagfilter_indices: newsched.Definition.RemoveFilter(idx) tagfilter = DB.ScheduleFilter(tagfield.FieldId, DB.ScheduleFilterType.Contains, tag.name) newsched.Definition.AddFilter(tagfilter) revit.update.set_name(newsched, newsched_name) return newsched
def WallFinishType(self): try: WallFinishName = self.WrapedRoom.parameters['Wall Finish'].value param_id = DB.ElementId(DB.BuiltInParameter.SYMBOL_NAME_PARAM) parameter_filter = db.ParameterFilter(param_id, equals=WallFinishName) WallType = db.Collector(of_category='OST_Walls', parameter_filter=parameter_filter, is_type=True).get_first() return WallType except Exception as e: print( "{roomname} is not set WallFinishType,We use Default Wall Type defaultType" .format(roomname=self.RoomName)) finally: defaultWallTypeId = doc.GetDefaultElementTypeId( DB.ElementTypeGroup.WallType) WallType = doc.GetElement(defaultWallTypeId) return WallType
def create_schedule_records(schedule, fields, records): """Create records in given schedule""" # create records first create_schedule_record(schedule, count=len(records)) # now grab the records and update their param values # iterate over elements and records for keysched_el, record_data in zip( revit.query.get_all_elements_in_view(schedule), records): logger.debug('Processing record: %s', record_data) for idx, field_name in enumerate(fields): if record_data[idx]: p = keysched_el.LookupParameter(field_name) if p and not p.SetValueString(record_data[idx]): if p.StorageType == DB.StorageType.Integer: p.Set(int(record_data[idx])) elif p.StorageType == DB.StorageType.Double: p.Set(float(record_data[idx])) elif p.StorageType == DB.StorageType.String: p.Set(record_data[idx]) elif p.StorageType == DB.StorageType.ElementId: p.Set(DB.ElementId(int(record_data[idx])))
def is_referenced(v): view_refs = DB.FilteredElementCollector(revit.doc)\ .OfCategory(DB.BuiltInCategory.OST_ReferenceViewer)\ .WhereElementIsNotElementType()\ .ToElements() view_refs_names = set() for view_ref in view_refs: ref_param = view_ref.Parameter[ DB.BuiltInParameter.REFERENCE_VIEWER_TARGET_VIEW] view_refs_names.add(ref_param.AsValueString()) refsheet = v.Parameter[DB.BuiltInParameter.VIEW_REFERENCING_SHEET] refviewport = v.Parameter[DB.BuiltInParameter.VIEW_REFERENCING_DETAIL] refprefix = VIEWREF_PREFIX.get(v.ViewType, '') if refsheet \ and refviewport \ and refsheet.AsString() != '' \ and refviewport.AsString() != '' \ or (refprefix + revit.query.get_name(v)) in view_refs_names: return True
def SolidRoom(Room): roomName = Room.Id.ToString() solid = GetElementSolid(Room) build = FlipSolidNormal(solid[0]) newSolid = build.meshSolid().GetGeometricalObjects() new = List[DB.GeometryObject]() new.Add(newSolid[0]) directShapeLibrary = DB.DirectShapeLibrary.GetDirectShapeLibrary(doc) directShapeType = DB.DirectShapeType.Create( doc, roomName, DB.ElementId(DB.BuiltInCategory.OST_Mass)) directShapeType.SetShape(new) directShapeType.Parameter[DB.BuiltInParameter.UNIFORMAT_CODE].Set( "14-90.03") directShapeLibrary.AddDefinitionType(roomName, directShapeType.Id) ds = DB.DirectShape.CreateElementInstance(doc, directShapeType.Id, directShapeType.Category.Id, roomName, DB.Transform.Identity) #ds.SetTypeId(directShapeType.Id) ds.Parameter[DB.BuiltInParameter.ALL_MODEL_MARK].Set("Room:" + roomName) ds.Name = roomName wrapedNewRoom = db.Element(ds) wrapedNewRoom.parameters['Area'] = round(CovertToM2(Room.Area), 1) wrapedNewRoom.parameters['Price'] = Room.Area * 10000 wrapedNewRoom.parameters['BAT_Area'] = db.Element( Room).parameters['BAT_Area'].value wrapedNewRoom.parameters['InterWallType'] = Room.Parameter[ DB.BuiltInParameter.ROOM_FINISH_WALL].AsString() print("done")
def get_elements_by_param_value(param_name, param_value, inverse=False, doc=None): doc = doc or HOST_APP.doc param_id = get_project_parameter_id(param_name) if param_id: pvprov = DB.ParameterValueProvider(param_id) pfilter = DB.FilterStringEquals() vrule = DB.FilterStringRule(pvprov, pfilter, param_value, True) if inverse: vrule = DB.FilterInverseRule(vrule) param_filter = DB.ElementParameterFilter(vrule) return DB.FilteredElementCollector(doc)\ .WherePasses(param_filter)\ .ToElements() else: return []