def first_point_is_inside_face(cls, e_1, e_2): """Находится ли первая точка контура внутри поверхности.""" first_point = list(e_1[1])[0].GetEndPoint(0) trans = e_2[0].ComputeDerivatives(UV(0, 0)) Pt = trans.Inverse.OfPoint(first_point) res = e_2[0].IsInside(UV(Pt.X, Pt.Y)) return res
def corners(self): """Возвращает все 4 угла региона.""" p1 = self.points[0] p2 = UV(self.points[1].U, self.points[0].V) p3 = self.points[1] p4 = UV(self.points[0].U, self.points[1].V) return (p1, p2, p3, p4)
def __init__(self, start_p, end_p): """ Args: start_p (_PatternPoint): end_p (_PatternPoint): """ self.start_point = start_p if start_p.v <= end_p.v else end_p self.end_point = end_p if start_p.v <= end_p.v else start_p self.u_vector = UV(1, 0)
def get_all_corner(cls, region, face=None): """Возвращает все углы данного региона.""" pr1, pr2 = region[0], region[1] p1 = pr1 p2 = UV(pr2.U, pr1.V) p3 = pr2 p4 = UV(pr1.U, pr2.V) if face is None: return (p1, p2, p3, p4) return (face.Evaluate(p1), face.Evaluate(p2), face.Evaluate(p3), face.Evaluate(p4))
def region_in_same_direction(cls, region, regions, direction=0): """Находит регионы соответствующего направления.""" regions_same_direction = list() for cur_region in regions: if direction == 0: same_direction = region.points[0].IsAlmostEqualTo(UV(region.points[0].U, cur_region.points[0].V)) and region.points[1].IsAlmostEqualTo(UV(region.points[1].U, cur_region.points[1].V)) else: same_direction = region.points[0].IsAlmostEqualTo(UV(cur_region.points[0].U, region.points[0].V)) and region.points[1].IsAlmostEqualTo(UV(cur_region.points[1].U, region.points[1].V)) if same_direction: regions_same_direction.append(cur_region) return regions_same_direction
def concate_regions(self, *regs): """Объединяет заданные регионы. Находит самую верхнюю левую и нижнюю правую """ us = [self.points[0].U, self.points[1].U] vs = [self.points[0].V, self.points[1].V] for region in regs: us.append(region.points[0].U) vs.append(region.points[0].V) us.append(region.points[1].U) vs.append(region.points[1].V) uv_max = UV(max(us), max(vs)) uv_min = UV(min(us), min(vs)) self.points = (uv_min, uv_max)
def get_tgt_space(self, space_uuid, src_space): try: return self.tgt_spaces[space_uuid] except KeyError: level = self.tgt_levels[src_space.Level.Name] uv = UV(src_space.Location.Point.X, src_space.Location.Point.Y) return self.tgt_doc.Create.NewSpace(level, uv)
def add_offset(self, lines, offset): """Добавляем отступ линии """ new_lines = [] for line in lines: points = [line.GetEndPoint(0), line.GetEndPoint(1)] for point_pos in range(0, 2): point = points[point_pos] faces = set() for face in self.room_faces: plane = face.GetSurface() project_point = plane.Project(point) # echo(project_point) if project_point: if project_point[1] < self.tollerance: faces.add(face) normal_sum = XYZ(0, 0, 0) for face in faces: normal_sum += face.ComputeNormal(UV()) if abs(normal_sum.X) > 0.0001: dev_x = abs(normal_sum.X) else: dev_x = 1 if abs(normal_sum.Y) > 0.0001: dev_y = abs(normal_sum.Y) else: dev_y = 1 normal_sum = XYZ(normal_sum.X / dev_x, normal_sum.Y / dev_y, 0) point -= normal_sum * offset points[point_pos] = point new_lines.append(Line.CreateBound(points[0], points[1])) return new_lines
def fill_grid_from_dict(self, data): fill_grid = FillGrid() for prop_name in FILL_PROP_NAMES: setattr(fill_grid, prop_name, data[prop_name]) setattr(fill_grid, "Origin", UV(*data["Origin"])) setattr(fill_grid, "Segments", data["Segments"]) return fill_grid
def concate_regions(cls, *regs): """Объединяет заданные регионы. Находит самую верхнюю левую и нижнюю правую """ us = set() vs = set() region_type = regs[0][2] for region in regs: us.add(region[0].U) vs.add(region[0].V) us.add(region[1].U) vs.add(region[1].V) uv_max = UV(max(us), max(vs)) uv_min = UV(min(us), min(vs)) return (uv_min, uv_max, region_type)
def space_creator(self, room, lvls): ''' Function creates new spaces room: Revit Room, lvls: level elevations and levels dictionary ''' try: # Get the room level room_lvl = room.Level # Get a level from the lvls dictionary by room level elevation lvl = lvls.get(room_lvl.Elevation) # Create space by coordinates and level taken from room with Transaction(self.doc, "Batch create spaces") as tr: tr.Start() options = tr.GetFailureHandlingOptions() failureHandler = ErrorSwallower() options.SetFailuresPreprocessor(failureHandler) options.SetClearAfterRollback(True) tr.SetFailureHandlingOptions(options) room_coords = self.transform.OfPoint(room.Location.Point) space = self.doc.Create.NewSpace( lvl, UV(room_coords.X, room_coords.Y)) # Get "REFERENCED_ROOM_UNIQUE_ID" parameter ref_id_par = space.GetParameters(self._search_id)[0] # Assign room UniqueID to "REFERENCED_ROOM_UNIQUE_ID" parameter if ref_id_par: if ref_id_par.StorageType == StorageType.String: ref_id_par.Set(room.UniqueId) self.New_MEPSpaces[ room.UniqueId] = self.New_MEPSpaces.get( room.UniqueId, space) self.para_setter(room, space) else: ref_id_par.Set(room.Id.IntegerValue) self.New_MEPSpaces[ room.Id.IntegerValue] = self.New_MEPSpaces.get( room.Id.IntegerValue, space) self.para_setter(room, space) tr.Commit() except Exception as e: logger.error(e, exc_info=True) pass try: with Transaction(self.doc, "Set space Id") as tr: tr.Start() # Get "ID_revit" parameter of a MEP space space_id = space.GetParameters("ID_revit")[0] # Assign space ID to "ID_revit" parameter if space_id: space_id.Set(space.Id.IntegerValue) tr.Commit() except Exception as e: logger.error(e, exc_info=True) pass
def find_nearest_point_by_direction(cls, point, points, direction=0): """Находим ближайшую точку по направлению. direction 0 - по вертикали 1 - по горизонтали """ gen_point = point if direction != 0: gen_point = UV(gen_point.V, gen_point.U) find_point = None for point in points: if direction != 0: temp_point = UV(point.V, point.U) else: temp_point = point if not gen_point.IsAlmostEqualTo(UV(gen_point.U, temp_point.V)): if temp_point.V > gen_point.V: distance = gen_point.DistanceTo(temp_point) if not find_point or find_point[1] > distance: find_point = (temp_point, distance) if find_point: if direction != 0: return UV(find_point[0].V, find_point[0].U) return find_point[0]
def find_wall_direction_faces(cls, wall): """Ищем боковые поверхносит стены.""" faces = cls.get_faces_from_solid(wall) direction = wall.Orientation result = [] for face in faces: normal = face.ComputeNormal(UV(0, 0)) if normal.IsAlmostEqualTo(direction) or normal.Negate().IsAlmostEqualTo(direction): result.append(face) return result
def _make_fill_grid(pattern_grid, scale): rvt_fill_grid = FillGrid() rvt_fill_grid.Angle = pattern_grid.angle rvt_fill_grid.Origin = UV(pattern_grid.origin.u * scale, pattern_grid.origin.v * scale) rvt_fill_grid.Offset = pattern_grid.offset * scale rvt_fill_grid.Shift = pattern_grid.shift * scale if pattern_grid.segments: scaled_segments = [seg * scale for seg in pattern_grid.segments] rvt_fill_grid.SetSegments(scaled_segments) return rvt_fill_grid
def region_find_near(cls, region, regions): """Ищет соседствующие регионы с таким же типом""" region_points = [region[0]] region_points += [UV(region[1].U, region[0].V)] region_points += [UV(region[0].U, region[1].V)] region_points += [region[1]] near_regions = list() for cur_region in regions: if region[2] == cur_region[2]: cur_region_points = [cur_region[0]] cur_region_points += [UV(cur_region[1].U, cur_region[0].V)] cur_region_points += [UV(cur_region[0].U, cur_region[1].V)] cur_region_points += [cur_region[1]] are_near = 0 for region_point in region_points: for cur_region_point in cur_region_points: if cur_region_point.IsAlmostEqualTo(region_point): are_near += 1 if are_near >= 2 and are_near < 4: near_regions.append(cur_region) return near_regions
def get_charactep_points_in_face(cls, face): """ Ищет все характерные точки на плоскости. Сейчас работает только с прямыми линиями. """ cls = face.GetEdgesAsCurveLoops() u_set = set() v_set = set() for cl in cls: for line in cl: if isinstance(line, Line): uv = face.Project(line.GetEndPoint(0)).UVPoint u_set.add(uv.U) v_set.add(uv.V) all_UV_points = set() for u in u_set: for v in v_set: all_UV_points.add(UV(u, v)) return all_UV_points
BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToElements() def GetElementCenter(el, v): cen = el.Location.Point z = (el.UpperLimit.Elevation + el.LimitOffset) / 2 cen = cen.Add(XYZ(0, 0, z)) return cen # def GetElementCenter( el, v ): # bounding = el.BoundingBox[v] # center = (bounding.Max + bounding.Min) * 0.5 # return center t = Transaction(doc, 'Tag All Rooms in All Views') t.Start() for v in views: for el in rooms: loc = GetElementCenter(el, v) if isinstance(v, View3D) or isinstance(v, ViewDrafting) or isinstance( v, ViewSheet): continue else: roomtag = doc.Create.NewRoomTag(LinkElementId(el.Id), UV(loc.X, loc.Y), v.Id) if isinstance(v, ViewSection): roomtag.Location.Move(XYZ(0, 0, loc.Z)) t.Commit()
# noinspection PyUnresolvedReferences from Autodesk.Revit.DB import FilteredElementCollector as Fec # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import BuiltInCategory, LinkElementId, UV, XYZ, ViewSection, ViewPlan views = Fec(doc).OfCategory( BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements() rooms = Fec(doc).OfCategory( BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToElements() def GetElementCenter(el, v): cen = el.Location.Point z = (el.UpperLimit.Elevation + el.LimitOffset) / 2 cen = cen.Add(XYZ(0, 0, z)) return cen with Action('Tag All Rooms in All Views'): for v in views: for el in rooms: room_center = GetElementCenter(el, v) if type(v) in [ViewSection, ViewPlan]: logger.debug('Working on view: %s' % v.ViewName) roomtag = doc.Create.NewRoomTag( LinkElementId(el.Id), UV(room_center.X, room_center.Y), v.Id) if isinstance(v, ViewSection): roomtag.Location.Move(XYZ(0, 0, room_center.Z))
active_lvl = active_view.GenLevel class RoomWarningSwallower(IFailuresPreprocessor): def PreprocessFailures(self, failuresAccessor): fail_list = List[FailureMessageAccessor]() fail_acc_list = failuresAccessor.GetFailureMessages().GetEnumerator() for failure in fail_acc_list: failure_id = failure.GetFailureDefinitionId() failure_severity = failure.GetSeverity() failure_type = BuiltInFailures.RoomFailures.RoomNotEnclosed if failure_id == failure_type: print("{0} with id: {1} of type: RoomNotEnclosed removed!". format(failure_severity, failure_id.Guid)) failuresAccessor.DeleteWarning(failure) return FailureProcessingResult.Continue # "Start" the transaction tx = Transaction(doc, "place unenclosed room") tx.Start() options = tx.GetFailureHandlingOptions() options.SetFailuresPreprocessor(RoomWarningSwallower()) tx.SetFailureHandlingOptions(options) room = doc.Create.NewRoom(active_lvl, UV(0, 0)) # "End" the transaction tx.Commit()
from scriptutils import logger from revitutils import doc, Action # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import FilteredElementCollector as Fec # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import BuiltInCategory, LinkElementId, UV, XYZ, ViewSection, ViewPlan views = Fec(doc).OfCategory( BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements() spaces = Fec(doc).OfCategory(BuiltInCategory.OST_MEPSpaces).WhereElementIsNotElementType().ToElements() def GetElementCenter(el, v): cen = el.Location.Point z = (el.UpperLimit.Elevation + el.LimitOffset) / 2 cen = cen.Add( XYZ( 0, 0, z ) ) return cen with Action('Tag All Rooms in All Views'): for v in views: for el in spaces: room_center = GetElementCenter(el, v) if type(v) in [ViewSection, ViewPlan]: logger.debug('Working on view: %s' % v.ViewName) roomtag = doc.Create.NewRoomTag(LinkElementId(el.Id), UV(room_center.X, room_center.Y), v.Id) if isinstance(v, ViewSection): roomtag.Location.Move(XYZ(0, 0, room_center.Z))
class _PatternLine: def __init__(self, start_p, end_p): """ Args: start_p (_PatternPoint): end_p (_PatternPoint): """ self.start_point = start_p if start_p.v <= end_p.v else end_p self.end_point = end_p if start_p.v <= end_p.v else start_p self.u_vector = UV(1, 0) def __repr__(self): return '<_PatternLine Start:{} End:{} Length:{} Angle:{}>'.format( self.start_point, self.end_point, self.length, self.angle) @property def direction(self): return _PatternPoint(self.end_point.u - self.start_point.u, self.end_point.v - self.start_point.v) @property def angle(self): # always return angle to u direction # todo: fix and use actual math for angles to remove revit dependency return self.u_vector.AngleTo(UV(self.direction.u, self.direction.v)) @property def center_point(self): return _PatternPoint((self.end_point.u + self.start_point.u) / 2.0, (self.end_point.v + self.start_point.v) / 2.0) @property def length(self): return abs(sqrt(self.direction.u**2 + self.direction.v**2)) def point_on_line(self, point, tolerance=ZERO_TOL): a = self.start_point b = self.end_point c = point if 0.0 <= abs((a.u - c.u) * (b.v - c.v) - (a.v - c.v) * (b.u - c.u)) <= tolerance: return True else: return False def intersect(self, pat_line): xdiff = _PatternPoint(self.start_point.u - self.end_point.u, pat_line.start_point.u - pat_line.end_point.u) ydiff = _PatternPoint(self.start_point.v - self.end_point.v, pat_line.start_point.v - pat_line.end_point.v) def det(a, b): return a.u * b.v - a.v * b.u div = det(xdiff, ydiff) if div == 0: raise PyRevitException('Lines do not intersect.') d = _PatternPoint(det(self.start_point, self.end_point), det(pat_line.start_point, pat_line.end_point)) int_point_x = det(d, xdiff) / div int_point_y = det(d, ydiff) / div return _PatternPoint(int_point_x, int_point_y) def rotate(self, origin, angle): self.start_point.rotate(origin, angle) self.end_point.rotate(origin, angle)
def angle(self): # always return angle to u direction # todo: fix and use actual math for angles to remove revit dependency return self.u_vector.AngleTo(UV(self.direction.u, self.direction.v))
BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements() ''' linkrooms = [] linkrooms.append(FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToElements()) levels = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements() ''' t = Transaction(doc, 'Create Spaces') t.Start() for g_rooms in linkrooms: for room in g_rooms: if room.Area > 0: list = [] message = [] cArray = CurveArray() pt = room.Location.Point uv = UV(pt.X, pt.Y) elev = round(room.Level.Elevation) level2 = None for level in levels: elev2 = round(level.Elevation) if elev == elev2: level2 = level if level2 is not None: if round(level2.Elevation) == round( doc.ActiveView.GenLevel.Elevation): name = room.get_Parameter( BuiltInParameter.ROOM_NAME).AsString() number = room.get_Parameter( BuiltInParameter.ROOM_NUMBER).AsString() height = room.get_Parameter(
from Autodesk.Revit.UI import TaskDialog from System import Math uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document curview = doc.ActiveView if isinstance(curview, View3D) and curview.IsSectionBoxActive: try: ref = uidoc.Selection.PickObject(ObjectType.Face) el = doc.GetElement(ref.ElementId) face = el.GetGeometryObjectFromReference(ref) box = curview.GetSectionBox() norm = face.ComputeNormal(UV(0, 0)).Normalize() boxNormal = box.Transform.Basis[0].Normalize() angle = norm.AngleTo(boxNormal) axis = XYZ(0, 0, 1.0) origin = XYZ(box.Min.X + (box.Max.X - box.Min.X) / 2, box.Min.Y + (box.Max.Y - box.Min.Y) / 2, 0.0) if norm.Y * boxNormal.X < 0: rotate = Transform.CreateRotationAtPoint(axis, Math.PI / 2 - angle, origin) else: rotate = Transform.CreateRotationAtPoint(axis, angle, origin) box.Transform = box.Transform.Multiply(rotate) t = Transaction(doc, 'Orient Section Box to Face') t.Start() curview.SetSectionBox(box) uidoc.RefreshActiveView()
cl_views = FilteredElementCollector(doc) views = cl_views.OfCategory( BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements() cl_rooms = FilteredElementCollector(doc) spaces = cl_rooms.OfCategory( BuiltInCategory.OST_MEPSpaces).WhereElementIsNotElementType().ToElements() def GetElementCenter(el, v): cen = el.Location.Point z = (el.UpperLimit.Elevation + el.LimitOffset) / 2 cen = cen.Add(XYZ(0, 0, z)) return cen t = Transaction(doc, 'Tag All Spaces in All Views') t.Start() for v in views: for el in spaces: loc = GetElementCenter(el, v) if isinstance(v, View3D) or isinstance(v, ViewDrafting) or isinstance( v, ViewSheet): continue else: spacetag = doc.Create.NewSpaceTag(el, UV(loc.X, loc.Y), v) if isinstance(v, ViewSection): spacetag.Location.Move(XYZ(0, 0, loc.Z)) t.Commit()