Пример #1
0
def override_graphics_region(doc,
                             view,
                             region,
                             fg_pattern_id,
                             fg_color,
                             bg_pattern_id,
                             bg_color,
                             line_color=None,
                             line_pattern_id=None,
                             lineweight=None):
    """Function to ovverride given region with the override settings.
    :param doc:             Revit Document
    :param region:          FilledRegion to apply OverrideGraphicsSettings
    :param fg_pattern_id:   Foreground - Pattern id
    :param fg_color:        Foreground - Colour
    :param bg_pattern_id:   Background - Pattern id
    :param bg_color:        Background - Colour
    :return:                None """
    try:
        override_settings = OverrideGraphicSettings()
        if fg_pattern_id != ElementId(-1):
            override_settings.SetSurfaceForegroundPatternId(fg_pattern_id)
            override_settings.SetSurfaceForegroundPatternColor(fg_color)
        else:
            override_settings.SetSurfaceForegroundPatternColor(
                Color(255, 255, 255))

        if bg_pattern_id != ElementId(-1):
            override_settings.SetSurfaceBackgroundPatternId(bg_pattern_id)
            override_settings.SetSurfaceBackgroundPatternColor(bg_color)
        else:
            override_settings.SetSurfaceBackgroundPatternColor(
                Color(255, 255, 255))

        # LINE
        if line_color: override_settings.SetProjectionLineColor(line_color)
        if line_pattern_id:
            override_settings.SetProjectionLinePatternId(line_pattern_id)
        if lineweight: override_settings.SetProjectionLineWeight(lineweight)

        view.SetElementOverrides(region.Id, override_settings)

    except:
        # DELETE REGIONS IF MODEL PATTERN IS USED ?
        doc.Delete(region.Id)
Пример #2
0
 def assign_graphics(self, revit_material, group):
     doc = self.doc
     graphic_name = GROUP_GRAPHICS[group]
     data = self.graphics_dict[graphic_name]
     for prop_name in COLOR_PROP_NAMES:
         setattr(revit_material, prop_name, Color(*data[prop_name]))
     for prop_name in PATTERN_PROP_NAMES:
         pattern_id = self.patterns_dict[data[prop_name]["Name"]]
         setattr(revit_material, prop_name, pattern_id)
Пример #3
0
def run():

    # retrieve List color from excel file
    lcolor = [
        sheet.cell_value(row,
                         col2num("A") - 1) for row in range(1, sheet.nrows)
    ]

    # eval ele in list
    lcolor = map(eval_str, lcolor)

    # Filtered Element Collector family instance
    f_family_ins = FilteredElementCollector(doc).OfClass(FamilyInstance)

    # create dict key: id, value: family instaces
    dic_ele = dict_by_familyinstance(f_family_ins)

    # start index value
    index = 0

    # start transaction
    t = Transaction(doc, "Change Color Element")
    t.Start()

    for keyid in list(dic_ele.keys()):

        if index >= len(lcolor):
            index = 0

        # get index of color
        r, b, g = lcolor[index]

        # get color
        color_ele = Color(r, b, g)

        for ele_in in dic_ele[keyid]:
            # Settings to override display of elements in a view.
            override = OverrideGraphicSettings()

            # Sets the projection surface fill color
            override.SetProjectionFillColor(color_ele)

            # Sets the projection surface fill pattern
            override.SetProjectionFillPatternId(pattern_color())

            # Sets graphic overrides for an element in the view.
            view.SetElementOverrides(ele_in.Id, override)

        index = index + 1
    # commit transaction
    t.Commit()
Пример #4
0
def new_line_style(name="NewLine",
                   pattern_id=plain_line_pattern_id,
                   color=None,
                   weight=1):
    # type: (str, ElementId, Color, int) -> Category
    """Create a new line style which is actually a new subcategory of OST_Lines

    """
    line = categories.NewSubcategory(line_category, name)  # type: Category

    if not color:
        color = Color(0, 0, 0)
    line.LineColor = color

    line.SetLinePatternId(pattern_id, GraphicsStyleType.Projection)

    line.SetLineWeight(weight, GraphicsStyleType.Projection)

    return line
Пример #5
0
TransactionManager.Instance.EnsureInTransaction(doc)

for v in views:
    if v.ViewType == ViewType.FloorPlan:
        scale = v.Scale
        elems = FilteredElementCollector(doc, v.Id).OfClass(CurveElement)
        for e in elems:
            graphics_style_cat = e.LineStyle.GraphicsStyleCategory
            id_cat = graphics_style_cat.Id
            if BuiltInCategory(id_cat.IntegerValue) == BuiltInCategory.OST_ProfileFamilies:
                cat = graphics_style_cat
                line_length += e.GeometryCurve.Length

gs = cat.GetGraphicsStyle(GraphicsStyleType.Projection)
gsCat = gs.GraphicsStyleCategory
gsCat.LineColor = Color(IN[1].Red, IN[1].Green, IN[1].Blue)  # noqa
v.Scale = 1
v.Scale = scale

line_length = UnitUtils.ConvertFromInternalUnits(line_length, DisplayUnitType.DUT_MILLIMETERS)

f_manager = doc.FamilyManager
param_name = "_Профиль.Длина"
length_param = f_manager.get_Parameter(param_name)

if len(list(f_manager.Types)) == 0:
    f_manager.NewType('Тип 1')

if length_param:
    if length_param.CanAssignFormula:
        f_manager.SetFormula(length_param, str(line_length))
GNU General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
"""

__doc__ = 'Sets the element graphic overrides to white projection color on the selected elements.'

__window__.Close()
from Autodesk.Revit.DB import Transaction, OverrideGraphicSettings, LinePatternElement, Group, Color

uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
selection = [
    doc.GetElement(elId)
    for elId in __revit__.ActiveUIDocument.Selection.GetElementIds()
]

with Transaction(doc, 'Whiteout Selected Elements') as t:
    t.Start()
    for el in selection:
        if el.ViewSpecific:
            continue
        elif isinstance(el, Group):
            for mem in el.GetMemberIds():
                selection.append(doc.GetElement(mem))
        ogs = OverrideGraphicSettings()
        ogs.SetProjectionLineColor(Color(255, 255, 255))
        doc.ActiveView.SetElementOverrides(el.Id, ogs)
    t.Commit()
Пример #7
0
def AddPrefixtoLines(doc, start_time, limit):
    lineStyles = doc.Settings.Categories.get_Item(
        BuiltInCategory.OST_Lines).SubCategories
    line_dict = {}
    paramList = []
    out = []
    # Unique Graphic Style Collector
    for i in lineStyles:
        lineColor = int(i.LineColor.Red + i.LineColor.Green + i.LineColor.Blue)
        weight = i.GetLineWeight(GraphicsStyleType.Projection).ToString()
        pattern = doc.GetElement(
            i.GetLinePatternId(GraphicsStyleType.Projection))
        if pattern is None:
            patternName = 'Solid'
        else:
            patternName = pattern.Name
        # unique parameter of line weight + line pattern as a parameter indicator
        uniqueParam = weight + patternName
        if not uniqueParam in paramList and lineColor == 0:
            if i.Name[0:len(prefix)] == prefix and i.Id.IntegerValue > 0:
                # Create standard line style dictionary
                line_dict[uniqueParam] = i
                paramList.append(uniqueParam)

    # Non-Standard Line Changer
    for i in lineStyles:
        t = Transaction(doc, 'Add PA prefix to Name')
        t.Start()
        if not i.Name[0:len(
                prefix)] == prefix and not i.Id.IntegerValue < 0 and time.time(
                ) - start_time < limit:
            weight = i.GetLineWeight(GraphicsStyleType.Projection).ToString()
            pattern = doc.GetElement(
                i.GetLinePatternId(GraphicsStyleType.Projection))
            if pattern is None:
                patternName = 'Solid'
            else:
                patternName = pattern.Name
            uniqueParam = weight + patternName
            # Try changing it to an existing line style in dictionary
            # if line_dict[uniqueParam]:
            try:
                SetLineStyle(doc, i, line_dict[uniqueParam])
                print('Changed ' + i.Name + ' to ' +
                      line_dict[uniqueParam].Name)
                doc.Delete(i.Id)
            # Create a new, properly named Line Style
            except:
                # else:
                categories = doc.Settings.Categories
                lineCat = doc.Settings.Categories.get_Item(
                    BuiltInCategory.OST_Lines)
                newName = prefix + 'Pen # ' + str(weight) + ' ' + str(
                    patternName)
                #try:
                newLineStyleCat = categories.NewSubcategory(lineCat, newName)
                doc.Regenerate()
                newLineStyleCat.SetLineWeight(int(weight),
                                              GraphicsStyleType.Projection)
                newLineStyleCat.LineColor = Color(0x00, 0x00, 0x00)
                try:
                    newLineStyleCat.SetLinePatternId(
                        pattern.Id, GraphicsStyleType.Projection)
                except:
                    pass
                # Add new Line style to dictionary
                line_dict[uniqueParam] = newLineStyleCat
                print('Renamed ' + i.Name + ' to ' '\'' + newName + '\'')
                SetLineStyle(doc, i, newLineStyleCat)
                doc.Delete(i.Id)
                #except:
                #print('Contains wrong characters ' + '\'' + i.Name + '\'')
        t.Commit()
def col(s):
    arr = [int(i) for i in s.split()]
    return Color(*arr) if len(arr) == 3 else None
Пример #9
0
_____________________________________________________________________
Description:
Switch Background of the Application.
Color will be switching depending on the current background colour.
Order: Black-> Gray -> White -> Black...
_____________________________________________________________________
How-to:
- Click on the button to change background colour in Revit.
_____________________________________________________________________
"""

# IMPORTS
from Autodesk.Revit.DB import Color

# VARIABLES
app = __revit__.Application

# MAIN
if __name__ == '__main__':
    # COLOURS
    Black = Color(0, 0, 0)
    White = Color(255, 255, 255)
    Gray = Color(190, 190, 190)
    current_color = app.BackgroundColor

    if current_color.Blue == 255 and current_color.Red == 255 and current_color.Green == 255:
        app.BackgroundColor = Black
    elif current_color.Blue == 0 and current_color.Red == 0 and current_color.Green == 0:
        app.BackgroundColor = Gray
    else:
        app.BackgroundColor = White
# Библиотеки Revit API
clr.AddReference('RevitAPI') # Основная библиотека Revit API
from Autodesk.Revit.DB import Color, Material # Необходимые классы для импорта

# Библиотеки Dynamo
clr.AddReference('RevitServices') # Работа с документом и транзакциями
from RevitServices.Persistence import DocumentManager as DM # Менеджер документа
from RevitServices.Transactions import TransactionManager as TM # Менеджер транзакций

# Входные переменные для числовых значений от 0 до 255 для каждого из трех каналов цветов
red,green,blue = [IN[i] for i in range(3)] # В каждую переменную подается от двух и более значений

mats = [] # Пустой список для будущих материалов

doc = DM.Instance.CurrentDBDocument # Получение файла документа

TM.Instance.EnsureInTransaction(doc) # Открытие транзакции

# Цикл, создающий материалы и присваивающий им соответствующие имена и значения цветов
for i in range(len(red)): # Перебор индексов элементов на основе длины списка
	r,g,b = red[i],green[i],blue[i] # Получение текущих значений цветовых каналов для материала
	name = '_'.join(['Material',str(r),str(g),str(b)]) # Генерация имени материала
	mat = doc.GetElement(Material.Create(doc,name)) # Создание материалов
	color = Color(r,g,b) # Создание цвета
	mat.Color = color # Присвоение цвета материалу
	mats.append(mat) # Добавление материала в список

TM.Instance.TransactionTaskDone() # Закрытие транзакции

OUT = mats # Вывод созданных материалов из узла Python Script