Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamo-Python
# collection of Dynamo Python functions.
# credits: archi-lab, MEPover, Bimorph, Clockwork, Rhythm and many more
for i in range(0, len(openings)):
subList = []
conElementsIds.append(subList)
for e in openings[i]:
bb = e.Element.get_BoundingBox(doc.ActiveView)
e.HostedBeamDepth
if e.BeamDirection == "dirX":
newMin = XYZ(bb.Min.X - (e.HostedBeamDepth)/304.8, bb.Min.Y, bb.Min.Z)
newMax = XYZ(bb.Max.X + (e.HostedBeamDepth)/304.8, bb.Max.Y, bb.Max.Z)
else:
newMin = XYZ(bb.Min.X, bb.Min.Y - (e.HostedBeamDepth)/304.8, bb.Min.Z)
newMax = XYZ(bb.Max.X, bb.Max.Y + (e.HostedBeamDepth)/304.8, bb.Max.Z)
outline = Outline( newMin,newMax );
oldline = [bb.Min.ToPoint(), bb.Max.ToPoint()]
bbfilter = BoundingBoxIntersectsFilter( outline );
# Use a view to construct the filter so we get only visible elements. For example, the analytical model will be found otherwise.
collector = FilteredElementCollector(doc, doc.ActiveView.Id).OfCategory(BuiltInCategory.OST_StructuralFraming)
# Lets also exclude the view itself (which often will have an intersecting bounding box), and also the element selected.
idsExclude = List[ElementId]();
idsExclude.Add( e.BeamElement.Id );
idsExclude.Add( e.Element.Id );
# Get the set of elements that pass the
# criteria. Note both filters are quick,
# so order is not so important.
connected = collector.Excluding( idsExclude ).WherePasses( bbfilter );
conElements.append(connected)
newBoundingBox.append([newMin.ToPoint(), newMax.ToPoint()])
for c in connected:
subList.append(e.Element)
subList.append(doc.GetElement(e.BeamElement.Id))
subList.append(doc.GetElement(c.Id))
def Position(duct):
if duct.Shape == "Rectangle":
hCheck = "Pass" if duct.Height < duct.HostedBeamDepth/2 else "Failed"
topFlange = "Pass" if round(duct.ZTop - duct.Centroid[2] - duct.Height/2,0) > (duct.HostedBeamDepth/4) else "Failed"
topFlangeValue = round(duct.ZTop - duct.Centroid[2] - duct.Height/2,0)
botFlange = "Pass" if round(duct.HostedBeamDepth - duct.Height - topFlangeValue,0) > (duct.HostedBeamDepth/4) else "Failed"
botFlangeValue = round(duct.HostedBeamDepth - duct.Height - topFlangeValue, 0)
stDist0 = "Pass" if duct.Distance0 - duct.Width/2 > (2*duct.HostedBeamDepth + 100) else "Failed"
stDist0Value = duct.Distance0 - duct.Width/2
stDist1 = "Pass" if duct.Distance1 - duct.Width/2 > (2*duct.HostedBeamDepth + 100) else "Failed"
stDist1Value = duct.Distance1 - duct.Width/2
return ["Opening Height: " + hCheck + ": " + str(duct.Height), "Distance from Top Flange: " + topFlange + ": " + str(topFlangeValue), "Distance from Bottom Flange: " + botFlange + ": " + str(botFlangeValue), "Distance from Start Point: " + stDist0 + ": " + str(stDist0Value), "Distance from End Point: " + stDist1 + ": " + str(stDist1Value), duct.Element]
else:
hCheck = "Pass" if duct.Width < duct.HostedBeamDepth/2 else "Failed"
topFlange = "Pass" if round(duct.ZTop - duct.Centroid[2] - duct.Width/2,0) > (duct.HostedBeamDepth/4) else "Failed"
topFlangeValue = round(duct.ZTop - duct.Centroid[2] - duct.Width/2,0)
botFlange = "Pass" if round(duct.HostedBeamDepth - duct.Width - topFlangeValue,0) > (duct.HostedBeamDepth/4) else "Failed"
botFlangeValue = round(duct.HostedBeamDepth - duct.Width - topFlangeValue, 0)
stDist0 = "Pass" if duct.Distance0 - duct.Width/2 > (2*duct.HostedBeamDepth + 100) else "Failed"
stDist0Value = duct.Distance0 - duct.Width/2
stDist1 = "Pass" if duct.Distance1 - duct.Width/2 > (2*duct.HostedBeamDepth + 100) else "Failed"
stDist1Value = duct.Distance1 - duct.Width/2
return ["Opening Height: " + hCheck + ": " + str(duct.Width), "Distance from Top Flange: " + topFlange + ": " + str(topFlangeValue), "Distance from Bottom Flange: " + botFlange + ": " + str(botFlangeValue), "Distance from Start Point: " + stDist0 + ": " + str(stDist0Value), "Distance from End Point: " + stDist1 + ": " + str(stDist1Value), duct.Element]
def CheckSpace(duct0, duct1):
allow = max(2*duct0.Width,2*duct1.Width)
distance = math.pow((math.pow((duct0.Centroid[0]-duct1.Centroid[0]),2) + math.pow((duct0.Centroid[1]-duct1.Centroid[1]),2)),0.5)-duct0.Width/2-duct1.Width/2
bool = distance > allow
return ["Required distance: " + str(round(allow,0)), "Actual distance: " + str(round(distance,0)), "Actual>Required? " + str(bool), duct0.Element]
import clr
#The inputs to this node will be stored as a list in the IN variables.
class GridPoint():
def __init__(self):
self.Point = None
self.Name = None
self.vGrid = None
self.hGrid = None
pass
gridObjects= []
for vGrid in IN[1]:
for hGrid in IN[2]:
instance = GridPoint()
instance.Name = vGrid+hGrid
instance.vGrid = vGrid
instance.hGrid = hGrid
gridObjects.append(instance)
for g,p in zip(gridObjects, IN[0]):
g.Point = p
#Assign your output to the OUT variable.
OUT = gridObjects
import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.UI import *
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Form, Button, Label, TextBox
doc = __revit__.ActiveUIDocument.Document
def createView ( sender, event): # creates drafting view
viewTypes = list(FilteredElementCollector(doc).OfClass(ViewFamilyType))
for vt in viewTypes:
if str(vt.ViewFamily) == 'Drafting':
viewType = vt
break
t = Transaction (doc, 'Make new Drafting view')
t.Start()
newDraftingView = ViewDrafting.Create(doc, viewType.Id)
newDraftingView.Name = textBox.Text
t.Commit()
status.Text = 'Drafting View created!'
# create Windows form
form = Form()
form.Width = 300
form.Height = 145
# Title text
label = Label()
label.Text = "New Drafting View name"
label.Width = 280
label.Parent = form
# User input
textBox = TextBox()
textBox.Text = "Enter View Name here"
textBox.Width = 280
textBox.Top += 25
textBox.Parent = form
# Button to action
button = Button()
button.Text = "Create View"
button.Click += createView
button.Width = 280
button.Top += 50
button.Parent = form
# Title text
status = Label()
status.Text = ""
status.Width = 280
status.Top += 75
status.Parent = form
form.ShowDialog()
area = UnwrapElement(IN[0])
F=IN[1] #Load value
loadtype=UnwrapElement(IN[2])
opt = SpatialElementBoundaryOptions()
opt.StoreFreeBoundaryFaces = False
opt.SpatialElementBoundaryLocation.Center
listLoad = []
TransactionManager.Instance.EnsureInTransaction(doc)
for i in range(0,len(area)):
profileLoops = []
segs = area[i].GetBoundarySegments(opt)
for i in range(0,len(segs)):
pL = CurveLoop()
profileLoops.Add(pL)
for j in range(0,len(segs[i])):
pL.Append(segs[i][j].GetCurve())
listLoad.append(AreaLoad.Create(doc,profileLoops,F.ToXyz(False),loadtype[0]))
TransactionManager.Instance.TransactionTaskDone()
OUT = listLoad
TransactionManager.Instance.EnsureInTransaction(doc)
pts = UnwrapElement(IN[0])
innerPts = UnwrapElement(IN[1])
frt = UnwrapElement(IN[2])
profileLoops = []
outerProfileLoop = CurveLoop()
#innerProfileLoop = CurveLoop()
profileLoops.Add(outerProfileLoop)
#profileLoops.Add(innerProfileLoop)
#create filled region
for i in range(0,len(pts)-1):
outerProfileLoop.Append(
Autodesk.Revit.DB.Line.CreateBound(
XYZ(pts[i].X,pts[i].Y,pts[i].Z),
XYZ(pts[i+1].X,pts[i+1].Y,pts[i+1].Z)
)
)
for j in range(0,len(innerPts)):
innerProfileLoop = CurveLoop()
profileLoops.Add(innerProfileLoop)
for i in range(0,len(innerPts[j])-1):
innerProfileLoop.Append(
Autodesk.Revit.DB.Line.CreateBound(
XYZ(innerPts[j][i].X,innerPts[j][i].Y,innerPts[j][i].Z),
XYZ(innerPts[j][i+1].X,innerPts[j][i+1].Y,innerPts[j][i+1].Z)
)
)
region = FilledRegion.Create(doc,frt[0].Id,activeViewId,profileLoops)
regions.Add(region)
TransactionManager.Instance.TransactionTaskDone()
def dispose_dyna_geom(args):
for arg in args:
arg.Dispose()
# Copy and paste from Bakery "GetElementRotation" node by Lukes Johnson
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
# Import RevitAPI
clr.AddReference('RevitAPI')
import Autodesk
#The inputs to this node will be stored as a list in the IN variable.
elements = UnwrapElement(IN[0])
outlist = [] #export list
templist = [] #temporary list to group attributes by element
for i in elements:
templist.append(i.HandOrientation) #vector XYZ Hand
templist.append(i.FacingFlipped) #is mirrored over X axis?
templist.append(i.HandFlipped) #is mirrored over Y axis?
outlist.append(templist[:])
del templist[:] #clear the templist
#Assign your output to the OUT variable
OUT = outlist
# Copy and paste from Bakery "GetElementRotation" node by Lukes Johnson
import clr
from math import *
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
#The inputs to this node will be stored as a list in the IN variable.
dataEnteringNode = IN
X=IN[0] #HandOrientation vector.X
Y=IN[1] #HandOrientation vector.Y
outlist = []
templist = []
templist2 = []
count = 0
for e in X:
templist.append((acos(e))) #rotation angle
#if HandOrientation vector.Y >=0 beam angle = rotation angle
#else beam angle = angle + [2*(180-angle)] => reflex angle
while count < len(templist):
#for item in templist:
if Y[count] >= 0:
templist2.append(degrees(templist[count]))
elif Y[count] < 0:
templist2.append((degrees(templist[count])) + (2*(180-(degrees(templist[count])))))
count = count + 1
for e in templist2:
if e == 0:
outlist.append(0)
else:
outlist.append(360 - e)
#Assign your output to the OUT variable
OUT = outlist
# when the beam does not have cut back applied
def GetEndPoints(beam):
return [beam.Location.Curve.GetEndPoint(0).ToPoint(),
beam.Location.Curve.GetEndPoint(1).ToPoint()]
#use when the beam has a cut back (location curve goes node to node)
def BeamEndPoints_InstaGeom(beam):
opt = Options()
opt.ComputeReferences = True
opt.IncludeNonVisibleObjects = True
#opt.View = doc.ActiveView
opt.DetailLevel = ViewDetailLevel.Medium
geo = beam.get_Geometry(opt)
solids = []
for item in geo:
try:
solids.append(item.GetInstanceGeometry())
except:
""
faces = [solid.Faces for solid in solids[0]]
bb1 = faces[1][0].Origin
bb2 = faces[1][1].Origin
return [bb1, bb2]
#use when the beam has a cut back (location curve goes node to node)
def BeamEndPoints_SolidGeom(beam):
opt = Options()
opt.ComputeReferences = True
opt.IncludeNonVisibleObjects = True
#opt.View = doc.ActiveView
opt.DetailLevel = ViewDetailLevel.Medium
pts = []
geo = beam.get_Geometry(opt)
for g in geo:
try:
pts.append([g.Faces[0].Origin,g.Faces[1].Origin])
except:
""
return pts[0]
for b in beam:
geo = b.get_Geometry(opt)
subList = []
check.append(subList)
for g in geo:
if g.GetType().ToString() == "Autodesk.Revit.DB.Solid":
subList.append("Solid")
else:
subList.append("Instance")
ptsList = []
for c,b in zip(check,beam):
if "Solid" in c:
ptsList.append(BeamEndPoints_SolidGeom(b))
else:
ptsList.append(BeamEndPoints_InstaGeom(b))
# when the beam has cutback applied. Some memory leak crashes Dynamo. Method taken from Marcello Sgambelluri
def BeamZTop(beam)
zOffset = GetBuiltInParam(beam, BuiltInParameter.Z_OFFSET_VALUE) # NEGATIVE VALUE!
return GetEndPoints(beam)[0].Z + zOffset
def beamRealCurve(element):
vertex = element.Geometry()[0].Vertices
pGeom = []
for v in vertex:
pGeom.append(v.PointGeometry)
dispose_dyna_geom(vertex) #DISPOSE
crv = LineBestFit(pGeom)
dispose_dyna_geom(pGeom) #DISPOSE
stPt = crv.PointAtParameter(0)
endPt = crv.PointAtParameter(1)
crv.Dispose() #DISPOSE
return [stPt, endPt]
def BeamZTop(beam):
zOffset = GetBuiltInParam(beam, BuiltInParameter.Z_OFFSET_VALUE) # NEGATIVE VALUE!
return GetEndPoints(beam)[0].Z + zOffset
def GetBuiltInParam(element, name):
p = element.get_Parameter(name)
if p.StorageType == StorageType.String:
return p.AsString()
elif p.StorageType == StorageType.ElementId:
elem = doc.GetElement(p.AsElementId())
return elem
elif p.StorageType == StorageType.Double:
ProjectUnits = p.DisplayUnitType
newval = UnitUtils.ConvertFromInternalUnits(p.AsDouble(),ProjectUnits)
return newval
else:
return p.AsInteger()
zOffset = GetBuiltInParam(beam, BuiltInParameter.Z_OFFSET_VALUE)
def getLocation(elem):
lc = elem.Location.Curve
return lc.ToProtoType()
#credit teocomi
#Given an element Id or a list or elementIds, return the matching tags/s found
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
def getTagsByElementId(beamIds):
doc = DocumentManager.Instance.CurrentDBDocument
allTags = FilteredElementCollector(doc).OfClass(IndependentTag).ToElements()
return loopSublists(beamIds, allTags)
def loopSublists(data, allTags):
out = []
if type(data) is list:
for d in data:
out.append(loopSublists(d, allTags))
elif data != None:
matches = []
for i in allTags:
if str(i.TaggedElementId.HostElementId) == str(data):
matches.append(i)
# if multiple matches nest them
if len(matches) == 1:
out = matches[0]
elif len(matches) == 0:
out = None
else:
out = matches
return out
OUT = getTagsByElementId(IN[0])
# simplified version
import clr
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
doc = DocumentManager.Instance.CurrentDBDocument
elements = UnwrapElement(IN[0])
thost = []
tags = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFramingTags).ToElements()
result = []
for e in elements:
subList = []
result.append(subList)
for t in tags:
try:
tid = t.Id
thost = doc.GetElement(t.TaggedLocalElementId)
if thost.Id == e.Id:
subList.append(t)
except:
""
OUT = result
def GetElemType(e):
try:
elemType = doc.GetElement(e.GetTypeId())
return elemType
except:
pass
return None
#credit MEPover
def GetParam(element, name):
p = element.get_Parameter(name)
if p.StorageType == StorageType.String:
return p.AsString()
elif p.StorageType == StorageType.ElementId:
elem = doc.GetElement(p.AsElementId())
return elem
elif p.StorageType == StorageType.Double:
ProjectUnits = p.DisplayUnitType
newval = UnitUtils.ConvertFromInternalUnits(p.AsDouble(),ProjectUnits)
return newval
else:
return p.AsInteger()
#credit: MEPover
def GetDoubleParVal(element, paramName):
value = []
for e in element:
for p in e.Parameters:
if p.Definition.Name == paramName:
ProjectUnits = p.DisplayUnitType
newVal = UnitUtils.ConvertFromInternalUnits(p.AsDouble(),ProjectUnits)
value.append(newVal)
#credit: MEPover
def GetStringParVal(element, paramName):
value = []
for e in element:
for p in e.Parameters:
if p.Definition.Name == paramName:
value.append(p.AsString())
return value
# Place a family instance on an element's face (i.e. a void in a beam)
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)
clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
uidoc=DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument
#Preparing input from dynamo to revit
beam = UnwrapElement(IN[0])
opt = Options()
opt.ComputeReferences = True
opt.IncludeNonVisibleObjects = False
opt.View = doc.ActiveView
geo = []
for obj in beam.get_Geometry(opt):
if isinstance(obj, Solid):
geo.append(obj)
geo.append(obj.ConvertToMany())
geomInst = None;
instTransform = None;
for instance in beam.get_Geometry(opt):
try:
geomInst = instance.GetSymbolGeometry() # Represented in the CS of the family without regards to the orientation and placement location within the project.
instTransform = instance.Transform;
except:
continue
faces = []
geo = []
for solid in geomInst:
faces.Add(solid.Faces)
geo.append(solid.ConvertToMany()) #THIS GIVES BOTH FACES AND LINES
areas = []
for f in faces[0]:
areas.append(f.Area)
webFace = faces[0][6]
bboxUV = webFace.GetBoundingBox()
center = (bboxUV.Max + bboxUV.Min) * 0.5; #PLACE THE FAMILY IN THE CENTER OF THE SURFACE
start = bboxUV.Min; # PLACE THE FAMILY AT A DISTANCE FROM THE BEAM START POINT
location = webFace.Evaluate(start);
normal = webFace.ComputeNormal(center); #THIS WORKS FOR SOLID/INSTANCE GEOMETRY
refDir = normal.CrossProduct(XYZ.BasisZ); #THIS WORKS FOR SOLID/INSTANCE GEOMETRY
transformedPoint = instTransform.OfPoint(location);
tNormal = instTransform.OfPoint(normal); # THIS DOES NOT GIVE THE CORRECT VECTOR
transformedDir = instTransform.OfPoint(refDir); # THIS DOES NOT GIVE THE CORRECT VECTOR
direction = beam.Location.Curve.GetEndPoint(0) - beam.Location.Curve.GetEndPoint(1) #CALCULATE THE BEAM DIRECTION FROM ITS END POINTS
fs = UnwrapElement(IN[1]) #VOID FAMILY TYPE
TransactionManager.Instance.EnsureInTransaction(doc)
void = doc.Create.NewFamilyInstance.Overloads[Reference, XYZ, XYZ, FamilySymbol](webFace.Reference, transformedPoint, direction, fs);
#void = doc.Create.NewFamilyInstance(location,fs,normal,beam,StructuralType.NonStructural); THIS WOULD WORK FOR WALLS OR FLOORS. IN BEAMS THE VOID APPEARS ON THE XY PLANE (INSTEAD OF ON THE BEAM WEB)
TransactionManager.Instance.TransactionTaskDone()
OUT = transformedPoint.X*304.8, transformedPoint.Y*304.8, tNormal, transformedDir, direction
import clr
clr.AddReference("ProtoGeometry")
from Autodesk.DesignScript.Geometry import *
# Import RevitAPI
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
clr.AddReference("RevitAPIUI")
from Autodesk.Revit.UI import TaskDialog
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
# Import ToProtoType, ToRevitType geometry conversion extension methods
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
doc = DocumentManager.Instance.CurrentDBDocument
my_list = IN[0]
unique = list(set(my_list))
indexes = []
f = lambda my_list, value:filter(lambda x: my_list[x] == value, range(len(my_list)))
for x in unique:
indexes.append(f(my_list, x))
#Assign your output to the OUT variable.
OUT = indexes
# sublist example
V0 = IN[0]
V1 = IN[1]
# Assign your output to the OUT variable.
OUT = [[v+temp for temp in V1] for v in V0]
[s[:-2] for s in IN[0]]
# Repeat the items in a list of lists according to a list of integers
# main list = [1..5,6..10]
# repeater = Math.Round(Math.RandomList(5)*20)
main = IN[0]
repeater = IN[1]
result = []
for m in main:
sub = []
result.append(sub)
for item,r in zip(m,repeater):
subList = []
sub.append(subList)
for i in range(0,int(r)):
subList.append(item)
OUT = result
class Opening:
def __init__(self, Shape, Width, Height, Centroid, HostedBeamDepth, BeamDirection, Distance0, Distance1, ZTop, Element, BeamElement):
self.Shape = Shape
self.Width = Width
self.Height = Height
self.Centroid = Centroid
self.HostedBeamDepth = HostedBeamDepth
self.BeamDirection = BeamDirection
self.Distance0 = Distance0
self.Distance1 = Distance1
self.ZTop = ZTop
self.Element = Element
self.BeamElement = BeamElement
pass
def printOut(self):
return [self.Shape, self.Width, self.Height, self.Centroid, self.HostedBeamDepth, self.BeamDirection, self.Distance0, self.Distance1, self.ZTop, self.Element, self.BeamElement]
pass
def distance(self, point):
return Geometry.DistanceTo(self.Centroid, point)
pass
def XYDistance(self, Pt1):
distance = math.pow((math.pow((self.Centroid.X-Pt1.X),2) + math.pow((self.Centroid.Y-Pt1.Y),2)),0.5)
return round(distance,0)
pass
def __getitem__(self, item):
return getattr(self, item)
pass
for i in range(0,len(beamList)):
subMEP = []
MEPobjects.append(subMEP)
subKeys = []
keys.append(subKeys)
for j in range(0,len(ductList[i])):
if ductList[i][j].Name == "OpeningDuct":
centroid = ductList[i][j].Location.Point.ToPoint()
stPt = beamEndPts[i][0].ToPoint()
endPt = beamEndPts[i][1].ToPoint()
vct = Vector.ByTwoPoints(stPt, endPt).X
if vct > 0:
beamDir = "dirX"
else:
beamDir = "dirY"
Distance0 = int(PointXYDistance(centroid, stPt))
Distance1 = int(PointXYDistance(centroid, endPt))
instance = Opening ( "Rectangle",
int(GetParamValue(ductList[i][j], "x")),
int(GetParamValue(ductList[i][j], "z")),
[centroid.X, centroid.Y, centroid.Z],
int(GetParamValue(beamList[i], "COBie.Type.NominalHeight")),
beamDir,
Distance0,
Distance1,
BeamZTop(beamList[i]),
ductList[i][j],
beamList[i]
)
subKeys.append(instance.Distance0)
subMEP.append(instance)
centroid.Dispose()
stPt.Dispose()
endPt.Dispose()
else:
centroid = ductList[i][j].Location.Point.ToPoint()
stPt = beamEndPts[i][0].ToPoint()
endPt = beamEndPts[i][1].ToPoint()
vct = Vector.ByTwoPoints(stPt, endPt).X
if vct > 0:
beamDir = "dirX"
else:
beamDir = "dirY"
Distance0 = int(PointXYDistance(centroid, stPt))
Distance1 = int(PointXYDistance(centroid, endPt))
instance = Opening ( "Pipe",
int(GetParamValue(ductList[i][j], "x")),
int(GetParamValue(ductList[i][j], "y")),
[centroid.X, centroid.Y, centroid.Z],
#int(GetParamValue(GetElemType(beamList[i]), "d")),
int(GetParamValue(beamList[i], "COBie.Type.NominalHeight")),
beamDir,
Distance0,
Distance1,
BeamZTop(beamList[i]),
ductList[i][j],
beamList[i]
)
subKeys.append(instance.Distance0)
subMEP.append(instance)
centroid.Dispose()
stPt.Dispose()
endPt.Dispose()
#credit Danny Bentley
def PlaceFamInst(point, famtype, x, y, z, angle):
ST = StructuralType.NonStructural
TransactionManager.Instance.EnsureInTransaction(doc)
newobj = doc.Create.NewFamilyInstance(point.ToXyz(),famtype,ST)
p = newobj.LookupParameter("x")
p.Set((x/304.8)/math.sin(math.radians(angle)))
p = newobj.LookupParameter("y")
p.Set(y/304.8)
p = newobj.LookupParameter("z")
p.Set(z/304.8)
p = newobj.LookupParameter("Comments")
#p.Set(Element.Name.__get__(famtype))
p.Set("Cable Trays")
TransactionManager.Instance.TransactionTaskDone()
return newobj
def PointXYDistance(Pt0, Pt1):
distance = math.pow((math.pow((Pt0.X-Pt1.X),2) + math.pow((Pt0.Y-Pt1.Y),2)),0.5)
return round(distance,0)
if isinstance(IN[0], list):
element = UnwrapElement(IN[0])
else:
element = [UnwrapElement(IN[0])]
#credits Clockwork package
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
import Autodesk
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
import math
doc = DocumentManager.Instance.CurrentDBDocument
getDocUnits = doc.GetUnits()
getDisplayUnits = getDocUnits.GetFormatOptions(UnitType.UT_Length).DisplayUnits
projloc = doc.ActiveProjectLocation
position_data = projloc.GetProjectPosition(XYZ.Zero)
location_data = projloc.GetSiteLocation()
elevation = UnitUtils.ConvertFromInternalUnits(position_data.Elevation, getDisplayUnits)
x = UnitUtils.ConvertFromInternalUnits(position_data.EastWest, getDisplayUnits)
y = UnitUtils.ConvertFromInternalUnits(position_data.NorthSouth, getDisplayUnits)
angle = position_data.Angle * 180 / math.pi
OUT = (-angle, elevation, x, y)
#Select all model elements in the Revit model (excluding Element Types, Views, Levels...)
collector = FilteredElementCollector( doc ).WhereElementIsNotElementType()
cat = []
for c in collector:
if (None != c.Category and c.Category.HasMaterialQuantities):
cat.append(c)
#this will not work with MEP objects. To capture them:
for c in collector:
if (None != c.Category and c.Category.CanAddSubcategory):
cat.append(c)
for m in MEPobjects:
sortedDucts = sorted(m, key=lambda instance: instance["Distance0"])
sortedResults.append(sortedDucts)
OUT = u"\u00F8"
def SplitString(string, char):
return string.split(char)
from System.Diagnostics import Stopwatch
sw = Stopwatch.StartNew()
a = 0
for i in range(0,IN[0]):
a += 1
#Assign your output to the OUT variable.
OUT = a, sw.Elapsed.TotalMilliseconds
# Transform from Survey coordinates to Dynamo internal coordinates (CS based in the Revit origin acquired using revitOrigin.py).
# PBP has been moved away from the Revit origin!
def transform(x,y,alfa,a,b){
xtransformed = (x-a)*Math.Cos(alfa)-(y-b)*Math.Sin(alfa);
ytransformed = (x-a)*Math.Sin(alfa)+(y-b)*Math.Cos(alfa);
pt = Autodesk.Point.ByCoordinates(xtransformed, ytransformed);
return pt;
};
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
# if you do not wrap the element, you will get an attribute error when trying to access some of its parameters (i.e. Name)
# https://github.com/DynamoDS/Dynamo/wiki/Python-0.6.3-to-0.7.x-Migration#revitapi
viewNames = []
for vft in FilteredElementCollector(sourceDoc).OfClass(ViewFamilyType):
viewNames.append(vft.ToDSType(True).Name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment