示例#1
0
 def __init__(self):
     self.xmldata = readxml()
     self.beam = revit.doc.GetElement(
         DB.ElementId(self.xmldata["elementAId"]))
     self.beamdata = clash.get_beam_data(self.beam)
     self.pipe = revit.doc.GetElement(
         DB.ElementId(self.xmldata["elementBId"]))
     self.pipedata = clash.get_pipe_data(self.pipe)
示例#2
0
    def __init__(self, el1, el2, chosenoption):

        self.xmldata = readxml(el1, el2)
        self.beam = revit.doc.GetElement(
            DB.ElementId(self.xmldata["elementAId"]))
        self.beamdata = clash.get_beam_data(self.beam)
        self.pipe = revit.doc.GetElement(
            DB.ElementId(self.xmldata["elementBId"]))
        self.pipedata = clash.get_pipe_data(self.pipe)
示例#3
0
def get_piping_system_type(param_name):
    # Accesses the ID associated with the built-in paramater "System Classification"
    # See RevitApiDocs: BuiltInParameter Enumeration
    param_id = DB.ElementId(DB.BuiltInParameter.RBS_PIPING_SYSTEM_TYPE_PARAM)
    # The filter needs the ID of the parameter we are searching for:
    # See RevitApiDocs: FilterableValueProvider Class
    param_prov = DB.ParameterValueProvider(param_id)
    # The filter also takes a rule evaluation
    # See RevitApiDocs: FilterStringRuleEvaluator Look at the inheritance Heirarchy
    # to get an idea of what options this has.
    filter_rule = DB.FilterStringContains()
    # This line directly translates from the C# example provided in the documentation
    # to the python equivalent. See RevitApiDocs: ElementParameterFilter Class
    case_sensitive = False
    param_filter = DB.FilterStringRule(param_prov, \
                                            filter_rule, \
                                            param_name, \
                                            case_sensitive)
    # Assigns our filter to the element parameter filter so it fits into the
    # 'WherePasses' method
    element_filter = DB.ElementParameterFilter(param_filter)
    # Collect a list of items eligible to get picked by the filter.
    # I found OST_PipeCurves from a combination of looking over the built in categories and
    collected_elements = DB.FilteredElementCollector(doc) \
            .OfCategory(DB.BuiltInCategory.OST_PipeCurves) \
            .WherePasses(element_filter) \
            .ToElements()

    return collected_elements
示例#4
0
def iterate(mode, step_size=1):
    if os.path.isfile(datafile_i):
        f = open(datafile_i, 'r')
        cur_i = pl.load(f)
        f.close()

        if (mode == '-'):
            i = cur_i - step_size
        else:
            i = cur_i + step_size
    else:
        i = 0

    try:
        f = open(datafile, 'r')
        cursel = pl.load(f)
        f.close()
        _i = i
        if (i < 0):
            i = abs(i / len(cursel)) * len(cursel) + i
        elif (i >= len(cursel)):
            i = i - abs(i / len(cursel)) * len(cursel)

        eId = DB.ElementId(int(list(cursel)[i]))
        uidoc.Selection.SetElementIds(List[DB.ElementId]([eId]))

        f = open(datafile_i, 'w')
        pl.dump(i, f)
        f.close()

    except:
        logger.debug('Selection file {0} does not exit'.format(datafile))
示例#5
0
def NewDS(s1, cat1, name1):
    temp_path = System.IO.Path.GetTempPath()
    sat_path = "%s%s.sat" % (temp_path, name1)
    try:
        if factor != 1:
            s1 = s1.Scale(factor)
        sat1 = Geometry.ExportToSAT(s1, sat_path)
        satId = doc.Import(sat1, satOpt, view1)
        el1 = doc.GetElement(satId)
        geom1 = el1.get_Geometry(opt1)
        enum = geom1.GetEnumerator()
        enum.MoveNext()
        geom2 = enum.Current.GetInstanceGeometry()
        enum2 = geom2.GetEnumerator()
        enum2.MoveNext()
        s1 = enum2.Current
        doc.Delete(satId)
        System.IO.File.Delete(sat_path)

        if cat1 is None or not RVT.DirectShape.IsValidCategoryId(cat1.Id, doc):
            cat1Id = RVT.ElementId(RVT.BuiltInCategory.OST_GenericModel)
        else:
            cat1Id = cat1.Id

        if name1 in dst_enum:
            old_type = dst_enum[name1]
            old_type.SetShape([s1])
            fec1 = RVT.FilteredElementCollector(doc).OfClass(
                RVT.DirectShape).WhereElementIsNotElementType()
            insts = [i for i in fec1 if i.GetTypeId().Equals(old_type.Id)]
            if insts:
                ds1 = insts[0]
            else:
                dsLib.AddDefinitionType(name1, old_type.Id)
                if isRvt2017:
                    ds1 = RVT.DirectShape.CreateElementInstance(
                        doc, old_type.Id, cat1Id, name1, tf1)
                else:
                    ds1 = RVT.DirectShape.CreateElementInstance(
                        doc, old_type.Id, cat1Id, name1, tf1, "Dynamo",
                        "spring nodes")
                ds1.SetTypeId(old_type.Id)
        else:
            dsType1 = RVT.DirectShapeType.Create(doc, name1, cat1Id)
            dsType1.SetShape([s1])
            dsLib.AddDefinitionType(name1, dsType1.Id)
            dst_enum[name1] = dsType1
            if isRvt2017:
                ds1 = RVT.DirectShape.CreateElementInstance(
                    doc, dsType1.Id, cat1Id, name1, tf1)
            else:
                ds1 = RVT.DirectShape.CreateElementInstance(
                    doc, dsType1.Id, cat1Id, name1, tf1, "Dynamo",
                    "spring nodes")
            ds1.SetTypeId(dsType1.Id)

        return ueWrapper.Invoke(None, (ds1, False))
    except:
        return traceback.format_exc()
示例#6
0
def get_viewName_prefix_byTemplate(templates):
    templatePrefix = []
    for template in templates:
        if int(template) != -1:
            vtn = (doc.GetElement(DB.ElementId(int(template))).Name)
            templatePrefix.append(vtn.replace(" ","-"))
        else :
            templatePrefix.append("No-Template")
    
    res = MultipleTextInput("Add view prefix according to template :", templatePrefix )
    return list(res)
示例#7
0
def RemoveViewTemplate(viewtype_id):
    view_type = doc.GetElement(viewtype_id)
    template_id = view_type.DefaultTemplateId
    if template_id.IntegerValue != -1:
        if forms.alert(
                "You are about to remove the ViewTempalte associated with this View Type. Is that cool with ya?",
                ok=False,
                yes=True,
                no=True,
                exitscript=True):
            with revit.Transaction("Remove ViewTemplate"):
                view_type.DefaultTemplateId = DB.ElementId(-1)
示例#8
0
def SelectSimilar(where='ActiveView'):
    els = ui.Selection()
    elTypes = FilterSelection(els)

    colEls = []
    colElsc = []

    for pmEnum, pmValues in elTypes.items():
        for elt in pmValues:
            param_id = DB.ElementId(pmEnum)
            parameter_filter = db.ParameterFilter(param_id, equals=elt)
            if where == 'ActiveView':
                colEls = db.Collector(view=doc.ActiveView,
                                      parameter_filter=parameter_filter)
            elif where == 'Project':
                colEls = db.Collector(parameter_filter=parameter_filter)
            else:
                return False
            colEls = colEls.get_elements(True)
            colElsc += colEls

    SetFocus(colElsc)
"""Mark all clashes from an interference report in current view."""

from HTMLParser import HTMLParser
import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
import Autodesk.Revit.DB as db
import Autodesk.Revit.UI as ui
clr.AddReference("System.Windows.Forms")
import System.Windows.Forms as swf

__name = "MarkAllClashes.py"
__version = "1.0b"

CLASH_COLOR = db.Color(255, 0, 0)  # red
CLASH_PATTERN_ID = db.ElementId(19)
FADED_COLOR = db.Color(192, 192, 192)  # light gray
FADED_PATTERN_ID = CLASH_PATTERN_ID
FADED_TRANSPARENCY = 50

clashing_overrides = db.OverrideGraphicSettings()
clashing_overrides.SetProjectionLineColor(CLASH_COLOR)
clashing_overrides.SetProjectionFillColor(CLASH_COLOR)
clashing_overrides.SetProjectionFillPatternId(CLASH_PATTERN_ID)
faded_overrides = db.OverrideGraphicSettings()
faded_overrides.SetProjectionLineColor(FADED_COLOR)
faded_overrides.SetProjectionFillColor(FADED_COLOR)
faded_overrides.SetProjectionFillPatternId(FADED_PATTERN_ID)
faded_overrides.SetSurfaceTransparency(FADED_TRANSPARENCY)

"""Collects all analytical lines"""

# import statements-------------------------------------------------
import clr

clr.AddReferenceByPartialName('PresentationCore')
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName('System')
clr.AddReferenceByPartialName('System.Windows.Forms')

from Autodesk.Revit import DB
from Autodesk.Revit import UI

#import Autodesk.Revit.DB as DB

# ------------------------------------------------------------------

doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument

element_id = DB.ElementId()
#analytical_model_id = DB.Eleme

print(el.GetAnalyticalModel().GetCurve().GetEndPoint(0))
示例#11
0
def get_railing_system():
    # Accesses the ID associated with the built-in paramater "System Classification"
    # See RevitApiDocs: BuiltInParameter Enumeration
    param_id = DB.ElementId(
        DB.BuiltInParameter.RAILING_SYSTEM_HANDRAILS_TYPES_PARAM)
    # The filter needs the ID of the parameter we are searching for:
    # See RevitApiDocs: FilterableValueProvider Class
    param_prov = DB.ParameterValueProvider(param_id)
    # The filter also takes a rule evaluation
    # See RevitApiDocs: FilterStringRuleEvaluator Look at the inheritance Heirarchy
    # to get an idea of what options this has.
    filter_rule = DB.FilterStringContains()
    # This line directly translates from the C# example provided in the documentation
    # to the python equivalent. See RevitApiDocs: ElementParameterFilter Class
    case_sensitive = False
    '''
    param_filter = DB.FilterStringRule(param_prov, \
                                            filter_rule, \
                                            param_name, \
                                            case_sensitive)
    '''
    # Assigns our filter to the element parameter filter so it fits into the
    # '.WherePasses(element_filter)' method
    '''
    element_filter = DB.ElementParameterFilter(param_filter)

    '''
    # Collect a list of items eligible to get picked by the filter.
    # I found OST_PipeCurves from a combination of looking over the built in categories and
    '''
    options for the collected elements
                .WhereElementIsNotElementType().
                .OfClass(typeof(FamilyInstance))
    '''
    collected_elements = []
    proj_stairs_railings = []
    proj_hand_railings = []
    proj_top_railings = []
    # print("\n" + "-" * 25 + "Stairs Railings: " + "-" * 25)
    stairs_railings = DB.FilteredElementCollector(doc) \
            .OfCategory(DB.BuiltInCategory.OST_StairsRailing) \
            .WhereElementIsNotElementType() \
            .ToElements()
    for rail in stairs_railings:
        collected_elements.append(rail)
        proj_stairs_railings.append(rail)
        # print(rail.Id)

    # print("\n" + "-" * 25 + "Hand Railings: " + "-" * 25)
    hand_railings = DB.FilteredElementCollector(doc) \
            .OfCategory(DB.BuiltInCategory.OST_RailingHandRail) \
            .WhereElementIsNotElementType() \
            .ToElements()
    for rail in hand_railings:
        collected_elements.append(rail)
        proj_hand_railings.append(rail)

        # print(rail.Id)

    # print("\n" + "-" * 25 + "Top Railings: " + "-" * 25)
    top_railings = DB.FilteredElementCollector(doc) \
            .OfCategory(DB.BuiltInCategory.OST_RailingTopRail) \
            .WhereElementIsNotElementType() \
            .ToElements()
    for rail in top_railings:
        collected_elements.append(rail)
        proj_top_railings.append(rail)
        # print(rail.Id)

    # for element in collected_elements:
    #     print(str(element))
    return collected_elements, proj_stairs_railings, proj_hand_railings, proj_top_railings
示例#12
0
from Autodesk.Revit import DB

clr.ImportExtensions(RhinoInside.Revit.Convert.Geometry)
doc = Revit.ActiveDBDocument

if 'generated_wall_id' not in globals():
    generated_wall_id = None

if P:
    P = rs.coercegeometry(P)
    lvloffset = P.GetBoundingBox(False).Min.Z
    print lvloffset
    curves = [x.ToLine() for x in list(P.ToPolyline().GetSegments())]
    #    curves = [rs.coercegeometry(x).ToCurve() for x in P]
    print curves
    wall_type = doc.GetElement(DB.ElementId(T))
    level = doc.GetElement(DB.ElementId(L))
    lvlel = level.Parameter[
        DB.BuiltInParameter.LEVEL_ELEV].AsDouble() * Revit.ModelUnits
    off = lvloffset - lvlel
    print lvlel
    tg = DB.TransactionGroup(doc, 'group')
    tg.Start()

    t = DB.Transaction(doc, 'Create Wall from Profile')
    t.Start()
    if generated_wall_id:
        doc.Delete(generated_wall_id)
    new_wall = None
    print(curves, wall_type.Id, level.Id, ST)
    new_wall = DB.Wall.Create(doc, curves, wall_type.Id, level.Id, ST)
def main():
    """Main Function."""

    print("Running {fname} version {ver}...".format(fname=__name,
                                                    ver=__version))

    # STEP 0: Setup
    doc = __revit__.ActiveUIDocument.Document
    view = doc.ActiveView

    # STEP 1: Ask user for clash report html file adn parse it
    print("Opening interference check report file...")
    open_dialog = swf.OpenFileDialog()
    open_dialog.Title = "Open Interference Check Report"
    open_dialog.Filter = "HMTL files (*.html)|*.html"
    if open_dialog.ShowDialog() == swf.DialogResult.OK:  # file selected
        file_path = open_dialog.FileName
        # STEP 2: Parse clash report file and summarize findings
        print("Reading {fname}...".format(fname=file_path))
        with open(file_path, mode="rb") as html_file:
            html = html_file.read()  # just read the plain bytes
            uhtml = unicode(
                html, "utf-16")  # Revit exports html in UTF-16(-LE) encoding
        print("Parsing file contents...")
        parser = InterferenceReportParser()
        parser.feed(uhtml)
        parser.close()
        clashes = parser.clashes
        clashing_ids = []
        for pair in parser.clashes.values():
            for elem_id in pair:
                clashing_ids.append(elem_id)
        clashing_ids = set(clashing_ids)
        # Get all element ids of the elements in the view
        all_ids = db.FilteredElementCollector(doc, view.Id)\
                    .WhereElementIsNotElementType()\
                    .ToElementIds()
        all_ids = set([elem_id.IntegerValue for elem_id in all_ids])
        # Get all element ids of non-clashing elements in the view
        non_clashing_ids = all_ids - clashing_ids
        # Create summary text for user input dialog
        summary_text = "Checked report {path}\n".format(path=file_path)
        summary_text += "Found {num} clashes in the report.\n".format(
            num=len(clashes))
        summary_text += "Found {num} clashing elements involved in those clashes.\n".format(
            num=len(clashing_ids))
        summary_text += "The total number of elements in the current view is {num}\n".format(
            num=len(all_ids))
        summary_text += "Found {num} non-clashing elements in the current view.".format(
            num=len(non_clashing_ids))
        print(summary_text)

        # STEP 3: Ask user for display option
        dialog = ui.TaskDialog(title="Mark All Clashes")
        dialog.MainInstruction = "Interference Report Summary"
        dialog.MainContent = summary_text
        dialog.AddCommandLink(ui.TaskDialogCommandLinkId.CommandLink1,
                              "Mark clashing elements and fade the rest")
        dialog.AddCommandLink(ui.TaskDialogCommandLinkId.CommandLink2,
                              "Hide all non-clashing elements temporarily")
        dialog.CommonButtons = ui.TaskDialogCommonButtons.Close
        dialog.DefaultButton = ui.TaskDialogResult.Close
        result = dialog.Show()

        # Step 4: Emphasize the clashes based on the user selection
        transaction = db.Transaction(doc)
        transaction.Start("{name} - v{ver}".format(name=__name, ver=__version))
        try:
            if result == ui.TaskDialogResult.CommandLink1:  # Mark clashes and fade the rest
                print("Marking all clashing elements and fading the rest...")
                for elem_id in all_ids:  # fade all visible elements in the view
                    view.SetElementOverrides(db.ElementId(elem_id),
                                             faded_overrides)
                for elem_id in clashing_ids:  # emphasize the clashing elements
                    view.SetElementOverrides(db.ElementId(elem_id),
                                             clashing_overrides)
            elif result == ui.TaskDialogResult.CommandLink2:  # Hide all non-clashing elements
                print(
                    "Hiding all non-clashing elements in the view temporarily..."
                )
                for elem_id in non_clashing_ids:  # hide alll non-clashing elements
                    view.HideElementTemporary(db.ElementId(elem_id))
            else:
                print("Nothing to do.")
        except Exception as ex:
            print("Exception: {ex}".format(ex=ex))
            transaction.RollBack()
        else:
            transaction.Commit()
            print("Done.")
    else:  # no file to parse
        print("Nothing to do.")
示例#14
0
with open('sampleExcel.csv') as f:
	reader = csv.reader(f)
	for row in reader:
		collection.append(row)
		column_Num = len(row)



#Revit Schedule Creation__________________________________________________________________________________
doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument

transaction = DB.Transaction(doc, 'import excel')
transaction.Start()

elemId = DB.ElementId(-1)
sched = DB.ViewSchedule.CreateSchedule(doc, elemId)
sched.Name = "TEST SCHEDULE"


definition = sched.Definition
definition.ShowHeaders = "false"

bodyData = sched.GetTableData().GetSectionData(DB.SectionType.Body)


headerData = sched.GetTableData().GetSectionData(DB.SectionType.Header)

#Bring Excel Data to create Revit Schedule

for i in range(len(collection)):
示例#15
0
def Import():
	import _neo_importer
	import lib.revisions.neo_revisions_main as mn
	with db.Transaction(str('neoCL | Import Revisions')):
		XL, wb = GetWb()
		XL.DisplayAlerts = False
		sh = wb.Worksheets(shName)
		sh.Cells(1, 1).Value = "Importing to Revit... please wait..."

		ri = re
		#ci = ce
	
		while(True):

			newRev = False
			rId = sh.Range[rg(ri, ce)]
			rlog = sh.Range[rg(ri, ce + 8)]
			rDescription = sh.Range[rg(ri, ce + 4)]
			revOrder = sh.Range[rg(ri, ce + 1)].Text
			revOrder = int(revOrder.strip() or 0)

			if rId.Text and not rDescription.Text:
				if mn.DeleteRevision(rId.Text):
					rlog.Value2 = "Revision DELETED!"
				else:
					rlog.Value2 = "Can't delete revision!"
					mn.revIdsToReorder.append([int(revOrder), DB.ElementId(int(rId.Text))])

			elif rDescription.Text:
				try:
					revId = rId.Text
					if revId:
						rev = doc.GetElement(DB.ElementId(int(revId)))
					else:
						rev = DB.Revision.Create(doc)
						revId = rev.Id.ToString()
						sh.Range[rg(ri, ce)].Value2 = "'" + revId
						newRev = True
					mn.revIdsToReorder.append([int(revOrder), DB.ElementId(int(revId))])
					rev.Issued = True if sh.Range[rg(ri, ce + 5)].Text == 'Yes' else False
					if not rev.Issued:
						rev.RevisionDate = sh.Range[rg(ri, ce + 3)].Text
						rev.Description = sh.Range[rg(ri, ce + 4)].Text
						rev.IssuedTo = sh.Range[rg(ri, ce + 6)].Text
						rev.IssuedBy = sh.Range[rg(ri, ce + 7)].Text
						numType = sh.Range[rg(ri, ce + 2)].Text
						if numType == "Numeric":
							rev.NumberType = DB.RevisionNumberType.Numeric 
						elif numType == "Alphanumeric":
							rev.NumberType = DB.RevisionNumberType.Alphanumeric
						elif numType == "None":
							rev.NumberType = DB.RevisionNumberType.None
						rlog.Value2 = "Done."
					else:
						rlog.Value2 = "Can't update data in Issued revisions. Set Issued to No to allow editing."
				except: # OSError as err:
						#print("OS error: {0}".format(err))
						rlog.Value2 = "Error trying to update... Is the Id correct?"
				if newRev:
					rlog.Value2 = "New revision created. " + rlog.Value2

			elif not rId.Text and not rDescription.Text:
				try:
					mn.ReorderRevisions()
					#print("Import is done!")
					sh.Cells(1, 1).Value = "Import to Revit is done!"
				except:
					err = "Process ended. Can't reorder revisions! Are all the revisions listed in Excel? Read HOW TO sheet!"
					#print(err)
					sh.Range[rg(1, 1)].Value2 = err
				sh.Cells.EntireColumn.AutoFit()
				XL.DisplayAlerts = True
				return
			ri += 1
示例#16
0
# Enable Python support and load DesignScript library
import sys

sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\DLLs')
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')

import clr
import json
import os

clr.AddReference('RevitAPI')
clr.AddReference('RevitServices')

from Autodesk.Revit.DB import FilteredElementCollector as FEC
from Autodesk.Revit import DB
from RevitServices.Persistence import DocumentManager

doc = DocumentManager.Instance.CurrentDBDocument

a = doc.GetElement(DB.ElementId(int('237184')))

OUT = a
示例#17
0
            target_parameter_value = ele.Parameter[
                target_parameter].AsValueString()
        except:
            forms.alert("Parameter {0} not found in {1}".format(
                selected_switch_parameter, category_name),
                        exitscript=True)
        decode_valuestring(target_parameter_value, target_category,
                           target_parameter)
    else:
        try:
            target_parameter_value = ele.Parameter[target_parameter].AsDouble()
        except:
            forms.alert("Parameter {0} not found in {1}".format(
                selected_switch_parameter, category_name),
                        exitscript=True)
        param_id = DB.ElementId(target_parameter)
        param_prov = DB.ParameterValueProvider(param_id)
        param_equality = DB.FilterNumericEquals()  # equality class for double
        value_rule = DB.FilterDoubleRule(param_prov, param_equality,
                                         target_parameter_value, 1e-3)
        param_filter = DB.ElementParameterFilter(value_rule)
elif selected_switch_parameter in ["Mark", "Comments"]:  # string values
    try:
        target_parameter_value = ele.Parameter[target_parameter].AsString()
    except:
        forms.alert("Parameter {0} not found in {1}".format(
            selected_switch_parameter, category_name),
                    exitscript=True)
    param_id = DB.ElementId(target_parameter)
    param_prov = DB.ParameterValueProvider(param_id)
    param_equality = DB.FilterStringEquals()  # equality class for string
示例#18
0
					TransactionManager.Instance.TransactionTaskDone()

# Converts selected in IN[0] node elements into list. No matter if there is only
# one or multiple input elements
def getlistOfElements():
	if hasattr(IN[0], '__iter__'):
		return IN[0]
	else:
		return [IN[0]]


# #### RUNS HERE ####
for elementToSplit in getlistOfElements():
	try:
		# Converts dynamo element into db.Element (from revit API)
		revitElement = doc.GetElement(db.ElementId(elementToSplit.Id))
	except AttributeError:
		continue		
	try:
		elementType = revitElement.GetType()
	except TypeError:
		elementType = None
	element = None
	if elementType == db.Wall:
		element = WallSplitter(doc, revitElement)
	elif elementType == db.FamilyInstance:
		# Depending upon structural type of column most suitable class is used for
		# element creation
		structuralType = revitElement.StructuralType
		if structuralType == db.Structure.StructuralType.Column and not revitElement.IsSlantedColumn:
			element = ColumnSplitter(doc, revitElement)
示例#19
0
__author__ = 'Ehsan Iran-Nejad'


# for timing -------------------------------------------------------------------
from pyrevit.coreutils import Timer
timer = Timer()
# ------------------------------------------------------------------------------


import Autodesk.Revit.DB as DB


doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument

height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM)

height_param_prov = DB.ParameterValueProvider(height_param_id)

param_equality = DB.FilterNumericEquals()

heigh_value_rule = DB.FilterDoubleRule(height_param_prov,
                                       param_equality,
                                       10.0,
                                       1E-6)

param_filter = DB.ElementParameterFilter(heigh_value_rule)


walls = DB.FilteredElementCollector(doc) \
          .WherePasses(param_filter) \
示例#20
0
def getlistOfElements():
    try:
        numberOfElements = len(IN[0])
        if numberOfElements > 1:
            return IN[0]
        else:
            return [IN[0]]
    except:
        return [IN[0]]

levels = getListOfLevelIds(doc)
for element in getlistOfElements():
    # converts dynamo element to revit element
    try:
    	revitElement = doc.GetElement(db.ElementId(element.Id))
    except AttributeError:
    	continue    	
    # gets revit element type
    try:
        elementType = revitElement.GetType()
    except TypeError:
        elementType = None
    
    element = None
    if elementType == db.Wall:
        element = WallSplitter(doc, revitElement, levels)
    elif elementType == db.FamilyInstance:
        structuralType = revitElement.StructuralType
        if structuralType == db.Structure.StructuralType.Column and not revitElement.IsSlantedColumn:
            element = ColumnSplitter(doc, revitElement, levels)
def NewDS_R17(geom1, cat1, name1, mat1):
    toDispose = []
    try:
        edg_enum = dict()
        br1 = RVT.BRepBuilder(RVT.BRepType.OpenShell)
        toDispose.append(br1)
        for f in geom1.Faces:
            s1 = f.SurfaceGeometry()
            toDispose.append(s1)
            planarTest = Curve.ByParameterLineOnSurface(
                s1, UV.ByCoordinates(0.01, 0.0), UV.ByCoordinates(0.99, 1))
            isPlanar = abs(
                planarTest.StartPoint.DistanceTo(planarTest.EndPoint) -
                planarTest.Length) <= 0.00001
            toDispose.append(planarTest)
            if isPlanar:
                o1 = s1.PointAtParameter(0.5, 0.5).ToXyz(True)
                v1 = s1.NormalAtParameter(0.5, 0.5).ToXyz(True)
                sf1 = RVT.BRepBuilderSurfaceGeometry.Create(
                    RVT.Plane.CreateByNormalAndOrigin(v1, o1), None)
                isFlipped = False
            else:
                ns1 = s1.ToNurbsSurface()
                toDispose.append(ns1)
                isFlipped = s1.NormalAtParameter(0.5, 0.5).Dot(
                    ns1.NormalAtParameter(0.5, 0.5)) < 0
                pts1 = [j.ToXyz(True) for i in ns1.ControlPoints() for j in i]
                weights = [j for i in ns1.Weights() for j in i]
                sf1 = RVT.BRepBuilderSurfaceGeometry.CreateNURBSSurface(
                    ns1.DegreeU, ns1.DegreeV, ns1.UKnots(), ns1.VKnots(), pts1,
                    weights, False, None)
            toDispose.append(sf1)
            sfId = br1.AddFace(sf1, isFlipped)
            if mat1 is not None:
                br1.SetFaceMaterialId(sfId, mat1.Id)
            for lp in f.Loops:
                lp1 = br1.AddLoop(sfId)
                for ce in lp.CoEdges:
                    edg = ce.Edge
                    c0 = edg.CurveGeometry
                    toDispose.append(c0)
                    mp = c0.PointAtParameter(0.5)
                    toDispose.append(mp)
                    edgHash = (round(mp.X, 5), round(mp.Y, 5), round(mp.Z, 5))
                    eId, isReversed, ceCount = edg_enum.get(
                        edgHash, [None, None, None])
                    if eId is None:
                        try:
                            c1 = c0.ToRevitType(True)
                        except:
                            n = len(c0.ToNurbsCurve().ControlPoints())
                            pts = [
                                c0.PointAtParameter(1.0 / n * j)
                                for j in xrange(n + 1)
                            ]
                            toDispose.extend(pts)
                            c1 = NurbsCurve.ByPoints(pts).ToRevitType(True)
                        toDispose.append(c1)
                        e1 = RVT.BRepBuilderEdgeGeometry.Create(c1)
                        toDispose.append(e1)
                        eId = br1.AddEdge(e1)
                        isReversed = ce.Reversed
                        ceCount = 0
                        edg_enum[edgHash] = [eId, not isReversed, ceCount]
                    if ceCount <= 1:
                        br1.AddCoEdge(lp1, eId, isReversed)
                        edg_enum[edgHash][-1] += 1
            br1.FinishLoop(lp1)
            br1.FinishFace(sfId)
        result = br1.Finish()
        if result == RVT.BRepBuilderOutcome.Success:
            if cat1 is None or not RVT.DirectShape.IsValidCategoryId(
                    cat1.Id, doc):
                cat1Id = RVT.ElementId(RVT.BuiltInCategory.OST_GenericModel)
            else:
                cat1Id = cat1.Id
            if name1 in dst_enum:  #definition exists
                old_type = dst_enum[name1]
                old_type.SetShape(br1)
                fec1 = RVT.FilteredElementCollector(doc).OfClass(
                    RVT.DirectShape).WhereElementIsNotElementType()
                insts = [i for i in fec1 if i.GetTypeId().Equals(old_type.Id)]
                if insts:
                    ds1 = insts[0]
                else:
                    dsLib.AddDefinitionType(name1, old_type.Id)
                    ds1 = RVT.DirectShape.CreateElementInstance(
                        doc, old_type.Id, cat1Id, name1, tf1)
                    ds1.SetTypeId(old_type.Id)
            else:
                dsType1 = RVT.DirectShapeType.Create(doc, name1, cat1Id)
                dsType1.SetShape(br1)
                dsLib.AddDefinitionType(name1, dsType1.Id)
                ds1 = RVT.DirectShape.CreateElementInstance(
                    doc, dsType1.Id, cat1Id, name1, tf1)
                ds1.SetTypeId(dsType1.Id)

            return ueWrapper.Invoke(None, (ds1, False))
        else:
            return result
    except:
        return traceback.format_exc()
    finally:
        for i in toDispose:
            i.Dispose()
示例#22
0
  '''
    pha = doc.Phases
    count = 0
    for p in pha:
        p_int = p.Id.IntegerValue
        if p_int == obj_phase:
            break
        else:
            count += 1
    return pha[count]


# Creating Collector instance and collecting all the casework from the model.

# Get Element Ids for all Families in project
family_name_id = DB.ElementId(DB.BuiltInParameter.ALL_MODEL_FAMILY_NAME)

# Get the Name of the Family
family_name_provider = DB.ParameterValueProvider(family_name_id)
# Create a Filter to look for specific text
filter_string_begin_with = DB.FilterStringBeginsWith()
# Filter for specific string
string_begins_with_12_Base = DB.FilterStringRule(family_name_provider,
                                                 filter_string_begin_with,
                                                 '12 BASE', 1)
#Filter for specific string
string_begins_with_12_Tall = DB.FilterStringRule(family_name_provider,
                                                 filter_string_begin_with,
                                                 '12 Tall', 1)
#Filter for specific string
string_begins_with_12_Case = DB.FilterStringRule(family_name_provider,
示例#23
0
文件: import_json.py 项目: dnkngh/BIM
	'Navisworks',
	'Номер секции №',
	'R_Type',
	'СККС_классификатор',
	'СККС_секция',
	'СККС_этаж',
	'СККС_этаж_тип',
	'СККС_группа',
	'СККС_объем',
] 

new_path = r'{}'.format(file_path)

with io.open(file_path, 'r', encoding='utf-8') as infile:
	data = json.load(infile)

TransactionManager.Instance.EnsureInTransaction(doc)
try:
	for element_id in data.keys():
		element = doc.GetElement(DB.ElementId(int(element_id)))
		for parameter_name in data[element_id].keys():
			parameter_value = data[element_id][parameter_name]
			if parameter_value != '-':
				element.LookupParameter(parameter_name).Set(parameter_value)
except:
	pass
TransactionManager.Instance.TransactionTaskDone()

# Назначьте вывод переменной OUT.
OUT = 'OK'