public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; List <Element> filledRegions = new List <Element>(); if (Util.GetSelectedElementsOrAll( filledRegions, uidoc, typeof(FilledRegion))) { int n = filledRegions.Count; string[] results = new string[n]; int i = 0; foreach (FilledRegion region in filledRegions.Cast <FilledRegion>()) { string desc = Util.ElementDescription(region); List <XYZ> corners = GetBoundaryCorners( region); string result = (null == corners) ? "failed" : string.Join(", ", corners.ConvertAll <string>( p => Util.PointString(p)) .ToArray()); results[i++] = string.Format("{0}: {1}", desc, result); } string s = string.Format( "Retrieving corners for {0} filled region{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); string t = string.Join("\r\n", results); Util.InfoMsg2(s, t); } return(Result.Succeeded); }
void Report(FilteredElementCollector a) { int n = 0; string s = _msg; foreach (Element e in a) { ++n; s += string.Format("\r\n {0}", Util.ElementDescription(e)); } s = string.Format(s, n, Util.PluralSuffix(n)); Util.InfoMsg(s); }
/// <summary> /// Return all wall profile boundary loop polygons /// for the given walls, offset out from the outer /// face of the wall by a certain amount. /// </summary> static public List <List <XYZ> > GetWallProfilePolygons( //Application app, List <Element> walls, Options opt) { XYZ p, q, v, w; //Options opt = app.Create.NewGeometryOptions(); List <List <XYZ> > polygons = new List <List <XYZ> >(); foreach (Wall wall in walls) { string desc = Util.ElementDescription(wall); LocationCurve curve = wall.Location as LocationCurve; if (null == curve) { throw new Exception(desc + ": No wall curve found."); } p = curve.Curve.GetEndPoint(0); q = curve.Curve.GetEndPoint(1); v = q - p; v = v.Normalize(); w = XYZ.BasisZ.CrossProduct(v).Normalize(); if (wall.Flipped) { w = -w; } GeometryElement geo = wall.get_Geometry(opt); //GeometryObjectArray objects = geo.Objects; // 2012 //foreach( GeometryObject obj in objects ) // 2012 foreach (GeometryObject obj in geo) // 2013 { Solid solid = obj as Solid; if (solid != null) { GetProfile(polygons, solid, v, w); } } } return(polygons); }
/// <summary> /// Read the value of the element ROOM_OCCUPANCY parameter. /// If it ends in a number, increment the number, else append "1". /// </summary> static void BumpOccupancy(Element e) { Parameter p = e.get_Parameter( BuiltInParameter.ROOM_OCCUPANCY); if (null == p) { Debug.Print( "{0} has no room occupancy parameter.", Util.ElementDescription(e)); } else { string occupancy = p.AsString(); string newOccupancy = BumpStringSuffix( occupancy); p.Set(newOccupancy); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Element e = null; while (true) { try { e = Util.SelectSingleElementOfType( uidoc, typeof(Element), "an element", true); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { message = "No element selected"; break; } if (null == e) { break; } Util.InfoMsg(string.Format( //"{0} is {1} {2} ({3})", "{0} is {1} ({2})", Util.ElementDescription(e), //MepElementShapeVersion3.GetElementShape( e ), MepElementShapeVersion2.GetElementShape(e), MepElementShapeV1.GetElementShape(e))); } return(Result.Succeeded); }
GetElementIds(FilteredElementCollector elements) { Dictionary <ElementId, List <ElementId> > dict = new Dictionary <ElementId, List <ElementId> >(); string fmt = "{0} is hosted by {1}"; foreach (FamilyInstance fi in elements) { ElementId id = fi.Id; ElementId idHost = fi.Host.Id; Debug.Print(fmt, Util.ElementDescription(fi), ElementDescription(idHost)); if (!dict.ContainsKey(idHost)) { dict.Add(idHost, new List <ElementId>()); } dict[idHost].Add(id); } return(dict); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; // Retrieve selected multistory stairs, or all // such elements, if nothing is pre-selected: List <Element> msss = new List <Element>(); if (!Util.GetSelectedElementsOrAll( msss, uidoc, typeof(MultistoryStairs))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some floor elements." : "No floor elements found."; return(Result.Failed); } int n = msss.Count; Debug.Print("{0} multi story stair{1} selected{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); foreach (MultistoryStairs mss in msss) { // Get the stairs by `GetAllStairsIds`, then // call `Element.GetSubelements` to get the // subelements of each stair. ISet <ElementId> ids = mss.GetAllStairsIds(); n = ids.Count; Debug.Print( "Multi story stair '{0}' has {1} stair instance{2}{3}", Util.ElementDescription(mss), n, Util.PluralSuffix(n), Util.DotOrColon(n)); foreach (ElementId id in ids) { Element e = doc.GetElement(id); Stairs stair = e as Stairs; Debug.Assert(null != stair, "expected a stair element"); IList <Subelement> ses = e.GetSubelements(); n = ses.Count; Debug.Print( "Multi story stair instance '{0}' has {1} subelement{2}{3}", Util.ElementDescription(e), n, Util.PluralSuffix(n), Util.DotOrColon(n)); foreach (Subelement se in ses) { Debug.Print( "Subelement {0} of type {1}", se.UniqueId, se.TypeId.IntegerValue); Element e2 = doc.GetElement(se.UniqueId); // null Element e2t = doc.GetElement(se.TypeId); // StairsType IList <ElementId> ps = se.GetAllParameters(); // 24 parameters GeometryObject geo = se.GetGeometryObject(null); } } } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Element e = Util.SelectSingleElement( uidoc, "an element"); if (null == e) { message = "No element selected"; return(Result.Failed); } // Trying to call this property returns the // compile time error: Property, indexer, or // event 'BoundingBox' is not supported by // the language; try directly calling // accessor method 'get_BoundingBox( View )' //BoundingBoxXYZ b = e.BoundingBox[null]; View v = null; BoundingBoxXYZ b = e.get_BoundingBox(v); if (null == b) { v = commandData.View; b = e.get_BoundingBox(v); } if (null == b) { Util.InfoMsg( Util.ElementDescription(e) + " has no bounding box."); } else { using (Transaction tx = new Transaction(doc)) { tx.Start("Draw Model Line Bounding Box Outline"); Debug.Assert(b.Transform.IsIdentity, "expected identity bounding box transform"); string in_view = (null == v) ? "model space" : "view " + v.Name; Util.InfoMsg(string.Format( "Element bounding box of {0} in " + "{1} extends from {2} to {3}.", Util.ElementDescription(e), in_view, Util.PointString(b.Min), Util.PointString(b.Max))); Creator creator = new Creator(doc); creator.DrawPolygon(new List <XYZ>( Util.GetBottomCorners(b))); Transform rotation = Transform.CreateRotation( XYZ.BasisZ, 60 * Math.PI / 180.0); b = RotateBoundingBox(b, rotation); Util.InfoMsg(string.Format( "Bounding box rotated by 60 degrees " + "extends from {0} to {1}.", Util.PointString(b.Min), Util.PointString(b.Max))); creator.DrawPolygon(new List <XYZ>( Util.GetBottomCorners(b))); tx.Commit(); } } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { Debug.Assert(false, "setting the disallow join property was not possible prior to Revit 2012. " + "In Revit 2012, you can use the WallUtils.DisallowWallJoinAtEnd method."); UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; string s = "a wall, to retrieve its join types"; Wall wall = Util.SelectSingleElementOfType( uidoc, typeof(Wall), s, false) as Wall; if (null == wall) { message = "Please select a wall."; } else { JoinType [] a1 = ( JoinType [] )Enum.GetValues(typeof(JoinType)); List <JoinType> a = new List <JoinType>((JoinType[])Enum.GetValues(typeof(JoinType))); int n = a.Count; LocationCurve lc = wall.Location as LocationCurve; s = Util.ElementDescription(wall) + ":\n"; /*for( int i = 0; i < 2; ++i ) * { * JoinType jt = lc.get_JoinType( i ); * int j = a.IndexOf( jt ) + 1; * JoinType jtnew = a[ j < n ? j : 0]; * lc.set_JoinType( j, jtnew ); * s += string.Format( * "\nChanged join type at {0} from {1} to {2}.", * ( 0 == i ? "start" : "end" ), jt, jtnew ); * } * // wall.Location = lc; // Property or indexer 'Autodesk.Revit.Element.Location' cannot be assigned to -- it is read only */ using (Transaction t = new Transaction(doc)) { t.Start("Set Wall Join Type"); for (int i = 0; i < 2; ++i) { JoinType jt = ((LocationCurve)wall.Location).get_JoinType(i); int j = a.IndexOf(jt) + 1; JoinType jtnew = a[j < n ? j : 0]; ((LocationCurve)wall.Location).set_JoinType(j, jtnew); s += string.Format( "\nChanged join type at {0} from {1} to {2}.", (0 == i ? "start" : "end"), jt, jtnew); } t.Commit(); } } Util.InfoMsg(s); return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Selection sel = uidoc.Selection; Reference r = sel.PickObject(ObjectType.Element, "Please pick an element"); // 'Autodesk.Revit.DB.Reference.Element' is // obsolete: Property will be removed. Use // Document.GetElement(Reference) instead. //Element e = r.Element; // 2011 Element e = doc.GetElement(r); // 2012 Transaction tx = new Transaction(doc); tx.Start(_caption); ICollection <ElementId> ids = doc.Delete(e.Id); tx.RollBack(); bool showOnlySketchElements = true; /* * StringBuilder s = new StringBuilder( * _caption + " for host element " + Util.ElementDescription( e ) + ": " ); + + foreach( ElementId id in ids ) + { + Element e = doc.GetElement( id ); + + if( !showOnlySketchElements || e is Sketch || e is SketchPlane ) ||{ || s.Append( Util.ElementDescription( e ) + ", " ); ||} ||} */ List <Element> a = new List <Element>( ids.Select(id => doc.GetElement(id))); string s = _caption + " for host element " + Util.ElementDescription(e) + ": "; s += string.Join(", ", a.Where(e2 => !showOnlySketchElements || e2 is Sketch || e2 is SketchPlane) .Select(e2 => Util.ElementDescription(e2)) .ToArray()); Util.InfoMsg(s); return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; List <Element> a = new List <Element>(); if (!Util.GetSelectedElementsOrAll(a, uidoc, typeof(FamilyInstance))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some family instances." : "No family instances found."; return(Result.Failed); } FamilyInstance inst = a[0] as FamilyInstance; // Here are two ways to traverse the nested instance geometry. // The first way can get the right position, but can't get the right structure. // The second way can get the right structure, but can't get the right position. // What I want is the right structure and right position. // First way: // In the current project project1.rvt, I can get myFamily3 instance via API, // the class is Autodesk.Revit.Elements.FamilyInstance. // Then i try to get its geometry: Options opt = app.Application.Create.NewGeometryOptions(); GeometryElement geoElement = inst.get_Geometry(opt); //GeometryObjectArray a1 = geoElement.Objects; // 2012 //int n = a1.Size; // 2012 int n = geoElement.Count <GeometryObject>(); // 2013 Debug.Print( "Family instance geometry has {0} geometry object{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); int i = 0; //foreach( GeometryObject o1 in a1 ) // 2012 foreach (GeometryObject o1 in geoElement) // 2013 { GeometryInstance geoInstance = o1 as GeometryInstance; if (null != geoInstance) { // geometry includes one instance, so get its geometry: GeometryElement symbolGeo = geoInstance.SymbolGeometry; //GeometryObjectArray a2 = symbolGeo.Objects; // 2012 //foreach( GeometryObject o2 in a2 ) // 2012 // the symbol geometry contains five solids. // how can I find out which solid belongs to which column? // how to relate the solid to the family instance? foreach (GeometryObject o2 in symbolGeo) { Solid s = o2 as Solid; if (null != s && 0 < s.Edges.Size) { List <XYZ> vertices = new List <XYZ>(); GetVertices(vertices, s); n = vertices.Count; Debug.Print("Solid {0} has {1} vertices{2} {3}", i++, n, Util.DotOrColon(n), Util.PointArrayString(vertices)); } } } } // In the Revit 2009 API, we can use // FamilyInstance.Symbol.Family.Components // to obtain the nested family instances // within the top level family instance. // In the Revit 2010 API, this property has been // removed, since we can iterate through the elements // of a family just like any other document; // cf. What's New in the RevitAPI.chm: #if REQUIRES_REVIT_2009_API ElementSet components = inst.Symbol.Family.Components; n = components.Size; #endif // REQUIRES_REVIT_2009_API Document fdoc = doc.EditFamily(inst.Symbol.Family); #if REQUIRES_REVIT_2010_API List <Element> components = new List <Element>(); fdoc.get_Elements(typeof(FamilyInstance), components); n = components.Count; #endif // REQUIRES_REVIT_2010_API FilteredElementCollector collector = new FilteredElementCollector(fdoc); collector.OfClass(typeof(FamilyInstance)); IList <Element> components = collector.ToElements(); Debug.Print( "Family instance symbol family has {0} component{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); foreach (Element e in components) { // there are 3 FamilyInstance: Column, myFamily1, myFamily2 // then we can loop myFamily1, myFamily2 also. // then get all the Column geometry // But all the Column's position is the same, // because the geometry is defined by the Symbol. // Not the actually position in project1.rvt LocationPoint lp = e.Location as LocationPoint; Debug.Print("{0} at {1}", Util.ElementDescription(e), Util.PointString(lp.Point)); } return(Result.Failed); }
string ElementDescription(ElementId id) { Element e = m_doc.GetElement(id); return(Util.ElementDescription(e)); }
/// <summary> /// Remove DWF links from model and return /// the total number of deleted elements. /// </summary> int RemoveDwfLinkUsingExternalFileUtils( Document doc) { List <ElementId> idsToDelete = new List <ElementId>(); ICollection <ElementId> ids = ExternalFileUtils .GetAllExternalFileReferences(doc); foreach (ElementId id in ids) { Element e = doc.GetElement(id); Debug.Print(Util.ElementDescription(e)); ExternalFileReference xr = ExternalFileUtils .GetExternalFileReference(doc, id); ExternalFileReferenceType xrType = xr.ExternalFileReferenceType; if (xrType == ExternalFileReferenceType.DWFMarkup) { ModelPath xrPath = xr.GetPath(); string path = ModelPathUtils .ConvertModelPathToUserVisiblePath(xrPath); if (path.EndsWith(".dwf") || path.EndsWith(".dwfx")) { idsToDelete.Add(id); } } } int n = idsToDelete.Count; ICollection <ElementId> idsDeleted = null; if (0 < n) { using (Transaction t = new Transaction(doc)) { t.Start("Delete DWFx Links"); idsDeleted = doc.Delete(idsToDelete); t.Commit(); } } int m = (null == idsDeleted) ? 0 : idsDeleted.Count; Debug.Print(string.Format( "Selected {0} DWF external file reference{1}, " + "{2} element{3} successfully deleted.", n, Util.PluralSuffix(n), m, Util.PluralSuffix(m))); return(m); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; using (Transaction tx = new Transaction(doc)) { tx.Start("Mirror and List Added"); //Line line = app.Create.NewLine( // XYZ.Zero, XYZ.BasisX, true ); // 2011 //ElementSet els = uidoc.Selection.Elements; // 2011 //Plane plane = new Plane( XYZ.BasisY, XYZ.Zero ); // added in 2012, used until 2016 Plane plane = Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero); // 2017 ICollection <ElementId> elementIds = uidoc.Selection.GetElementIds(); // 2012 using (SubTransaction t = new SubTransaction(doc)) { // determine newly added elements relying on the // element sequence as returned by the filtered collector. // this approach works in both Revit 2010 and 2011: t.Start(); int n = GetElementCount(doc); //doc.Mirror( els, line ); // 2011 //ElementTransformUtils.MirrorElements( // doc, elementIds, plane ); // 2012-2015 ElementTransformUtils.MirrorElements( doc, elementIds, plane, true); // 2016 List <Element> a = GetElementsAfter(n, doc); t.RollBack(); } using (SubTransaction t = new SubTransaction(doc)) { // here is an idea for a new approach in 2011: // determine newly added elements relying on // monotonously increasing element id values: t.Start(); FilteredElementCollector a = GetElements(doc); int i = a.Max <Element>(e => e.Id.IntegerValue); ElementId maxId = new ElementId(i); // doc.Mirror( els, line ); // 2011 //ElementTransformUtils.MirrorElements( // doc, elementIds, plane ); // 2012-2015 ElementTransformUtils.MirrorElements( doc, elementIds, plane, true); // 2016 // get all elements in document with an // element id greater than maxId: a = GetElementsAfter(doc, maxId); Report(a); t.RollBack(); } using (SubTransaction t = new SubTransaction(doc)) { // similar to the above approach relying on // monotonously increasing element id values, // but apply a quick filter first: t.Start(); FilteredElementCollector a = GetElements(doc); int i = a.Max <Element>(e => e.Id.IntegerValue); ElementId maxId = new ElementId(i); //doc.Mirror( els, line ); // 2011 //ElementTransformUtils.MirrorElements( // doc, elementIds, plane ); // 2012-2015 ElementTransformUtils.MirrorElements( doc, elementIds, plane, true); // 2016 // only look at non-ElementType elements // instead of all document elements: a = GetElements(doc); a = GetElementsAfter(a, maxId); Report(a); t.RollBack(); } using (SubTransaction t = new SubTransaction(doc)) { // use a local and temporary DocumentChanged event // handler to directly obtain a list of all newly // created elements. // unfortunately, this canot be tested in this isolated form, // since the DocumentChanged event is only triggered when the // real outermost Revit transaction is committed, i.e. our // local sub-transaction makes no difference. since we abort // the sub-transaction before the command terminates and no // elements are really added to the database, our event // handler is never called: t.Start(); app.DocumentChanged += new EventHandler <DocumentChangedEventArgs>( app_DocumentChanged); //doc.Mirror( els, line ); // 2011 //ElementTransformUtils.MirrorElements( // doc, elementIds, plane ); // 2012-2015 ElementTransformUtils.MirrorElements( doc, elementIds, plane, true); // 2016 app.DocumentChanged -= new EventHandler <DocumentChangedEventArgs>( app_DocumentChanged); Debug.Assert(null == _addedElementIds, "never expected the event handler to be called"); if (null != _addedElementIds) { int n = _addedElementIds.Count; string s = string.Format(_msg, n, Util.PluralSuffix(n)); foreach (ElementId id in _addedElementIds) { Element e = doc.GetElement(id); s += string.Format("\r\n {0}", Util.ElementDescription(e)); } Util.InfoMsg(s); } t.RollBack(); } tx.RollBack(); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Wall wall = Util.SelectSingleElementOfType( uidoc, typeof(Wall), "a wall", false) as Wall; if (null == wall) { message = "Please select a single wall element."; return(Result.Failed); } ICollection <ElementId> delIds = null; using (Transaction t = new Transaction(doc)) { try { t.Start("Temporary Wall Deletion"); delIds = doc.Delete(wall.Id); t.RollBack(); } catch (Exception ex) { message = "Deletion failed: " + ex.Message; t.RollBack(); } } WallFoundation footing = null; foreach (ElementId id in delIds) { footing = doc.GetElement(id) as WallFoundation; if (null != footing) { break; } } string s = Util.ElementDescription(wall); Util.InfoMsg((null == footing) ? string.Format("No footing found for {0}.", s) : string.Format("{0} has {1}.", s, Util.ElementDescription(footing))); return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; int n = uidoc.Selection.GetElementIds().Count; bool preselected = 0 < n; Element e = null; while (true) { try { e = Util.SelectSingleElementOfType( uidoc, typeof(Element), "an element", true); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { message = "No element selected"; break; } if (null == e) { break; } string s = "Not a duct."; Duct duct = e as Duct; if (null != duct) { ConnectorProfileType[] profileTypes = GetProfileTypes(duct); n = profileTypes.GetLength(0); s = string.Format("{0} connectors:\r\n", n) + string.Join("\r\n", profileTypes .Select <ConnectorProfileType, string>( a => a.ToString())); } string msg = string.Format( //"{0} is {1} {2} ({3})", "{0} is {1}-{2} ({3})", Util.ElementDescription(e), //MepElementShapeVersion3.GetElementShape( e ), GetElementShape4(e), MepElementShapeVersion2.GetElementShape(e), MepElementShapeV1.GetElementShape(e)); Util.InfoMsg2(msg, s); if (preselected) { break; } } return(Result.Succeeded); }
public Result ExecuteObsolete( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; BindingMap bindings = doc.ParameterBindings; //Dictionary<string, Guid> guids = new Dictionary<string, Guid>(); Dictionary <Definition, object> mapDefToGuid = new Dictionary <Definition, object>(); int n = bindings.Size; Debug.Print("{0} shared parementer{1} defined{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); if (0 < n) { DefinitionBindingMapIterator it = bindings.ForwardIterator(); while (it.MoveNext()) { Definition d = it.Key as Definition; Binding b = it.Current as Binding; if (d is ExternalDefinition) { Guid g = ((ExternalDefinition)d).GUID; Debug.Print(d.Name + ": " + g.ToString()); mapDefToGuid.Add(d, g); } else { Debug.Assert(d is InternalDefinition); // this built-in parameter is INVALID: BuiltInParameter bip = ((InternalDefinition)d).BuiltInParameter; Debug.Print(d.Name + ": " + bip.ToString()); // if have a definition file and group name, we can still determine the GUID: //Guid g = SharedParamGuid( app, "Identity data", d.Name ); mapDefToGuid.Add(d, null); } } } List <Element> walls = new List <Element>(); if (!Util.GetSelectedElementsOrAll( walls, uidoc, typeof(Wall))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some wall elements." : "No wall elements found."; } else { //List<string> keys = new List<string>( mapDefToGuid.Keys ); //keys.Sort(); foreach (Wall wall in walls) { Debug.Print(Util.ElementDescription(wall)); foreach (Definition d in mapDefToGuid.Keys) { object o = mapDefToGuid[d]; Parameter p = (null == o) ? wall.get_Parameter(d) : wall.get_Parameter((Guid)o); string s = (null == p) ? "<null>" : p.AsValueString(); Debug.Print(d.Name + ": " + s); } } } return(Result.Failed); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = app.ActiveUIDocument.Document; // Retrieve selected walls, or all walls, // if nothing is selected: List <Element> walls = new List <Element>(); if (!Util.GetSelectedElementsOrAll( walls, uidoc, typeof(Wall))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some wall elements." : "No wall elements found."; return(Result.Failed); } //int i; // 2011 int n; double halfThickness, layerOffset; //Creator creator = new Creator( doc ); XYZ lcstart, lcend, v, w, p, q; using (Transaction tx = new Transaction(doc)) { tx.Start("Draw wall layer sepearation lines"); foreach (Wall wall in walls) { string desc = Util.ElementDescription(wall); LocationCurve curve = wall.Location as LocationCurve; if (null == curve) { message = desc + ": No wall curve found."; return(Result.Failed); } // Wall centre line and thickness: lcstart = curve.Curve.GetEndPoint(0); lcend = curve.Curve.GetEndPoint(1); halfThickness = 0.5 * wall.WallType.Width; v = lcend - lcstart; v = v.Normalize(); // one foot long w = XYZ.BasisZ.CrossProduct(v).Normalize(); if (wall.Flipped) { w = -w; } p = lcstart - 2 * v; q = lcend + 2 * v; Creator.CreateModelLine(doc, p, q); q = p + halfThickness * w; Creator.CreateModelLine(doc, p, q); // Exterior edge p = lcstart - v + halfThickness * w; q = lcend + v + halfThickness * w; Creator.CreateModelLine(doc, p, q); //CompoundStructure structure = wall.WallType.CompoundStructure; // 2011 CompoundStructure structure = wall.WallType.GetCompoundStructure(); // 2012 if (null == structure) { message = desc + ": No compound structure " + "found. Is this a stacked wall?"; return(Result.Failed); } //CompoundStructureLayerArray layers = structure.Layers; // 2011 IList <CompoundStructureLayer> layers = structure.GetLayers(); // 2012 //i = 0; // 2011 //n = layers.Size; // 2011 n = layers.Count; // 2012 Debug.Print( "{0} with thickness {1}" + " has {2} layer{3}{4}", desc, Util.MmString(2 * halfThickness), n, Util.PluralSuffix(n), Util.DotOrColon(n)); if (0 == n) { // Interior edge p = lcstart - v - halfThickness * w; q = lcend + v - halfThickness * w; Creator.CreateModelLine(doc, p, q); } else { layerOffset = halfThickness; foreach (CompoundStructureLayer layer in layers) { Debug.Print( " Layer {0}: function {1}, " + "thickness {2}", //++i, // 2011 layers.IndexOf(layer), // 2012 layer.Function, Util.MmString(layer.Width)); //layerOffset -= layer.Thickness; // 2011 layerOffset -= layer.Width; // 2012 p = lcstart - v + layerOffset * w; q = lcend + v + layerOffset * w; Creator.CreateModelLine(doc, p, q); } } tx.Commit(); } } return(Result.Succeeded); }
/// <summary> /// Cumulate the compound wall layer volumes for the given wall. /// </summary> void GetWallLayerVolumes( Wall wall, ref MapLayerToVolume totalVolumes) { WallType wt = wall.WallType; //CompoundStructure structure= wt.CompoundStructure; // 2011 CompoundStructure structure = wt.GetCompoundStructure(); // 2012 //CompoundStructureLayerArray layers = structure.Layers; // 2011 IList <CompoundStructureLayer> layers = structure.GetLayers(); // 2012 //int i, n = layers.Size; // 2011 int i, n = layers.Count; // 2012 double area = GetWallParameter(wall, _bipArea); double volume = GetWallParameter(wall, _bipVolume); double thickness = wt.Width; string desc = Util.ElementDescription(wall); Debug.Print( "{0} with thickness {1}" + " and volume {2}" + " has {3} layer{4}{5}", desc, Util.MmString(thickness), Util.RealString(volume), n, Util.PluralSuffix(n), Util.DotOrColon(n)); // volume for entire wall: string key = wall.WallType.Name; totalVolumes.Cumulate(key, volume); // volume for compound wall layers: if (0 < n) { i = 0; double total = 0.0; double layerVolume; foreach (CompoundStructureLayer layer in layers) { key = wall.WallType.Name + " : " + layer.Function; //layerVolume = area * layer.Thickness; // 2011 layerVolume = area * layer.Width; // 2012 totalVolumes.Cumulate(key, layerVolume); total += layerVolume; Debug.Print( " Layer {0}: function {1}, " + "thickness {2}, volume {3}", ++i, layer.Function, Util.MmString(layer.Width), Util.RealString(layerVolume)); } Debug.Print("Wall volume = {0}," + " total layer volume = {1}", Util.RealString(volume), Util.RealString(total)); if (!Util.IsEqual(volume, total)) { Debug.Print("Wall host volume parameter" + " value differs from sum of all layer" + " volumes: {0}", volume - total); } } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; //// Select all pipes in the entire model. //List<Pipe> pipes = new List<Pipe>( // new FilteredElementCollector( doc ) // .OfClass( typeof( Pipe ) ) // .ToElements() // .Cast<Pipe>() ); //int n = pipes.Count; //// If there are less than two, //// there is nothing we can do. //if( 2 > n ) //{ // message = _prompt; // return Result.Failed; //} //// If there are exactly two, pick those. //if( 2 < n ) //{ // // Else, check for a pre-selection. // pipes.Clear(); // Selection sel = uidoc.Selection; // //n = sel.Elements.Size; // 2014 // ICollection<ElementId> ids // = sel.GetElementIds(); // 2015 // n = ids.Count; // 2015 // Debug.Print( "{0} pre-selected elements.", // n ); // // If two or more model pipes were pre- // // selected, use the first two encountered. // if( 1 < n ) // { // //foreach( Element e in sel.Elements ) // 2014 // foreach( ElementId id in ids ) // 2015 // { // Pipe c = doc.GetElement( id ) as Pipe; // if( null != c ) // { // pipes.Add( c ); // if( 2 == pipes.Count ) // { // Debug.Print( "Found two model pipes, " // + "ignoring everything else." ); // break; // } // } // } // } // // Else, prompt for an // // interactive post-selection. // if( 2 != pipes.Count ) // { // pipes.Clear(); // try // { // Reference r = sel.PickObject( // ObjectType.Element, // new PipeElementSelectionFilter(), // "Please pick first pipe." ); // pipes.Add( doc.GetElement( r.ElementId ) // as Pipe ); // } // catch( Autodesk.Revit.Exceptions // .OperationCanceledException ) // { // return Result.Cancelled; // } // try // { // Reference r = sel.PickObject( // ObjectType.Element, // new PipeElementSelectionFilter(), // "Please pick second pipe." ); // pipes.Add( doc.GetElement( r.ElementId ) // as Pipe ); // } // catch( Autodesk.Revit.Exceptions // .OperationCanceledException ) // { // return Result.Cancelled; // } // } //} JtPairPicker <Pipe> picker = new JtPairPicker <Pipe>(uidoc); Result rc = picker.Pick(); if (Result.Failed == rc) { message = _prompt; } if (Result.Succeeded != rc) { return(rc); } IList <Pipe> pipes = picker.Selected; // Check for same pipe system type. ElementId systemTypeId = pipes[0].MEPSystem.GetTypeId(); Debug.Assert(pipes[1].MEPSystem.GetTypeId() .IntegerValue.Equals( systemTypeId.IntegerValue), "expected two similar pipes"); // Check for same pipe level. ElementId levelId = pipes[0].LevelId; Debug.Assert( pipes[1].LevelId.IntegerValue.Equals( levelId.IntegerValue), "expected two pipes on same level"); // Extract data from the two selected pipes. double wall_thickness = GetWallThickness(pipes[0]); Debug.Print("{0} has wall thickness {1}", Util.ElementDescription(pipes[0]), Util.RealString(wall_thickness)); Curve c0 = pipes[0].GetCurve(); Curve c1 = pipes[1].GetCurve(); if (!(c0 is Line) || !(c1 is Line)) { message = _prompt + " Expected straight pipes."; return(Result.Failed); } XYZ p00 = c0.GetEndPoint(0); XYZ p01 = c0.GetEndPoint(1); XYZ p10 = c1.GetEndPoint(0); XYZ p11 = c1.GetEndPoint(1); XYZ v0 = p01 - p00; XYZ v1 = p11 - p10; if (!Util.IsParallel(v0, v1)) { message = _prompt + " Expected parallel pipes."; return(Result.Failed); } // Select the two pipe endpoints // that are farthest apart. XYZ p0 = p00.DistanceTo(p10) > p01.DistanceTo(p10) ? p00 : p01; XYZ p1 = p10.DistanceTo(p0) > p11.DistanceTo(p0) ? p10 : p11; XYZ pm = 0.5 * (p0 + p1); XYZ v = p1 - p0; if (Util.IsParallel(v, v0)) { message = "The selected pipes are colinear."; return(Result.Failed); } // Normal vector of the plane defined by the // two parallel and offset pipes, which is // the plane hosting the rolling offset XYZ z = v.CrossProduct(v1); // Vector perpendicular to v0 and v0 and // z, i.e. vector pointing from the first pipe // to the second in the cross sectional view. XYZ w = z.CrossProduct(v1).Normalize(); // Offset distance perpendicular to pipe direction double distanceAcross = Math.Abs( v.DotProduct(w)); // Distance between endpoints parallel // to pipe direction double distanceAlong = Math.Abs( v.DotProduct(v1.Normalize())); Debug.Assert(Util.IsEqual(v.GetLength(), Math.Sqrt(distanceAcross * distanceAcross + distanceAlong * distanceAlong)), "expected Pythagorean equality here"); // The required offset pipe angle. double angle = 45 * Math.PI / 180.0; // The angle on the other side. double angle2 = 0.5 * Math.PI - angle; double length = distanceAcross * Math.Tan(angle2); double halfLength = 0.5 * length; // How long should the pipe stubs become? double remainingPipeLength = 0.5 * (distanceAlong - length); if (0 > v1.DotProduct(v)) { v1.Negate(); } v1 = v1.Normalize(); XYZ q0 = p0 + remainingPipeLength * v1; XYZ q1 = p1 - remainingPipeLength * v1; using (Transaction tx = new Transaction(doc)) { // Determine pipe diameter for creating // matching pipes and fittings Pipe pipe = pipes[0]; double diameter = pipe .get_Parameter(bipDiameter) // "Diameter" .AsDouble(); // Pipe type for calls to doc.Create.NewPipe PipeType pipe_type_standard = new FilteredElementCollector(doc) .OfClass(typeof(PipeType)) .Cast <PipeType>() .Where <PipeType>(e => e.Name.Equals("Standard")) .FirstOrDefault <PipeType>(); Debug.Assert( pipe_type_standard.Id.IntegerValue.Equals( pipe.PipeType.Id.IntegerValue), "expected all pipes in this simple " + "model to use the same pipe type"); tx.Start("Rolling Offset"); if (_place_model_line) { // Trim or extend existing pipes (pipes[0].Location as LocationCurve).Curve = Line.CreateBound(p0, q0); (pipes[1].Location as LocationCurve).Curve = Line.CreateBound(p1, q1); // Add a model line for the rolling offset pipe Creator creator = new Creator(doc); Line line = Line.CreateBound(q0, q1); creator.CreateModelCurve(line); pipe = null; } else if (_place_fittings) { // Set active work plane to the rolling // offset plane... removed again, since // this has no effect at all on the // fitting placement or rotation. // //Plane plane = new Plane( z, q0 ); // //SketchPlane sp = SketchPlane.Create( // doc, plane ); // //uidoc.ActiveView.SketchPlane = sp; //uidoc.ActiveView.ShowActiveWorkPlane(); FamilySymbol symbol = new FilteredElementCollector(doc) .OfClass(typeof(FamilySymbol)) .OfCategory(BuiltInCategory.OST_PipeFitting) .Cast <FamilySymbol>() .Where <FamilySymbol>(e => e.Family.Name.Contains("Elbow - Generic")) .FirstOrDefault <FamilySymbol>(); // Set up first 45 degree elbow fitting FamilyInstance fitting0 = doc.Create .NewFamilyInstance(q0, symbol, StructuralType.NonStructural); fitting0.LookupParameter("Angle").Set( 45.0 * Math.PI / 180.0); //fitting0.get_Parameter( bipDiameter ) // does not exist // .Set( diameter ); fitting0.LookupParameter("Nominal Radius") .Set(0.5 * diameter); Line axis = Line.CreateBound(p0, q0); angle = z.AngleTo(XYZ.BasisZ); ElementTransformUtils.RotateElement( doc, fitting0.Id, axis, Math.PI - angle); Connector con0 = Util.GetConnectorClosestTo( fitting0, p0); // Trim or extend existing pipe (pipes[0].Location as LocationCurve).Curve = Line.CreateBound(p0, con0.Origin); // Connect pipe to fitting Util.Connect(con0.Origin, pipe, fitting0); // Set up second 45 degree elbow fitting FamilyInstance fitting1 = doc.Create .NewFamilyInstance(q1, symbol, StructuralType.NonStructural); //fitting1.get_Parameter( "Angle" ).Set( 45.0 * Math.PI / 180.0 ); // 2014 //fitting1.get_Parameter( "Nominal Radius" ).Set( 0.5 * diameter ); // 2014 fitting1.LookupParameter("Angle").Set(45.0 * Math.PI / 180.0); // 2015 fitting1.LookupParameter("Nominal Radius").Set(0.5 * diameter); // 2015 axis = Line.CreateBound( q1, q1 + XYZ.BasisZ); ElementTransformUtils.RotateElement( doc, fitting1.Id, axis, Math.PI); axis = Line.CreateBound(q1, p1); ElementTransformUtils.RotateElement( doc, fitting1.Id, axis, Math.PI - angle); Connector con1 = Util.GetConnectorClosestTo( fitting1, p1); (pipes[1].Location as LocationCurve).Curve = Line.CreateBound(con1.Origin, p1); Util.Connect(con1.Origin, fitting1, pipes[1]); con0 = Util.GetConnectorClosestTo( fitting0, pm); con1 = Util.GetConnectorClosestTo( fitting1, pm); // Connecting one fitting to the other does // not insert a pipe in between. If the // system is edited later, however, the two // fittings snap together. // //con0.ConnectTo( con1 ); // Create rolling offset pipe segment //pipe = doc.Create.NewPipe( con0.Origin, // 2014 // con1.Origin, pipe_type_standard ); pipe = Pipe.Create(doc, pipe_type_standard.Id, levelId, con0, con1); // 2015 pipe.get_Parameter(bipDiameter) .Set(diameter); // Connect rolling offset pipe segment // with elbow fittings at each end Util.Connect(con0.Origin, fitting0, pipe); Util.Connect(con1.Origin, pipe, fitting1); } else { if (_use_static_pipe_create) { // Element id arguments to Pipe.Create. ElementId idSystem; ElementId idType; ElementId idLevel; // All these values are invalid for idSystem: ElementId idSystem1 = pipe.MEPSystem.Id; ElementId idSystem2 = ElementId.InvalidElementId; ElementId idSystem3 = PipingSystem.Create( doc, pipe.MEPSystem.GetTypeId(), "Tbc") .Id; // This throws an argument exception saying // The systemTypeId is not valid piping system type. // Parameter name: systemTypeId //pipe = Pipe.Create( doc, idSystem, // idType, idLevel, q0, q1 ); // Retrieve pipe system type, e.g. // hydronic supply. PipingSystemType pipingSystemType = new FilteredElementCollector(doc) .OfClass(typeof(PipingSystemType)) .OfType <PipingSystemType>() .FirstOrDefault(st => st.SystemClassification == MEPSystemClassification .SupplyHydronic); if (null == pipingSystemType) { message = "Could not find hydronic supply piping system type"; return(Result.Failed); } idSystem = pipingSystemType.Id; Debug.Assert(pipe.get_Parameter( BuiltInParameter.RBS_PIPING_SYSTEM_TYPE_PARAM) .AsElementId().IntegerValue.Equals( idSystem.IntegerValue), "expected same piping system element id"); // Retrieve the PipeType. PipeType pipeType = new FilteredElementCollector(doc) .OfClass(typeof(PipeType)) .OfType <PipeType>() .FirstOrDefault(); if (null == pipeType) { message = "Could not find pipe type"; return(Result.Failed); } idType = pipeType.Id; Debug.Assert(pipe.get_Parameter( BuiltInParameter.ELEM_TYPE_PARAM) .AsElementId().IntegerValue.Equals( idType.IntegerValue), "expected same pipe type element id"); Debug.Assert(pipe.PipeType.Id.IntegerValue .Equals(idType.IntegerValue), "expected same pipe type element id"); // Retrieve the reference level. // pipe.LevelId is not the correct source! idLevel = pipe.get_Parameter( BuiltInParameter.RBS_START_LEVEL_PARAM) .AsElementId(); // Create the rolling offset pipe. pipe = Pipe.Create(doc, idSystem, idType, idLevel, q0, q1); } else { //pipe = doc.Create.NewPipe( q0, q1, pipe_type_standard ); // 2014 pipe = Pipe.Create(doc, systemTypeId, pipe_type_standard.Id, levelId, q0, q1); // 2015 } pipe.get_Parameter(bipDiameter) .Set(diameter); // Connect rolling offset pipe segment // directly with the neighbouring original // pipes // //Util.Connect( q0, pipes[0], pipe ); //Util.Connect( q1, pipe, pipes[1] ); // NewElbowFitting performs the following: // - select appropriate fitting family and type // - place and orient a family instance // - set its parameters appropriately // - connect it with its neighbours Connector con0 = Util.GetConnectorClosestTo( pipes[0], q0); Connector con = Util.GetConnectorClosestTo( pipe, q0); doc.Create.NewElbowFitting(con0, con); Connector con1 = Util.GetConnectorClosestTo( pipes[1], q1); con = Util.GetConnectorClosestTo( pipe, q1); doc.Create.NewElbowFitting(con, con1); } tx.Commit(); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = app.ActiveUIDocument.Document; List <Element> walls = new List <Element>(); if (!Util.GetSelectedElementsOrAll( walls, uidoc, typeof(Wall))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some wall elements." : "No wall elements found."; return(Result.Failed); } int i, n; string desc, s = null; //List<Element> neighbours; ElementArray neighbours; foreach (Wall wall in walls) { desc = Util.ElementDescription(wall); LocationCurve c = wall.Location as LocationCurve; if (null == c) { s = desc + ": No wall curve found."; } else { s = string.Empty; for (i = 0; i < 2; ++i) { neighbours = c.get_ElementsAtJoin(i); n = neighbours.Size; s += string.Format( "\n\n{0} {1} point has {2} neighbour{3}{4}", desc, (0 == i ? "start" : "end"), n, Util.PluralSuffix(n), Util.DotOrColon(n)); foreach (Wall nb in neighbours) { s += "\n " + Util.ElementDescription(nb); } } } Util.InfoMsg(s); } return(Result.Failed); }
Transform.CreateTranslation(_offset); // 2014 #endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Options opt = app.Create.NewGeometryOptions(); XyzEqualityComparer comparer = new XyzEqualityComparer(1e-6); #if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES Creator creator = new Creator(doc); Transaction t = new Transaction(doc); t.Start("Create model curve copies of top face edges"); #endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES IList <Face> topFaces = new List <Face>(); int n; int nWalls = 0; //foreach( Element e in uidoc.Selection.Elements ) // 2014 foreach (ElementId id in uidoc.Selection.GetElementIds()) // 2015 { Element e = doc.GetElement(id); Wall wall = e as Wall; if (null == wall) { Debug.Print("Skipped " + Util.ElementDescription(e)); continue; } // Get the side faces IList <Reference> sideFaces = HostObjectUtils.GetSideFaces(wall, ShellLayerType.Exterior); // Access the first side face Element e2 = doc.GetElement(sideFaces[0]); Debug.Assert(e2.Id.Equals(e.Id), "expected side face element to be the wall itself"); Face face = e2.GetGeometryObjectFromReference( sideFaces[0]) as Face; if (null == face) { Debug.Print("No side face found for " + Util.ElementDescription(e)); continue; } // When there are opening such as doors or // windows in the wall, we need to find the // outer loop. // For one possible approach to extract the // outermost loop, please refer to // http://thebuildingcoder.typepad.com/blog/2008/12/2d-polygon-areas-and-outer-loop.html // Determine the outer loop of the side face // by finding the polygon with the largest area XYZ normal; double area, dist, maxArea = 0; EdgeArray outerLoop = null; foreach (EdgeArray ea in face.EdgeLoops) { if (CmdWallProfileArea.GetPolygonPlane( ea.GetPolygon(), out normal, out dist, out area) && Math.Abs(area) > Math.Abs(maxArea)) { maxArea = area; outerLoop = ea; } } n = 0; #if GET_FACES_FROM_OUTER_LOOP // With the outermost loop, calculate the top faces foreach (Edge edge in outerLoop) { // For each edge, get the neighbouring // face and check its normal for (int i = 0; i < 2; ++i) { PlanarFace pf = edge.get_Face(i) as PlanarFace; if (null == pf) { Debug.Print("Skipped non-planar face on " + Util.ElementDescription(e)); continue; } if (Util.PointsUpwards(pf.Normal, 0.9)) { if (topFaces.Contains(pf)) { Debug.Print("Duplicate face on " + Util.ElementDescription(e)); } else { topFaces.Add(pf); ++n; } } } } #endif // GET_FACES_FROM_OUTER_LOOP List <XYZ> sideVertices = outerLoop.GetPolygon(); // Go over all the faces of the wall and // determine which ones fulfill the following // two criteria: (i) planar face pointing // upwards, and (ii) neighbour of the side // face outer loop. Solid solid = wall.get_Geometry(opt) .OfType <Solid>() .First <Solid>(sol => null != sol); foreach (Face f in solid.Faces) { if (IsTopFace(f)) { IList <XYZ> faceVertices = f.Triangulate().Vertices; //if( sideVertices.Exists( v // => faceVertices.Contains<XYZ>( v, comparer ) ) ) //{ // topFaces.Add( f ); // ++n; //} foreach (XYZ v in faceVertices) { if (sideVertices.Contains <XYZ>( v, comparer)) { topFaces.Add(f); ++n; #if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES // Display face for debugging purposes foreach (EdgeArray ea in f.EdgeLoops) { IEnumerable <Curve> curves = ea.Cast <Edge>() .Select <Edge, Curve>( x => x.AsCurve()); foreach (Curve curve in curves) { //creator.CreateModelCurve( curve.get_Transformed( _t ) ); // 2013 creator.CreateModelCurve(curve.CreateTransformed(_t)); // 2014 } } #endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES break; } } } } Debug.Print(string.Format( "{0} top face{1} found on {2} ({3})", n, Util.PluralSuffix(n), Util.ElementDescription(e)), nWalls++); } #if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES t.Commit(); #endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES string s = string.Format( "{0} wall{1} successfully processed", nWalls, Util.PluralSuffix(nWalls)); n = topFaces.Count; TaskDialog.Show("Wall Top Faces", string.Format( "{0} with {1} top face{2}.", s, n, Util.PluralSuffix(n))); return(Result.Succeeded); }
/// <summary> /// Useless non-functional attempt to remove all /// DWF links from the model and return /// the total number of deleted elements. /// This does not work! Instead, use /// RemoveDwfLinkUsingExternalFileUtils. /// </summary> int RemoveDwfLinkUsingDelete(Document doc) { int nDeleted = 0; FilteredElementCollector col = new FilteredElementCollector(doc) .WhereElementIsNotElementType(); List <ElementId> ids = new List <ElementId>(); int pinned = 0; foreach (Element e in col) { if (ElementCategoryContainsDwf(e)) { Debug.Print(Util.ElementDescription(e)); pinned += (e.Pinned ? 1 : 0); ids.Add(e.Id); } } ICollection <ElementId> idsDeleted = null; Transaction t; int n = ids.Count; int unpinned = 0; if (0 < n) { if (0 < pinned) { using (t = new Transaction(doc)) { t.Start( "Unpin non-ElementType '.dwf' elements"); unpinned = Unpin(ids, doc); t.Commit(); } } using (t = new Transaction(doc)) { t.Start( "Delete non-ElementType '.dwf' elements"); idsDeleted = doc.Delete(ids); t.Commit(); } } int m = (null == idsDeleted) ? 0 : idsDeleted.Count; Debug.Print(string.Format( "Selected {0} non-ElementType element{1}, " + "{2} pinned, {3} unpinned, " + "{4} successfully deleted.", n, Util.PluralSuffix(n), pinned, unpinned, m)); nDeleted += m; col = new FilteredElementCollector(doc) .WhereElementIsElementType(); ids.Clear(); pinned = 0; foreach (Element e in col) { if (ElementCategoryContainsDwf(e)) { Debug.Print(Util.ElementDescription(e)); pinned += (e.Pinned ? 1 : 0); ids.Add(e.Id); } } n = ids.Count; if (0 < n) { if (0 < pinned) { using (t = new Transaction(doc)) { t.Start( "Unpin element type '.dwf' elements"); unpinned = Unpin(ids, doc); t.Commit(); } } using (t = new Transaction(doc)) { t.Start("Delete element type '.dwf' elements"); idsDeleted = doc.Delete(ids); t.Commit(); } } m = (null == idsDeleted) ? 0 : idsDeleted.Count; Debug.Print(string.Format( "Selected {0} element type{1}, " + "{2} pinned, {3} unpinned, " + "{4} successfully deleted.", n, Util.PluralSuffix(n), pinned, unpinned, m)); nDeleted += m; return(nDeleted); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { if (null == _hWndRevit) { //Process[] processes // = Process.GetProcessesByName( "Revit" ); //if( 0 < processes.Length ) //{ // IntPtr h = processes[0].MainWindowHandle; // _hWndRevit = new WindowHandle( h ); //} Process process = Process.GetCurrentProcess(); IntPtr h = process.MainWindowHandle; _hWndRevit = new WindowHandle(h); } UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; using (CmdWindowHandleForm f = new CmdWindowHandleForm()) { f.Show(_hWndRevit); bool go = true; while (go) { //SelElementSet ss = sel.Elements; // 2014 //int n = ss.Size; ICollection <ElementId> ids = sel.GetElementIds(); // 2015 int n = ids.Count; string s = string.Format( "{0} element{1} selected{2}", n, Util.PluralSuffix(n), ((0 == n) ? ";\n" + _prompt : ":")); foreach (ElementId id in ids) { s += "\n"; s += Util.ElementDescription( doc.GetElement(id)); } f.LabelText = s; #if _2010 sel.StatusbarTip = _prompt; go = sel.PickOne(); #endif // _2010 Reference r = uidoc.Selection.PickObject( ObjectType.Element, _prompt); go = null != r; Debug.Print("go = " + go.ToString()); } } return(Result.Failed); }
Result Flatten( Document doc, ElementId viewId) { FilteredElementCollector col = new FilteredElementCollector(doc, viewId) .WhereElementIsNotElementType(); Options geometryOptions = new Options(); using (Transaction tx = new Transaction(doc)) { if (tx.Start("Convert elements to DirectShapes") == TransactionStatus.Started) { foreach (Element e in col) { GeometryElement gelt = e.get_Geometry( geometryOptions); if (null != gelt) { string appDataGUID = e.Id.ToString(); // Currently create direct shape // replacement element in the original // document – no API to properly transfer // graphic styles to a new document. // A possible enhancement: make a copy // of the current project and operate // on the copy. DirectShape ds = DirectShape.CreateElement(doc, e.Category.Id, _direct_shape_appGUID, appDataGUID); try { ds.SetShape( new List <GeometryObject>(gelt)); // Delete original element doc.Delete(e.Id); } catch (Autodesk.Revit.Exceptions .ArgumentException ex) { Debug.Print( "Failed to replace {0}; exception {1} {2}", Util.ElementDescription(e), ex.GetType().FullName, ex.Message); } } } tx.Commit(); } } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; ICollection <ElementId> ids = sel.GetElementIds(); Options opt = app.Application.Create.NewGeometryOptions(); Material mat; string msg = string.Empty; int i, n; foreach (ElementId id in ids) { Element e = doc.GetElement(id); // For 0310_ensure_material.htm: if (e is FamilyInstance) { mat = GetMaterial(doc, e as FamilyInstance); Util.InfoMsg( "Family instance element material: " + (null == mat ? "<null>" : mat.Name)); } GeometryElement geo = e.get_Geometry(opt); // If you are not interested in duplicate // materials, you can define a class that // overloads the Add method to only insert // a new entry if its value is not already // present in the list, instead of using // the standard List<> class: List <string> materials = GetMaterials(doc, geo); msg += "\n" + Util.ElementDescription(e); n = materials.Count; if (0 == n) { msg += " has no materials."; } else { i = 0; msg += string.Format( " has {0} material{1}:", n, Util.PluralSuffix(n)); foreach (string s in materials) { msg += string.Format( "\n {0} {1}", i++, s); } } } if (0 == msg.Length) { msg = "Please select some elements."; } Util.InfoMsg(msg); return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; // Retrieve selected floors, or all floors, if nothing is selected: List <Element> floors = new List <Element>(); if (!Util.GetSelectedElementsOrAll( floors, uidoc, typeof(Floor))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some floor elements." : "No floor elements found."; return(Result.Failed); } // Determine top face of each selected floor: int nNullFaces = 0; List <Face> topFaces = new List <Face>(); Options opt = app.Application.Create.NewGeometryOptions(); foreach (Floor floor in floors) { GeometryElement geo = floor.get_Geometry(opt); //GeometryObjectArray objects = geo.Objects; // 2012 foreach (GeometryObject obj in geo) { Solid solid = obj as Solid; if (solid != null) { PlanarFace f = GetTopFace(solid); if (null == f) { Debug.WriteLine( Util.ElementDescription(floor) + " has no top face."); ++nNullFaces; } topFaces.Add(f); } } } using (Transaction t = new Transaction(doc)) { t.Start("Create Model Lines and Floor"); // Create new floors from the top faces found. // Before creating the new floor, we would obviously // apply whatever modifications are required to the // new floor profile: Autodesk.Revit.Creation.Application creApp = app.Application.Create; Autodesk.Revit.Creation.Document creDoc = doc.Create; int i = 0; int n = topFaces.Count - nNullFaces; Debug.Print( "{0} top face{1} found.", n, Util.PluralSuffix(n)); foreach (Face f in topFaces) { Floor floor = floors[i++] as Floor; if (null != f) { EdgeArrayArray eaa = f.EdgeLoops; CurveArray profile; #region Attempt to include inner loops #if ATTEMPT_TO_INCLUDE_INNER_LOOPS bool use_original_loops = true; if (use_original_loops) { profile = Convert(eaa); } else #endif // ATTEMPT_TO_INCLUDE_INNER_LOOPS #endregion // Attempt to include inner loops { profile = new CurveArray(); // Only use first edge array, // the outer boundary loop, // skip the further items // representing holes: EdgeArray ea = eaa.get_Item(0); foreach (Edge e in ea) { IList <XYZ> pts = e.Tessellate(); int m = pts.Count; XYZ p = pts[0]; XYZ q = pts[m - 1]; Line line = Line.CreateBound(p, q); profile.Append(line); } } //Level level = floor.Level; // 2013 Level level = doc.GetElement(floor.LevelId) as Level; // 2014 // In this case we have a valid floor type given. // In general, not that NewFloor will only accept // floor types whose IsFoundationSlab predicate // is false. floor = creDoc.NewFloor(profile, floor.FloorType, level, true); XYZ v = new XYZ(5, 5, 0); //doc.Move( floor, v ); // 2011 ElementTransformUtils.MoveElement(doc, floor.Id, v); // 2012 } } t.Commit(); } return(Result.Succeeded); }
void DetermineAdjacentElementLengthsAndWallAreas( Room room) { Document doc = room.Document; // 'Autodesk.Revit.DB.Architecture.Room.Boundary' is obsolete: // use GetBoundarySegments(SpatialElementBoundaryOptions) instead. //BoundarySegmentArrayArray boundaries = room.Boundary; // 2011 IList <IList <BoundarySegment> > boundaries = room.GetBoundarySegments( new SpatialElementBoundaryOptions()); // 2012 // a room may have a null boundary property: int n = 0; if (null != boundaries) { //n = boundaries.Size; // 2011 n = boundaries.Count; // 2012 } Debug.Print( "{0} has {1} boundar{2}{3}", Util.ElementDescription(room), n, Util.PluralSuffixY(n), Util.DotOrColon(n)); if (0 < n) { int iBoundary = 0, iSegment; //foreach( BoundarySegmentArray b in boundaries ) // 2011 foreach (IList <BoundarySegment> b in boundaries) // 2012 { ++iBoundary; iSegment = 0; foreach (BoundarySegment s in b) { ++iSegment; //Element neighbour = s.Element; // 2015 Element neighbour = doc.GetElement(s.ElementId); // 2016 //Curve curve = s.Curve; // 2015 Curve curve = s.GetCurve(); // 2016 double length = curve.Length; Debug.Print( " Neighbour {0}:{1} {2} has {3}" + " feet adjacent to room.", iBoundary, iSegment, Util.ElementDescription(neighbour), Util.RealString(length)); if (neighbour is Wall) { Wall wall = neighbour as Wall; Parameter p = wall.get_Parameter( BuiltInParameter.HOST_AREA_COMPUTED); double area = p.AsDouble(); LocationCurve lc = wall.Location as LocationCurve; double wallLength = lc.Curve.Length; //Level bottomLevel = wall.Level; // 2013 Level bottomLevel = doc.GetElement(wall.LevelId) as Level; // 2014 double bottomElevation = bottomLevel.Elevation; double topElevation = bottomElevation; p = wall.get_Parameter( BuiltInParameter.WALL_HEIGHT_TYPE); if (null != p) { ElementId id = p.AsElementId(); Level topLevel = doc.GetElement(id) as Level; topElevation = topLevel.Elevation; } double height = topElevation - bottomElevation; Debug.Print( " This wall has a total length," + " height and area of {0} feet," + " {1} feet and {2} square feet.", Util.RealString(wallLength), Util.RealString(height), Util.RealString(area)); } } } } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; FilteredElementCollector col = new FilteredElementCollector(doc) .WhereElementIsNotElementType(); List <ElementId> ids = new List <ElementId>(); foreach (Element e in col) { if (ElementNameMayIndicateImageFileReference(e)) { Debug.Print(Util.ElementDescription(e)); ids.Add(e.Id); } } ICollection <ElementId> idsDeleted = null; Transaction t; int n = ids.Count; if (0 < n) { using (t = new Transaction(doc)) { t.Start("Delete non-ElementType '.jpg' elements"); idsDeleted = doc.Delete(ids); t.Commit(); } } int m = (null == idsDeleted) ? 0 : idsDeleted.Count; Debug.Print(string.Format( "Selected {0} non-ElementType element{1}, " + "{2} successfully deleted.", n, Util.PluralSuffix(n), m)); col = new FilteredElementCollector(doc) .WhereElementIsElementType(); ids.Clear(); foreach (Element e in col) { if (ElementNameMayIndicateImageFileReference(e)) { Debug.Print(Util.ElementDescription(e)); ids.Add(e.Id); } } n = ids.Count; if (0 < n) { using (t = new Transaction(doc)) { t.Start("Delete element type '.jpg' elements"); idsDeleted = doc.Delete(ids); t.Commit(); } } m = (null == idsDeleted) ? 0 : idsDeleted.Count; Debug.Print(string.Format( "Selected {0} element type{1}, " + "{2} successfully deleted.", n, Util.PluralSuffix(n), m)); return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; FilteredElementCollector sheets = new FilteredElementCollector(doc); sheets.OfClass(typeof(ViewSheet)); // map with key = sheet element id and // value = list of viewport element ids: Dictionary <ElementId, List <ElementId> > mapSheetToViewport = new Dictionary <ElementId, List <ElementId> >(); // map with key = viewport element id and // value = sheet element id: Dictionary <ElementId, ElementId> mapViewportToSheet = new Dictionary <ElementId, ElementId>(); foreach (ViewSheet sheet in sheets) { //int n = sheet.Views.Size; // 2014 ISet <ElementId> viewIds = sheet.GetAllPlacedViews(); // 2015 int n = viewIds.Count; Debug.Print( "Sheet {0} contains {1} view{2}: ", Util.ElementDescription(sheet), n, Util.PluralSuffix(n)); ElementId idSheet = sheet.Id; int i = 0; foreach (ElementId id in viewIds) { View v = doc.GetElement(id) as View; BoundingBoxXYZ bb; bb = v.get_BoundingBox(doc.ActiveView); Debug.Assert(null == bb, "expected null view bounding box"); bb = v.get_BoundingBox(sheet); Debug.Assert(null == bb, "expected null view bounding box"); Element viewport = GetViewport(sheet, v); // null if not in active view: bb = viewport.get_BoundingBox(doc.ActiveView); BoundingBoxUV outline = v.Outline; Debug.WriteLine(string.Format( " {0} {1} bb {2} outline {3}", ++i, Util.ElementDescription(v), (null == bb ? "<null>" : Util.BoundingBoxString(bb)), Util.BoundingBoxString(outline))); if (!mapSheetToViewport.ContainsKey(idSheet)) { mapSheetToViewport.Add(idSheet, new List <ElementId>()); } mapSheetToViewport[idSheet].Add(v.Id); Debug.Assert( !mapViewportToSheet.ContainsKey(v.Id), "expected viewport to be contained" + " in only one single sheet"); mapViewportToSheet.Add(v.Id, idSheet); } } return(Result.Cancelled); }