public static IList<Element> OfCategory(Category category) { var catFilter = new ElementCategoryFilter(category.InternalCategory.Id); var fec = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument); var instances = fec.WherePasses(catFilter) .WhereElementIsNotElementType() .ToElementIds() .Select(id => ElementSelector.ByElementId(id.IntegerValue)) .ToList(); return instances; }
public Result OnStartup(UIControlledApplication a) { //Create Ribbon Panel add the UI button on start up RibbonPanel alignViewsPanel = ribbonPanel(a); //Register location updater with Revit. LocationUpdater updater = new LocationUpdater(a.ActiveAddInId); UpdaterRegistry.RegisterUpdater(updater, true); ElementCategoryFilter viewPortFilter = new ElementCategoryFilter(BuiltInCategory.OST_Viewports); ElementCategoryFilter viewFilter = new ElementCategoryFilter(BuiltInCategory.OST_Views); LogicalOrFilter filter = new LogicalOrFilter(viewPortFilter, viewFilter); //Parameter to send to the trigger. ElementClassFilter viewPort = new ElementClassFilter(typeof(Viewport)); ElementId viewPortNumberId = new ElementId(BuiltInParameter.VIEWPORT_DETAIL_NUMBER); //Set trigger UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), viewPort, Element.GetChangeTypeParameter(viewPortNumberId)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); //add buttons to ribbon addVRCommandButtons(alignViewsPanel); pushButton_Setting(alignViewsPanel); return Result.Succeeded; }
/// <summary> /// Adds 1 to the mark of every column in the document /// </summary> /// <param name="commandData">the revit command data</param> /// <param name="message">a message to return</param> /// <param name="elements">Elements to display in a failed message dialog</param> /// <returns>Suceeded, Failed or Cancelled</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //we want the 'database' document, which represents the Revit Model itself. Document dbDoc = commandData.Application.ActiveUIDocument.Document; //Use a FilteredElementCollector to get all the columns in the model. FilteredElementCollector collector = new FilteredElementCollector(dbDoc); //for this, we use a Category Filter which finds all elements in the Column category ElementCategoryFilter columnFilter = new ElementCategoryFilter(BuiltInCategory.OST_Columns); //structural columns have a different category ElementCategoryFilter structuralColumnFilter =new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns); //to get elements that match either of these categories, we us a logical 'Or' filter. LogicalOrFilter orFilter = new LogicalOrFilter(columnFilter, structuralColumnFilter); //you can then get these elements as a list. //we also specify WhereElementIsNotElementType() so that we don't get FamilySymbols IList<Element> allColumns = collector.WherePasses(orFilter).WhereElementIsNotElementType().ToElements(); string results = "Updated Marks For : " + Environment.NewLine; //loop through this list and update the mark foreach (Element element in allColumns) { UpdateMark(element); results += element.Id + Environment.NewLine; } TaskDialog.Show("Updated Elements", results); return Result.Succeeded; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; m_doc = app.ActiveUIDocument.Document; // filter for family instance and (door or window): ElementClassFilter fFamInstClass = new ElementClassFilter( typeof( FamilyInstance ) ); ElementCategoryFilter fDoorCat = new ElementCategoryFilter( BuiltInCategory.OST_Doors ); ElementCategoryFilter fWindowCat = new ElementCategoryFilter( BuiltInCategory.OST_Windows ); LogicalOrFilter fCat = new LogicalOrFilter( fDoorCat, fWindowCat ); LogicalAndFilter f = new LogicalAndFilter( fCat, fFamInstClass ); FilteredElementCollector openings = new FilteredElementCollector( m_doc ); openings.WherePasses( f ); // map with key = host element id and // value = list of hosted element ids: Dictionary<ElementId, List<ElementId>> ids = GetElementIds( openings ); DumpHostedElements( ids ); m_doc = null; return Result.Succeeded; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; Application app = uiapp.Application; // Register updater to react to view creation if (_updater == null) { _updater = new ElevationWatcherUpdater( app.ActiveAddInId); UpdaterRegistry.RegisterUpdater(_updater); ElementCategoryFilter f = new ElementCategoryFilter( BuiltInCategory.OST_Views); UpdaterRegistry.AddTrigger( _updater.GetUpdaterId(), f, Element.GetChangeTypeElementAddition()); } else { UpdaterRegistry.UnregisterUpdater(_updater.GetUpdaterId()); _updater = null; } return Result.Succeeded; }
public Result OnStartup(UIControlledApplication application) { ThisApp = this; var elementCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_GenericAnnotation); _updaterModified = new UpdaterModified(application.ActiveAddInId); if (!UpdaterRegistry.IsUpdaterRegistered(_updaterModified.GetUpdaterId())) { UpdaterRegistry.RegisterUpdater(_updaterModified); UpdaterRegistry.AddTrigger(_updaterModified.GetUpdaterId(), elementCategoryFilter, Element.GetChangeTypeAny()); } _updaterAdded = new UpdaterAdded(application.ActiveAddInId); if (!UpdaterRegistry.IsUpdaterRegistered(_updaterAdded.GetUpdaterId())) { UpdaterRegistry.RegisterUpdater(_updaterAdded); UpdaterRegistry.AddTrigger(_updaterAdded.GetUpdaterId(), elementCategoryFilter, Element.GetChangeTypeElementAddition()); } _paneId = new DockablePaneId(Guid.NewGuid()); _handler = new RequestHandler(); _exEvent = ExternalEvent.Create(_handler); _sheetNoteModel = new ViewModel(); _mainPage = new MainPage { Resources = {["ViewModel"] = _sheetNoteModel } }; application.RegisterDockablePane(_paneId, "Sheet Note Manager", (IDockablePaneProvider)_mainPage); application.ControlledApplication.DocumentClosed += new EventHandler<DocumentClosedEventArgs>(OnDocumentClosed); application.ControlledApplication.DocumentOpened += new EventHandler<DocumentOpenedEventArgs>(OnDocumentOpened); return Result.Succeeded; }
private static void ExtractObjects() { ElementFilter ductFilter = new ElementCategoryFilter(BuiltInCategory.OST_DuctCurves); ElementFilter faminsFilter = new ElementClassFilter(typeof(MEPCurve)); FilteredElementCollector ductCollector = new FilteredElementCollector(_doc); ductCollector.WherePasses(ductFilter).WherePasses(faminsFilter); foreach (MEPCurve duct in ductCollector) _ducts.Add(duct); }
private static void ExtractObjects() { List<ElementId> materials = null; Material material = null; ElementFilter WallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementFilter NonStruWallFilter = new StructuralWallUsageFilter(StructuralWallUsage.NonBearing); ElementFilter WallClassFilter = new ElementClassFilter(typeof(Wall)); FilteredElementCollector GypWalls = new FilteredElementCollector(_doc); GypWalls.WherePasses(WallFilter).WherePasses(NonStruWallFilter); int[] count1 = new int[2]; //0:Gyp, 1:wallpaper, 2:ceramic foreach (Wall wall in GypWalls) { materials = wall.GetMaterialIds(false).ToList(); foreach (ElementId eleId in materials) { material = _doc.GetElement(eleId) as Material; if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Gypsum]) ++count1[0]; else if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.WallPaper]) ++count1[1]; else if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Ceramic]) ++count1[2]; } //assert: count1[i] is non-negative if (count1[0] == 0) continue; if (count1[1] == 0 && count1[2] == 0) _GypWalls.Add(new RichWall(wall,FinishType.None)); else if(count1[2] == 0) //assert: count1[1] != 0 { if (count1[1] == 1) _GypWalls.Add(new RichWall(wall,FinishType.OneWallpaper)); else if (count1[1] == 2) _GypWalls.Add(new RichWall(wall,FinishType.TwoWallpaper)); } else if(count1[1] == 0) //assert: count1[2] != 0 { if (count1[2] == 1) _GypWalls.Add(new RichWall(wall,FinishType.OneCeramic)); else if (count1[2] == 2) _GypWalls.Add(new RichWall(wall,FinishType.TwoCeramic)); } else _abandonWriter.WriteAbandonment(wall, AbandonmentTable.TooManyFinishes); } if (_addiInfo.requiredComp[(byte)PGComponents.WallFinish]) { int count2 = 0; FilteredElementCollector GeneticWalls = new FilteredElementCollector(_doc); GeneticWalls.WherePasses(WallFilter).WherePasses(WallClassFilter); foreach (Wall wall in GeneticWalls) { materials = wall.GetMaterialIds(false).ToList(); foreach (ElementId eleId in materials) { material = _doc.GetElement(eleId) as Material; if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Wood] || material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Marble]) ++count2; } if (count2 == 1) _GeneticWalls.Add(new RichWall(wall,FinishType.OneWood)); else if (count2 == 2) _GeneticWalls.Add(new RichWall(wall,FinishType.TwoWood)); else if (2 <= count2) _abandonWriter.WriteAbandonment(wall, AbandonmentTable.TooManyFinishes); } } }
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; ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); IList <Element> elems = new FilteredElementCollector(doc).WherePasses(filter).WhereElementIsNotElementType().ToElements(); MessageBox.Show($"{elems.Count}"); return(Result.Succeeded); }
private void GetAllViewsOnSheet(Document doc, out List <Viewport> vpListvpList) { vpListvpList = new List <Viewport>(); ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Viewports); FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id); IList <Element> allViews = collector.WherePasses(filter).ToElements(); foreach (Element e in allViews) { Viewport vp = e as Viewport; vpListvpList.Add(vp); //Parameter p = vp.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER); } }
public FilteredElementCollector GetElementsByCategory(params BuiltInCategory[] categorys) { if (categorys.Length > 0) { ElementFilter elementFilter = new ElementCategoryFilter(categorys[0]); for (int i = 1; i < categorys.Length; i++) { BuiltInCategory builtInCategory = categorys[i]; elementFilter = new LogicalOrFilter(elementFilter, new ElementCategoryFilter(builtInCategory)); } return(new FilteredElementCollector(APIObjectList.ActiveDocument).WherePasses(elementFilter)); } throw new System.ArgumentException("please specify at least one BuiltInCategory", "categorys"); }
/// <summary> /// initialize list of column, beam and brace's type; /// initialize list of level /// </summary> private void Initialize() { Application app = m_commandData.Application.Application; Document doc = m_commandData.Application.ActiveUIDocument.Document; FilteredElementCollector collector1 = new FilteredElementCollector(doc); IList <Autodesk.Revit.DB.Element> a1 = collector1.OfClass(typeof(Level)).ToElements(); foreach (Level lev in a1) { m_levels.Add(lev.Elevation, lev); } a1.Clear(); Categories categories = doc.Settings.Categories; BuiltInCategory bipColumn = BuiltInCategory.OST_StructuralColumns; BuiltInCategory bipFraming = BuiltInCategory.OST_StructuralFraming; Autodesk.Revit.DB.ElementId idColumn = categories.get_Item(bipColumn).Id; Autodesk.Revit.DB.ElementId idFraming = categories.get_Item(bipFraming).Id; ElementCategoryFilter filterColumn = new ElementCategoryFilter(bipColumn); ElementCategoryFilter filterFraming = new ElementCategoryFilter(bipFraming); LogicalOrFilter orFilter = new LogicalOrFilter(filterColumn, filterFraming); ElementClassFilter filterSymbol = new ElementClassFilter(typeof(FamilySymbol)); LogicalAndFilter andFilter = new LogicalAndFilter(orFilter, filterSymbol); // // without filtering for the structural categories, // our sample project was returning over 500 family symbols; // adding the category filters reduced this number to 40: // FilteredElementCollector collector2 = new FilteredElementCollector(doc); IList <Element> a2 = collector2.WherePasses(andFilter).ToElements(); foreach (FamilySymbol symbol in a2) { Autodesk.Revit.DB.ElementId categoryId = symbol.Category.Id; if (idFraming.Equals(categoryId)) { m_beambracesSymbolsMgr.AddSymbol(symbol); } else if (idColumn.Equals(categoryId)) { m_columnSymbolsMgr.AddSymbol(symbol); } } }
private void GetWallElement(Document doc) { ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter wallCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); LogicalAndFilter wallFilter = new LogicalAndFilter(familyInstanceFilter, wallCategoryFilter); FilteredElementCollector collector = new FilteredElementCollector(doc); IList <Element> walls = collector.WherePasses(wallFilter).ToElements(); foreach (Element ele in walls) { Wall wall = ele as Wall; TaskDialog.Show("wall 特性", wall.WallType.Name.ToString()); } }
/// <summary> /// run this sample now /// </summary> public void Run() { try { // filtrate the windows from the element set. ElementClassFilter filter1 = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter filter2 = new ElementCategoryFilter(BuiltInCategory.OST_Windows); LogicalAndFilter andFilter = new LogicalAndFilter(filter1, filter2); FilteredElementCollector collector = new FilteredElementCollector(m_doc); ICollection <Element> arrayFamily = collector.WherePasses(andFilter).ToElements(); // filtrate the Symbol from the element set to modify the window's type. ElementClassFilter filter3 = new ElementClassFilter(typeof(FamilySymbol)); ElementCategoryFilter filter4 = new ElementCategoryFilter(BuiltInCategory.OST_Windows); LogicalAndFilter andFilter1 = new LogicalAndFilter(filter3, filter4); collector = new FilteredElementCollector(m_doc); ICollection <Element> found = collector.WherePasses(andFilter1).ToElements(); ElementArray arraySymbol = new ElementArray(); foreach (Element ee in found) { if (ee.Name == "36\" x 72\"") { arraySymbol.Insert(ee, 0); break; } } MessageBox.Show("Replace 16\" x 24\" to 36\" x 72\".", "FindAndReplaceWinType"); // matching and replacing int replacenum = 0; foreach (Element ee in arrayFamily) { FamilyInstance windows = ee as FamilyInstance; if (0 == windows.Symbol.Name.CompareTo("16\" x 24\"")) { windows.Symbol = arraySymbol.get_Item(0) as FamilySymbol; replacenum++; } } // Show the number of windows modified. MessageBox.Show("Revit has completed its search and has made " + replacenum + " modifications.", "FindAndReplaceWinType"); } catch (Exception ee) { MessageBox.Show(ee.Message); } }
private void materialSelector_Load(object sender, EventArgs e) { FilteredElementCollector collector = new FilteredElementCollector(this.doc); ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Materials); //材料篩選器的用法和類別篩選器大致相同,並且,因為材料是不可見的,所以不做Selection的前置動作 IList <Element> matList = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); foreach (Element ele in matList) //取得所有材料之後將它塞進下拉式選單之中 { comboBox1.Items.Add(ele.Id + "\t" + ele.Name + "\t" + ele.Category.Name); //但是記得在Id及Name之間要加上適當的分隔符號,因為Name是給人看的,Id是給電腦用的, //稍後我們要再用Split()字串處理函式把Id拆出來 } }
/// <summary> /// Get list elements from active view /// </summary> /// <param name="doc"></param> /// <param name="listBuiltInCategories"></param> /// <returns></returns> public IList <Element> AllElneweActiveView(Document doc, List <BuiltInCategory> listBuiltInCategories) { List <Element> listElements = new List <Element>(); foreach (BuiltInCategory category in listBuiltInCategories) { ElementCategoryFilter elementCategoryFilter = new ElementCategoryFilter(category); FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc, doc.ActiveView.Id); IList <Element> list = filteredElementCollector.WherePasses(elementCategoryFilter) .WhereElementIsNotElementType().ToElements(); listElements.AddRange(list); } return(listElements); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { DataTable dt = new DataTable("familyInstance"); dt.Columns.Add("实例名称", typeof(String)); dt.Columns.Add("选定参数值", typeof(String)); Document Revit_Doc = commandData.Application.ActiveUIDocument.Document; //获取文件中所有元素 FilteredElementCollector all_Elements = new FilteredElementCollector(Revit_Doc); //建立族类型过滤器(其中FamilySymbol可做替换) ElementClassFilter class_Filter = new ElementClassFilter(typeof(FamilyInstance)); //建立类别过滤器(其中OST_Lights可做替换,例如OST_StackedWalls) ElementCategoryFilter cat_Filter = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalFixtures); all_Elements = all_Elements.WherePasses(class_Filter).WherePasses(cat_Filter); FamilyInstance fi = null; List <FamilyInstance> filteredList = new List <FamilyInstance>(); var filteresd = from e in all_Elements //where e.Name.Substring(0, 3) == "IBS" where e.Name != null select e as FamilyInstance; filteredList = filteresd.ToList <FamilyInstance>(); //for (int ii =0; ii<filteredList.Count() ;ii++) //{ // dt.Rows.Add(); // dt.Rows[ii]["实例名称"] = filteredList[ii].Name; // Parameter para = filteredList[ii].LookupParameter("长度"); // if (para != null) // { // string parav = para.AsValueString(); // dt.Rows[ii]["选定参数值"] = parav; // } //} RevitFamilyManagerFormSTC RevitFamilyManagerFormSTC = new RevitFamilyManagerFormSTC(); //RevitFamilyManagerFormSTC.fidt = dt; RevitFamilyManagerFormSTC.filteredList = filteredList; RevitFamilyManagerFormSTC.ShowDialog(); return(Result.Succeeded); }
public static List <global::Revit.Elements.Element> DependentElementsOfCategory(global::Revit.Elements.Element element, global::Revit.Elements.Category category) { Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; //obtain the builtin category from the id BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString()); //the filter to use Autodesk.Revit.DB.ElementFilter elemFilter = new ElementCategoryFilter(myCatEnum); //dependent element ids IList <ElementId> elemIds = element.InternalElement.GetDependentElements(elemFilter); //get the elements List <global::Revit.Elements.Element> elems = new List <global::Revit.Elements.Element>(elemIds.Select(e => doc.GetElement(new ElementId(e.IntegerValue)).ToDSType(true))); return(elems); }
private static void ExtractObjects() { FilteredElementCollector Walls = new FilteredElementCollector(_doc); ElementFilter WallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementFilter NonStruWallFilter = new StructuralWallUsageFilter(StructuralWallUsage.NonBearing); Walls.WherePasses(WallFilter).WherePasses(NonStruWallFilter); foreach (Wall wall in Walls) { if (wall.WallType.Kind == WallKind.Curtain) { _CurtainWalls.Add(wall); } } }
/// <summary> /// Finds all windows in the active document. /// </summary> /// <returns>An enumerable containing all windows.</returns> protected IEnumerable<FamilyInstance> CollectWindows() { // Windows are family instances whose category is correctly set. ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter windowCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_Windows); LogicalAndFilter andFilter = new LogicalAndFilter(familyInstanceFilter, windowCategoryFilter); FilteredElementCollector collector = new FilteredElementCollector(Document); ICollection<Element> elementsToProcess = collector.WherePasses(andFilter).ToElements(); // Convert to IEnumerable of FamilyInstance using LINQ IEnumerable<FamilyInstance> windows = from window in elementsToProcess.Cast<FamilyInstance>() select window; return windows; }
public static System.Collections.Generic.List <Element> GetElements(bool isElementType, params Category[] categorys) { if (categorys.Length > 0) { ElementFilter elementFilter = new ElementCategoryFilter(categorys[0].Id); for (int i = 1; i < categorys.Length; i++) { elementFilter = new LogicalOrFilter(elementFilter, new ElementCategoryFilter(categorys[i].Id)); } elementFilter = new LogicalAndFilter(elementFilter, new ElementIsElementTypeFilter(!isElementType)); FilteredElementCollector source = new FilteredElementCollector(APIObjectList.ActiveDocument).WherePasses(elementFilter); return(source.ToList <Element>()); } throw new System.ArgumentException("please specify at least one BuiltInCategory", "categorys"); }
private static void ExtractObjects() { FilteredElementCollector Walls = new FilteredElementCollector(_doc); ElementFilter WallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementFilter NonStruWallFilter = new StructuralWallUsageFilter(StructuralWallUsage.NonBearing); Walls.WherePasses(WallFilter).WherePasses(NonStruWallFilter); foreach (Wall wall in Walls) { if (wall.Name.Contains("Storefront") || wall.Name.Contains("店面")) { _Storefronts.Add(wall); } } }
public void SetData(Document doc) { ElementCategoryFilter elementCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_Floors); FilteredElementCollector collectors = new FilteredElementCollector(doc); IList <Element> elementLists = collectors.WherePasses(elementCategoryFilter).WhereElementIsNotElementType().ToElements(); if (!string.IsNullOrEmpty(m_sqliteFilePath)) { ReadDataFromDB(m_sqliteFilePath); } foreach (var item in elementLists) { SetParameters(item); } }
/// <summary> /// Finds all windows in the active document. /// </summary> /// <returns>An enumerable containing all windows.</returns> protected IEnumerable <FamilyInstance> CollectWindows() { // Windows are family instances whose category is correctly set. ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter windowCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_Windows); LogicalAndFilter andFilter = new LogicalAndFilter(familyInstanceFilter, windowCategoryFilter); FilteredElementCollector collector = new FilteredElementCollector(Document); ICollection <Element> elementsToProcess = collector.WherePasses(andFilter).ToElements(); // Convert to IEnumerable of FamilyInstance using LINQ IEnumerable <FamilyInstance> windows = from window in elementsToProcess.Cast <FamilyInstance>() select window; return(windows); }
public Result RunRemotely(Document document) { FilteredElementCollector collector = new FilteredElementCollector(document); ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns); TextWriter writer = new StreamWriter(@"C:\ColumnOutput.txt", true); writer.WriteLine("Column IDs"); foreach (Element e in collector.WherePasses(filter)) { writer.WriteLine(e.Name + " " + e.Id); } writer.WriteLine("Written: " + DateTime.Now); writer.Close(); return Result.Succeeded; }
public FormSelectElements(Document doc, UIApplication uiapp) { InitializeComponent(); this.uiapp = uiapp; this.doc = doc; FilteredElementCollector assemblies = new FilteredElementCollector(doc).OfClass(typeof(AssemblyInstance)); listView1.View = System.Windows.Forms.View.Details; ElementClassFilter familyinstance = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter framingfilter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming); FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id); framing = collector.WherePasses(framingfilter).WhereElementIsNotElementType().ToElements().ToList(); listView2.View = System.Windows.Forms.View.Details; foreach (var ass in assemblies) { ListViewItem item = new ListViewItem(); AssemblyInstance assinstance = doc.GetElement(ass.Id) as AssemblyInstance; if (assinstance != null) { listassemblies.Add(assinstance); item.SubItems.Add(assinstance.AssemblyTypeName); } listView1.Items.Add(item); } foreach (var fra in framing) { ListViewItem item = new ListViewItem(); if (fra != null) { try { Parameter controlmark = fra.LookupParameter("CONTROL_MARK"); listcontrolmark.Add(fra); item.SubItems.Add(controlmark.AsString()); Parameter controlnumber = fra.LookupParameter("CONTROL_NUMBER"); item.SubItems.Add(controlnumber.AsString()); } catch { } string name = fra.Name; item.SubItems.Add(name); } listView2.Items.Add(item); } }
public bool RefreshTriggers(Document doc, ProjectUpdater pUpdater) { bool refreshed = false; try { UpdaterRegistry.RemoveDocumentTriggers(updaterId, doc); ElementFilter catFilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); FilteredElementCollector collector = new FilteredElementCollector(doc); List <FamilyInstance> doorInstances = collector.WherePasses(catFilter).WhereElementIsNotElementType().Cast <FamilyInstance>().ToList(); collector = new FilteredElementCollector(doc); List <Family> doorFamilies = collector.OfClass(typeof(Family)).Cast <Family>().ToList(); bool existParam = FindClearanceParameter(doorInstances, doorFamilies); if (existParam) { if (pullParameters.Count > 0) { foreach (Parameter param in pullParameters) { UpdaterRegistry.AddTrigger(updaterId, doc, catFilter, Element.GetChangeTypeParameter(param)); } } if (pushParameters.Count > 0) { foreach (Parameter param in pushParameters) { UpdaterRegistry.AddTrigger(updaterId, doc, catFilter, Element.GetChangeTypeParameter(param)); } } if (stateCAParameters.Count > 0) { UpdaterRegistry.AddTrigger(updaterId, doc, catFilter, Element.GetChangeTypeElementAddition()); foreach (Parameter param in stateCAParameters) { UpdaterRegistry.AddTrigger(updaterId, doc, catFilter, Element.GetChangeTypeParameter(param)); } } } } catch (Exception ex) { string message = ex.Message; LogUtil.AppendLog("DoorUpdater-RefreshTriggers:" + ex.Message); } return(refreshed); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Topography); FilteredElementCollector collector = new FilteredElementCollector(doc); IList <Element> topoSurf = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); TopographySurface topo = topoSurf[0] as TopographySurface; try { GeometryElement elementGeometry = topo.get_Geometry(new Options()); TaskDialog.Show("Here", elementGeometry.LongCount().ToString()); int count = 0; foreach (GeometryObject obj in elementGeometry) { if (obj is Mesh) { Mesh topoMesh = obj as Mesh; count += topoMesh.NumTriangles; } else if (obj is Solid) { Solid sol = obj as Solid; foreach (Face face in sol.Faces) { Mesh meshFace = face.Triangulate(0.7); } } } TaskDialog.Show("There", count.ToString()); return(Result.Succeeded); } catch (Exception e) { TaskDialog.Show("There", e.Message); return(Result.Cancelled); } }
public void TestFilter() { Document doc = this.ActiveUIDocument.Document; UIDocument uidoc = this.ActiveUIDocument; // get the familyInstance we want ElementClassFilter f1 = new ElementClassFilter( typeof(FamilyInstance)); ElementCategoryFilter f2 // Can get all family symbol = new ElementCategoryFilter( BuiltInCategory.OST_Columns); LogicalAndFilter f3 = new LogicalAndFilter(f1, f2); ElementClassFilter f4 = new ElementClassFilter( typeof(Floor)); FilteredElementCollector collector = new FilteredElementCollector(doc); collector = GetStructuralElements(doc); List <Element> columns = collector .WherePasses(f1) .ToElements() as List <Element>; // List<Element> columnInstances // = ( from instances in columns // where instances is FamilyInstance // select instances ).ToList<Element>(); int n = columns.Count; var query = from element in collector //where element.Category.Name == "結構柱" where element.Category.Name == "結構構架" select element; // Cast found elements to family instances, // this cast to FamilyInstance is safe because ElementClassFilter for FamilyInstance was used List <FamilyInstance> familyInstances = query.Cast <FamilyInstance>().ToList <FamilyInstance>(); }
public Result OnStartup(UIControlledApplication app) { app.CreateRibbonTab("LOD Manager"); RibbonPanel panel = app.CreateRibbonPanel("LOD Manager", "LOD Parameters"); AddRibbonItems(panel); LODupdater lODupdater = new LODupdater(app.get_ActiveAddInId()); UpdaterRegistry.RegisterUpdater(lODupdater, true); ElementFilter val = new ElementCategoryFilter(-2005000, true); UpdaterRegistry.AddTrigger(lODupdater.GetUpdaterId(), val, Element.GetChangeTypeElementAddition()); app.get_ControlledApplication().add_DocumentOpened((EventHandler <DocumentOpenedEventArgs>)lodApp_DocumentOpened); app.get_ControlledApplication().add_DocumentClosing((EventHandler <DocumentClosingEventArgs>)lodApp_DocumentClosing); return(0); }
public Result RunRemotely(Document document) { FilteredElementCollector collector = new FilteredElementCollector(document); ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns); TextWriter writer = new StreamWriter(@"C:\ColumnOutput.txt", true); writer.WriteLine("Column IDs"); foreach (Element e in collector.WherePasses(filter)) { writer.WriteLine(e.Name + " " + e.Id); } writer.WriteLine("Written: " + DateTime.Now); writer.Close(); return(Result.Succeeded); }
private void docOpen(object sender, DocumentOpenedEventArgs e) { Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application; UIApplication uiApp = new UIApplication(app); Document doc = uiApp.ActiveUIDocument.Document; FilteredElementCollector collector = new FilteredElementCollector(doc); collector.WherePasses(new ElementClassFilter(typeof(FamilyInstance))); var sphereElements = from element in collector where element.Name == "sphere" select element; if (sphereElements.Count() == 0) { TaskDialog.Show("Error", "Sphere family must be loaded"); return; } FamilyInstance sphere = sphereElements.Cast <FamilyInstance>().First <FamilyInstance>(); FilteredElementCollector viewCollector = new FilteredElementCollector(doc); ICollection <Element> views = viewCollector.OfClass(typeof(View3D)).ToElements(); var viewElements = from element in viewCollector where element.Name == "AVF" select element; if (viewElements.Count() == 0) { TaskDialog.Show("Error", "A 3D view named 'AVF' must exist to run this application."); return; } View view = viewElements.Cast <View>().First <View>(); SpatialFieldUpdater updater = new SpatialFieldUpdater(uiApp.ActiveAddInId, sphere.Id, view.Id); if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) { UpdaterRegistry.RegisterUpdater(updater); } ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); IList <ElementFilter> filterList = new List <ElementFilter>(); filterList.Add(wallFilter); filterList.Add(familyFilter); filterList.Add(massFilter); LogicalOrFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeGeometry()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); }
public void filterChanger() { Document CurDoc = this.ActiveUIDocument.Document; ElementCategoryFilter GMFilt = new ElementCategoryFilter(BuiltInCategory.OST_GenericModel); string GmMat = ""; foreach (Element G in new FilteredElementCollector(CurDoc) .OfClass(typeof(FamilyInstance)) .WherePasses(GMFilt)) { FamilyInstance gfi = G as FamilyInstance; FamilySymbol gs = gfi.Symbol; GmMat += gs.StructuralMaterialType; } TaskDialog.Show("elements", GmMat); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; FilteredElementCollector collector = new FilteredElementCollector(doc); ElementCategoryFilter filter1 = new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns); ElementCategoryFilter filter2 = new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming); LogicalOrFilter filter = new LogicalOrFilter(filter1, filter2); IList <Element> beamList = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); StringBuilder result = new StringBuilder(); foreach (Element ele in beamList) { result.AppendLine(ele.Category.Name + "\t" + ele.Name + "\t" + ele.Id); } MessageBox.Show(result.ToString()); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; FilteredElementCollector collector = new FilteredElementCollector(doc); ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Materials); IList <Element> matList = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); string result = ""; foreach (Element ele in matList) { result += ele.Category.Name + "\t" + ele.Name + "\t" + ele.Id + "\n"; } MessageBox.Show(result); return(Result.Succeeded); }
/// <summary> /// Delete all elements that cut out of target elements, to allow for calculation of gross material quantities. /// </summary> private void DeleteAllCuttingElements() { IList <ElementFilter> filterList = new List <ElementFilter>(); FilteredElementCollector collector = new FilteredElementCollector(m_doc); // (Type == FamilyInstance && (Category == Door || Category == Window) || Type == Opening ElementClassFilter filterFamilyInstance = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter filterWindowCategory = new ElementCategoryFilter(BuiltInCategory.OST_Windows); ElementCategoryFilter filterDoorCategory = new ElementCategoryFilter(BuiltInCategory.OST_Doors); LogicalOrFilter filterDoorOrWindowCategory = new LogicalOrFilter(filterWindowCategory, filterDoorCategory); LogicalAndFilter filterDoorWindowInstance = new LogicalAndFilter(filterDoorOrWindowCategory, filterFamilyInstance); ElementClassFilter filterOpening = new ElementClassFilter(typeof(Opening)); LogicalOrFilter filterCuttingElements = new LogicalOrFilter(filterOpening, filterDoorWindowInstance); ICollection <Element> cuttingElementsList = collector.WherePasses(filterCuttingElements).ToElements(); foreach (Element e in cuttingElementsList) { // Doors in curtain grid systems cannot be deleted. This doesn't actually affect the calculations because // material quantities are not extracted for curtain systems. if (e.Category != null) { if (e.Category.BuiltInCategory == BuiltInCategory.OST_Doors) { FamilyInstance door = e as FamilyInstance; Wall host = door.Host as Wall; if (host.CurtainGrid != null) { continue; } } ICollection <ElementId> deletedElements = m_doc.Delete(e.Id); // Log failed deletion attempts to the output. (These may be other situations where deletion is not possible but // the failure doesn't really affect the results. if (deletedElements == null || deletedElements.Count < 1) { m_warningsForGrossQuantityCalculations.Add( String.Format(" The tool was unable to delete the {0} named {2} (id {1})", e.GetType().Name, e.Id, e.Name)); } } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; FilteredElementCollector roomCollector = new FilteredElementCollector(doc); ElementCategoryFilter roomFilter = new ElementCategoryFilter(BuiltInCategory.OST_Rooms); List <Element> rooms = roomCollector.WherePasses(roomFilter).WhereElementIsNotElementType().ToElements().ToList(); room_count = rooms.Count; string newFileName = @"C:\Users\8014\Desktop\BIM模型檢核.csv"; StringBuilder sb = new StringBuilder(); sb.AppendLine("1.房間種類高度檢核:"); sb.AppendLine("規範:居室及浴室房間高度不可小於2.1m "); sb.AppendLine("房間樓層\t房間名稱(種類)\t目前房高(cm)\t規範最低房高(cm)\t是否通過規範"); form_list1.Add(new string[] { "1.房間種類高度檢核:" }); form_list1.Add(new string[] { "規範:居室及浴室房間高度不可小於2.1m " }); foreach (Element elem in rooms) { Room room = elem as Room; string level_name = room.get_Parameter(BuiltInParameter.LEVEL_NAME).AsString(); string room_name = room.get_Parameter(BuiltInParameter.ROOM_NAME).AsString(); double room_height = Convert.ToDouble(room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsValueString()) / 10; sb.AppendLine(level_name + "\t" + room_name + "\t" + room_height.ToString() + "\t" + regulation_height.ToString() + "\t" + (room_height >= regulation_height).ToString()); string[] row = new string[] { room.Id.ToString(), room_name, room_height.ToString(), regulation_height.ToString(), "無", (room_height >= regulation_height).ToString() }; form_list1.Add(row); } sb.AppendLine(); sb.AppendLine(); File.AppendAllText(newFileName, sb.ToString(), Encoding.Unicode); form_list1.Add(new string[] {}); form_list1.Add(new string[] {}); return(Result.Succeeded); }
/// <summary> /// 射线法获取房间吊顶高度,单位foot /// </summary> /// <param name="room"></param> /// <param name="pointInRoom">房间内一点,请确保该点在房间下楼板和上天花板内,否则计算值错误</param> /// <param name="currDocument">当前文件,射线法需要用到</param> /// <returns></returns> public static double GetRoomCeilingHeightByRay(this Room room, XYZ pointInRoom, Document currDocument) { if (room.Document.IsLinked && currDocument == null) { throw new InvalidOperationException("如果房间是链接文件中的房间,必须传递当前文件currDocument参数"); } ElementFilter elementFilter; ReferenceIntersector referenceIntersector; //向上找天花板 elementFilter = new ElementCategoryFilter(BuiltInCategory.OST_Ceilings); //射线法需要的三维视图,很关键,找不好就会找不到想要的结果 FilteredElementCollector collector = new FilteredElementCollector(currDocument); //待改进 var view3D = collector.OfClass(typeof(View3D)).Cast <View3D>().FirstOrDefault <View3D>(v3 => !(v3.IsTemplate)); referenceIntersector = RevitExtensions.GetReferenceIntersector( view3D, room.Document.IsLinked, findReferenceTarget: FindReferenceTarget.All, targetElementIds: null, elementFilter: elementFilter); var topReference = referenceIntersector.FindNearest(pointInRoom, XYZ.BasisZ); if (topReference == null) { return(double.NaN); } //向下找楼板 elementFilter = new ElementCategoryFilter(BuiltInCategory.OST_Floors); referenceIntersector.SetFilter(elementFilter); var bottomReference = referenceIntersector.FindNearest(pointInRoom, XYZ.BasisZ.Negate()); if (bottomReference == null) { return(double.NaN); } return(topReference.Proximity + bottomReference.Proximity); }
public static IList <Element> OfCategory(Category category) { if (category == null) { return(null); } var catFilter = new ElementCategoryFilter(category.InternalCategory.Id); var fec = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument); var instances = fec.WherePasses(catFilter) .WhereElementIsNotElementType() .ToElementIds() .Select(id => ElementSelector.ByElementId(id.IntegerValue)) .ToList(); return(instances); }
// get reference to the project basepoint public static Element GetProjectBasepoint() { ElementCategoryFilter sitElementCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_ProjectBasePoint); FilteredElementCollector collector = new FilteredElementCollector(AppRibbon.Doc); IList <Element> siteElements = collector.WherePasses(sitElementCategoryFilter).ToElements(); if (siteElements.Count != 1) { return(null); } return(siteElements[0]); }
private static void ExtractObjects() { FilteredElementCollector Walls = new FilteredElementCollector(_doc); ElementFilter WallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); IList<ElementFilter> StruWallFilterList = new List<ElementFilter>(); StruWallFilterList.Add(new StructuralWallUsageFilter(StructuralWallUsage.Bearing)); StruWallFilterList.Add(new StructuralWallUsageFilter(StructuralWallUsage.Shear)); StruWallFilterList.Add(new StructuralWallUsageFilter(StructuralWallUsage.Combined)); LogicalOrFilter logicOrFilter = new LogicalOrFilter(StruWallFilterList); Walls.WherePasses(WallFilter).WherePasses(logicOrFilter); foreach (Wall wall in Walls) { Material material = _doc.GetElement (wall.WallType.get_Parameter(BuiltInParameter.STRUCTURAL_MATERIAL_PARAM).AsElementId()) as Material; if (material == null) continue; if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Masonry]) { _masonryWalls.Add(wall); } } }
private void docOpen(object sender, DocumentOpenedEventArgs e) { Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application; UIApplication uiApp = new UIApplication(app); Document doc = uiApp.ActiveUIDocument.Document; FilteredElementCollector collector = new FilteredElementCollector(doc); collector.WherePasses(new ElementClassFilter(typeof(FamilyInstance))); var sphereElements = from element in collector where element.Name == "sphere" select element; if (sphereElements.Count() == 0) { TaskDialog.Show("Error", "Sphere family must be loaded"); return; } FamilyInstance sphere = sphereElements.Cast<FamilyInstance>().First<FamilyInstance>(); FilteredElementCollector viewCollector = new FilteredElementCollector(doc); ICollection<Element> views = viewCollector.OfClass(typeof(View3D)).ToElements(); var viewElements = from element in viewCollector where element.Name == "AVF" select element; if (viewElements.Count() == 0) { TaskDialog.Show("Error", "A 3D view named 'AVF' must exist to run this application."); return; } View view = viewElements.Cast<View>().First<View>(); SpatialFieldUpdater updater = new SpatialFieldUpdater(uiApp.ActiveAddInId, sphere.Id, view.Id); if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(updater); ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); IList<ElementFilter> filterList = new List<ElementFilter>(); filterList.Add(wallFilter); filterList.Add(familyFilter); filterList.Add(massFilter); LogicalOrFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeGeometry()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); }
/// <summary> /// Helper function /// Find a door or window on the given wall. /// If it does, return it. /// </summary> public FamilyInstance FindWindowDoorOnWall(Document rvtDoc, Wall aWall) { // Collect the list of windows and doors // No object relation graph. So going hard way. // List all the door instances var windowDoorCollector = new FilteredElementCollector(rvtDoc); windowDoorCollector.OfClass(typeof(FamilyInstance)); ElementCategoryFilter windowFilter = new ElementCategoryFilter(BuiltInCategory.OST_Windows); ElementCategoryFilter doorFilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); LogicalOrFilter windowDoorFilter = new LogicalOrFilter(windowFilter, doorFilter); windowDoorCollector.WherePasses(windowDoorFilter); IList<Element> windowDoorList = windowDoorCollector.ToElements(); // This is really bad in a large model! // You might have ten thousand doors and windows. // It would make sense to add a bounding box containment or intersection filter as well. // Check to see if the door or window is on the wall we got. foreach (FamilyInstance e in windowDoorList) { if (e.Host.Id.Equals(aWall.Id)) { return e; } } // If you come here, you did not find window or door on the given wall. return null; }
public override void PopulateItems() { Items.Clear(); //find all the structural framing family types in the project var collector = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument); var catFilter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming); collector.OfClass(typeof(FamilySymbol)).WherePasses(catFilter); if (collector.ToElements().Count == 0) { Items.Add(new DynamoDropDownItem(noFraming, null)); SelectedIndex = 0; return; } foreach (var e in collector.ToElements()) Items.Add(new DynamoDropDownItem(e.Name, e)); Items = Items.OrderBy(x => x.Name).ToObservableCollection<DynamoDropDownItem>(); }
private string ExportToFbx() { try { double building_width = 0; double building_length = 0; ElementCategoryFilter eleFilter;//the class varies from Autodesk.Revit.DB? y FilteredElementCollector collector;//the class varies from Autodesk.Revit.DB? y IList<Element> filteredObject;// the interface of System.Collections.Generic? y where did it state it is the interface? in .net lib string semanticInfo = "";//store all semantic information string commentParameter = "";//store the comment parameter in left column revit //get ground objects //read semantic information from revit file //for floor eleFilter = new ElementCategoryFilter(BuiltInCategory.OST_Floors);// get all floor objects in revit project collector = new FilteredElementCollector(uidoc.Document);//the same way to get objects in revit filteredObject = collector.WherePasses(eleFilter).WhereElementIsNotElementType().ToElements();// the same way to get objects in revit //we create filter instance and all objects instance. then we pass filter into all objects to get filteredbojects. foreach (Element e in filteredObject)//go throught each item/objects in revit model { commentParameter = GetParameterInformation(e.Parameters, uidoc.Document, "Comments"); string level = GetParameterInformation(e.Parameters, uidoc.Document, "Level"); if (level.ToLower() == "level 0") { CalculateArea(e.Parameters, uidoc.Document, ref building_width, ref building_length); if (building_width > 100 || building_length > 100) { TaskDialog.Show("Error", "W: " + building_width + ", L: " + building_length + ". Size is too big for our application."); return "Size Error."; } } if (commentParameter == "emergency") semanticInfo += e.Id + "-emergency,"+level+"\n";// explain this please. put id and emergency into the whole semantic information list with different line. else semanticInfo += e.Id + "-ground," + level + "\n"; } //for stairs eleFilter = new ElementCategoryFilter(BuiltInCategory.OST_Stairs); collector = new FilteredElementCollector(uidoc.Document); filteredObject = collector.WherePasses(eleFilter).WhereElementIsNotElementType().ToElements(); foreach (Element e in filteredObject) { semanticInfo += e.Id + "-stair\n"; } //get obstacle objects///for walls eleFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls);//I get all walls collector = new FilteredElementCollector(uidoc.Document); filteredObject = collector.WherePasses(eleFilter).WhereElementIsNotElementType().ToElements(); foreach (Element e in filteredObject)//I loop each wall. I want to check the COMMENT property of each wall { /*//this block is used to get Comment property in revit commentParameter = "";//this parameter store Comment property value foreach (Parameter para in e.Parameters)//loop each property { try { commentParameter = GetParameterInformation(para, uidoc.Document).ToLower(); if (commentParameter == "wood") break; } catch (Exception ex) { //cannot get info, we know it and we don't need to write it } } //if it is wood, we set wood to the semantic file, otherwise it is obstable (brick) if (commentParameter == "wood") semanticInfo += e.Id + "-wood\n"; //else if (status == "somethingelse") //content += e.Id + "-somethingelse\n"; else*/ semanticInfo += e.Id + "-obstacle\n"; } //for doors eleFilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); collector = new FilteredElementCollector(uidoc.Document); filteredObject = collector.WherePasses(eleFilter).WhereElementIsNotElementType().ToElements(); foreach (Element e in filteredObject) { commentParameter = GetParameterInformation(e.Parameters, uidoc.Document, "Comments"); if (commentParameter == "closed") semanticInfo += e.Id + "-obstacle\n"; else if (commentParameter == "opened") semanticInfo += e.Id + "-openeddoor\n"; else semanticInfo += e.Id + "-openeddoor\n"; // else mean the default status??? yes SetParameter(e.Parameters, "Comments", "test"); } string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); CreateTempFolder(path + "\\revitfbx\\"); //output //System.IO.Directory.CreateDirectory("revitfbx"); System.IO.File.Delete(path + "\\revitfbx\\building.fbx"); System.IO.File.Delete(path + "\\revitfbx\\semantic.txt"); //we write new fbx //////////////////////////// ViewSet views = new ViewSet(); views.Insert(uidoc.ActiveView); FBXExportOptions exportoption = new FBXExportOptions(); //here, revit forces us to use a folder. I forgot that. so we have to use a folder. uidoc.Document.Export(path + "\\revitfbx", "building.fbx", views, exportoption);//generate fbx file ///////////////////////////// //we write new semantic Utility.WriteFile(path + "\\revitfbx\\semantic.txt", semanticInfo, false); //send semantic and 3d fbx model to PHP server NameValueCollection paras = new NameValueCollection(); paras.Add("sid", selectedSid); paras.Add("act", "ClientSendModelFile"); string web = client.UploadFileEx(path + "\\revitfbx\\building.fbx", AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH, "building", null, paras); if (web.Trim() != "") return "Unknown error"; paras = new NameValueCollection(); paras.Add("sid", selectedSid); paras.Add("act", "ClientSendSemanticFile"); client.UploadFileEx(path + "\\revitfbx\\semantic.txt", AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH, "semantic", null, paras); return "done"; } /////////////////////////// catch (Exception ex) { TaskDialog.Show("Error", ex.Message); return ex.Message; } }
private static ElementFilter GetVisibleElementFilter() { var filterList = new List<ElementFilter>(); var fContinuousRail = new ElementClassFilter(typeof(ContinuousRail)); var fRailing = new ElementClassFilter(typeof(Railing)); var fStairs = new ElementClassFilter(typeof(Stairs)); var fStairsLanding = new ElementClassFilter(typeof(StairsLanding)); var fTopographySurface = new ElementClassFilter(typeof(TopographySurface)); var fAssemblyInstance = new ElementClassFilter(typeof(AssemblyInstance)); var fBaseArray = new ElementClassFilter(typeof(BaseArray)); var fBeamSystem = new ElementClassFilter(typeof(BeamSystem)); var fBoundaryConditions = new ElementClassFilter(typeof(BoundaryConditions)); var fConnectorElement = new ElementClassFilter(typeof(ConnectorElement)); var fControl = new ElementClassFilter(typeof(Control)); var fCurveElement = new ElementClassFilter(typeof(CurveElement)); var fDividedSurface = new ElementClassFilter(typeof(DividedSurface)); var fCableTrayConduitRunBase = new ElementClassFilter(typeof(CableTrayConduitRunBase)); var fHostObject = new ElementClassFilter(typeof(HostObject)); var fInstance = new ElementClassFilter(typeof(Instance)); var fmepSystem = new ElementClassFilter(typeof(MEPSystem)); var fModelText = new ElementClassFilter(typeof(ModelText)); var fOpening = new ElementClassFilter(typeof(Opening)); var fPart = new ElementClassFilter(typeof(Part)); var fPartMaker = new ElementClassFilter(typeof(PartMaker)); var fReferencePlane = new ElementClassFilter(typeof(ReferencePlane)); var fReferencePoint = new ElementClassFilter(typeof(ReferencePoint)); var fSpatialElement = new ElementClassFilter(typeof(SpatialElement)); var fAreaReinforcement = new ElementClassFilter(typeof(AreaReinforcement)); var fHub = new ElementClassFilter(typeof(Hub)); var fPathReinforcement = new ElementClassFilter(typeof(PathReinforcement)); var fRebar = new ElementClassFilter(typeof(Rebar)); var fTruss = new ElementClassFilter(typeof(Truss)); filterList.Add(fContinuousRail); filterList.Add(fRailing); filterList.Add(fStairs); filterList.Add(fStairsLanding); filterList.Add(fTopographySurface); filterList.Add(fAssemblyInstance); filterList.Add(fBaseArray); filterList.Add(fBeamSystem); filterList.Add(fBoundaryConditions); filterList.Add(fConnectorElement); filterList.Add(fControl); filterList.Add(fCurveElement); filterList.Add(fDividedSurface); filterList.Add(fCableTrayConduitRunBase); filterList.Add(fHostObject); filterList.Add(fInstance); filterList.Add(fmepSystem); filterList.Add(fModelText); filterList.Add(fOpening); filterList.Add(fPart); filterList.Add(fPartMaker); filterList.Add(fReferencePlane); filterList.Add(fReferencePoint); filterList.Add(fAreaReinforcement); filterList.Add(fHub); filterList.Add(fPathReinforcement); filterList.Add(fRebar); filterList.Add(fTruss); filterList.Add(fSpatialElement); var cRvtLinks = new ElementCategoryFilter(BuiltInCategory.OST_RvtLinks); filterList.Add(cRvtLinks); var filters = new LogicalOrFilter(filterList); return filters; }
public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { try { //TAF load english_us TODO add a way to localize res = Resource_en_us.ResourceManager; // Create new ribbon panel RibbonPanel ribbonPanel = application.CreateRibbonPanel(res.GetString("App_Description")); //MDJ todo - move hard-coded strings out to resource files //Create a push button in the ribbon panel PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo", res.GetString("App_Name"), m_AssemblyName, "Dynamo.Applications.DynamoRevit")) as PushButton; System.Drawing.Bitmap dynamoIcon = Dynamo.Applications.Properties.Resources.Nodes_32_32; BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( dynamoIcon.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; // MDJ = element level events and dyanmic model update // MDJ 6-8-12 trying to get new dynamo to watch for user created ref points and re-run definition when they are moved IdlePromise.RegisterIdle(application); updater = new DynamoUpdater(application.ActiveAddInId, application.ControlledApplication); if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(updater); ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter refPointFilter = new ElementCategoryFilter(BuiltInCategory.OST_ReferencePoints); ElementClassFilter modelCurveFilter = new ElementClassFilter(typeof(CurveElement)); ElementClassFilter sunFilter = new ElementClassFilter(typeof(SunAndShadowSettings)); IList<ElementFilter> filterList = new List<ElementFilter>(); filterList.Add(SpatialFieldFilter); filterList.Add(familyFilter); filterList.Add(modelCurveFilter); filterList.Add(refPointFilter); filterList.Add(sunFilter); ElementFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeAny()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); return Result.Succeeded; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); return Result.Failed; } }
public void Execute(UpdaterData data) { Document doc = data.GetDocument(); Autodesk.Revit.ApplicationServices.Application app = doc.Application; View view = doc.get_Element(viewID) as View; FamilyInstance sphere = doc.get_Element(sphereID) as FamilyInstance; LocationPoint sphereLP = sphere.Location as LocationPoint; XYZ sphereXYZ = sphereLP.Point; SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view); if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3); // Three measurement values for each point sfm.Clear(); FilteredElementCollector collector = new FilteredElementCollector(doc,view.Id); ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); LogicalOrFilter filter = new LogicalOrFilter(wallFilter, massFilter); ICollection<Element> elements = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); foreach (Face face in GetFaces(elements)) { int idx = sfm.AddSpatialFieldPrimitive(face.Reference); List<double> doubleList = new List<double>(); IList<UV> uvPts = new List<UV>(); IList<ValueAtPoint> valList = new List<ValueAtPoint>(); BoundingBoxUV bb = face.GetBoundingBox(); for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15) { for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15) { UV uvPnt = new UV(u, v); uvPts.Add(uvPnt); XYZ faceXYZ = face.Evaluate(uvPnt); // Specify three values for each point doubleList.Add(faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10); valList.Add(new ValueAtPoint(doubleList)); doubleList.Clear(); } } FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts); FieldValues vals = new FieldValues(valList); AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("Schema 1", "Schema 1 Description"); IList<int> registeredResults = new List<int>(); registeredResults = sfm.GetRegisteredResults(); int idx1 = 0; if (registeredResults.Count == 0) { idx1 = sfm.RegisterResult(resultSchema1); } else { idx1 = registeredResults.First(); } sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1); } }
// (sic) From Dynamo legacy /// <summary> /// Utility method to create a filtered element collector which collects all elements in a view /// which Dynamo would like to view or on which Dynamo would like to operate. /// </summary> /// <returns></returns> protected static FilteredElementCollector GetVisibleElementFilter() { var fec = new FilteredElementCollector(Document); var filterList = new List<ElementFilter>(); //Autodesk.Revit.DB.Analysis.AnalysisDisplayLegend; //Autodesk.Revit.DB.Analysis.AnalysisDisplayStyle; //Autodesk.Revit.DB.Analysis.MassEnergyAnalyticalModel; //Autodesk.Revit.DB.Analysis.MassLevelData; //Autodesk.Revit.DB.Analysis.MassSurfaceData; //Autodesk.Revit.DB.Analysis.MassZone; //Autodesk.Revit.DB.Analysis.SpatialFieldManager; //Autodesk.Revit.DB.AreaScheme; //Autodesk.Revit.DB.AppearanceAssetElement; var FContinuousRail = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.ContinuousRail)); var FRailing = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.Railing)); var FStairs = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.Stairs)); var FStairsLanding = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsLanding)); //var FStairsPath = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsPath)); //var FStairsRun = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsRun)); var FTopographySurface = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.TopographySurface)); //Autodesk.Revit.DB.AreaScheme; var FAssemblyInstance = new ElementClassFilter(typeof(Autodesk.Revit.DB.AssemblyInstance)); var FBaseArray = new ElementClassFilter(typeof(Autodesk.Revit.DB.BaseArray)); //ElementClassFilter FBasePoint = new ElementClassFilter(typeof(Autodesk.Revit.DB.BasePoint)); var FBeamSystem = new ElementClassFilter(typeof(Autodesk.Revit.DB.BeamSystem)); var FBoundaryConditions = new ElementClassFilter(typeof(Autodesk.Revit.DB.BoundaryConditions)); //ElementClassFilter FCombinableElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.CombinableElement)); //Autodesk.Revit.DB..::..ComponentRepeater //Autodesk.Revit.DB..::..ComponentRepeaterSlot var FConnectorElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.ConnectorElement)); var FControl = new ElementClassFilter(typeof(Autodesk.Revit.DB.Control)); var FCurveElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.CurveElement)); //Autodesk.Revit.DB.DesignOption; //Autodesk.Revit.DB.Dimension; //Autodesk.Revit.DB..::..DisplacementElement var FDividedSurface = new ElementClassFilter(typeof(Autodesk.Revit.DB.DividedSurface)); var FCableTrayConduitRunBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.Electrical.CableTrayConduitRunBase)); //Autodesk.Revit.DB.Electrical.ElectricalDemandFactorDefinition; //Autodesk.Revit.DB.Electrical.ElectricalLoadClassification; //Autodesk.Revit.DB.Electrical.PanelScheduleSheetInstance; //Autodesk.Revit.DB.Electrical.PanelScheduleTemplate; var FElementType = new ElementClassFilter(typeof(Autodesk.Revit.DB.ElementType)); //Autodesk.Revit.DB..::..ElevationMarker //ElementClassFilter FFamilyBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.FamilyBase)); //Autodesk.Revit.DB.FilledRegion; //Autodesk.Revit.DB.FillPatternElement; //Autodesk.Revit.DB.FilterElement; //Autodesk.Revit.DB.GraphicsStyle; //Autodesk.Revit.DB.Grid; //ElementClassFilter FGroup = new ElementClassFilter(typeof(Autodesk.Revit.DB.Group)); var FHostObject = new ElementClassFilter(typeof(Autodesk.Revit.DB.HostObject)); //Autodesk.Revit.DB.IndependentTag; var FInstance = new ElementClassFilter(typeof(Autodesk.Revit.DB.Instance)); //Autodesk.Revit.DB.Level; //Autodesk.Revit.DB.LinePatternElement; //Autodesk.Revit.DB.Material; //Autodesk.Revit.DB.Mechanical.Zone; var FMEPSystem = new ElementClassFilter(typeof(Autodesk.Revit.DB.MEPSystem)); var FModelText = new ElementClassFilter(typeof(Autodesk.Revit.DB.ModelText)); //Autodesk.Revit.DB..::..MultiReferenceAnnotation var FOpening = new ElementClassFilter(typeof(Autodesk.Revit.DB.Opening)); var FPart = new ElementClassFilter(typeof(Autodesk.Revit.DB.Part)); var FPartMaker = new ElementClassFilter(typeof(Autodesk.Revit.DB.PartMaker)); //Autodesk.Revit.DB.Phase; //Autodesk.Revit.DB..::..PhaseFilter //Autodesk.Revit.DB.PrintSetting; //Autodesk.Revit.DB.ProjectInfo; //Autodesk.Revit.DB.PropertyLine; //ElementClassFilter FPropertySetElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.PropertySetElement)); //Autodesk.Revit.DB.PropertySetLibrary; var FReferencePlane = new ElementClassFilter(typeof(Autodesk.Revit.DB.ReferencePlane)); var FReferencePoint = new ElementClassFilter(typeof(Autodesk.Revit.DB.ReferencePoint)); //Autodesk.Revit.DB..::..ScheduleSheetInstance //Autodesk.Revit.DB..::..Segment //ElementClassFilter FSketchBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.SketchBase)); //ElementClassFilter FSketchPlane = new ElementClassFilter(typeof(Autodesk.Revit.DB.SketchPlane)); var FSpatialElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.SpatialElement)); //Autodesk.Revit.DB..::..SpatialElementCalculationLocation //ElementClassFilter FSpatialElementTag = new ElementClassFilter(typeof(Autodesk.Revit.DB.SpatialElementTag)); //Autodesk.Revit.DB.Structure..::..AnalyticalLink //Autodesk.Revit.DB.Structure.AnalyticalModel; var FAreaReinforcement = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.AreaReinforcement)); //Autodesk.Revit.DB.Structure..::..FabricArea //Autodesk.Revit.DB.Structure..::..FabricReinSpanSymbolControl //Autodesk.Revit.DB.Structure..::..FabricSheet var FHub = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Hub)); //Autodesk.Revit.DB.Structure.LoadBase; //Autodesk.Revit.DB.Structure.LoadCase; //Autodesk.Revit.DB.Structure.LoadCombination; //Autodesk.Revit.DB.Structure.LoadNature; //Autodesk.Revit.DB.Structure.LoadUsage; var FPathReinforcement = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.PathReinforcement)); var FRebar = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Rebar)); //Autodesk.Revit.DB.Structure..::..RebarInSystem var FTruss = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Truss)); //Autodesk.Revit.DB.SunAndShadowSettings; //Autodesk.Revit.DB.TextElement; //Autodesk.Revit.DB.View; //Autodesk.Revit.DB..::..Viewport //Autodesk.Revit.DB.ViewSheetSet; //Autodesk.Revit.DB.WorksharingDisplaySettings; filterList.Add(FContinuousRail); filterList.Add(FRailing); filterList.Add(FStairs); filterList.Add(FStairsLanding); filterList.Add(FTopographySurface); filterList.Add(FAssemblyInstance); filterList.Add(FBaseArray); filterList.Add(FBeamSystem); filterList.Add(FBoundaryConditions); filterList.Add(FConnectorElement); filterList.Add(FControl); filterList.Add(FCurveElement); filterList.Add(FDividedSurface); filterList.Add(FCableTrayConduitRunBase); filterList.Add(FHostObject); filterList.Add(FInstance); filterList.Add(FMEPSystem); filterList.Add(FModelText); filterList.Add(FOpening); filterList.Add(FPart); filterList.Add(FPartMaker); filterList.Add(FReferencePlane); filterList.Add(FReferencePoint); filterList.Add(FAreaReinforcement); filterList.Add(FHub); filterList.Add(FPathReinforcement); filterList.Add(FRebar); filterList.Add(FTruss); filterList.Add(FSpatialElement); //ElementCategoryFilter CRailings = new ElementCategoryFilter(BuiltInCategory.OST_StairsRailing); //ElementCategoryFilter CStairs = new ElementCategoryFilter(BuiltInCategory.OST_Stairs); var CRvtLinks = new ElementCategoryFilter(BuiltInCategory.OST_RvtLinks); filterList.Add(CRvtLinks); //List<ElementFilter> ignores = new List<ElementFilter>(); //ElementCategoryFilter CLightFixtureSource = new ElementCategoryFilter(BuiltInCategory.OST_LightingFixtureSource, true); //ignores.Add(CLightFixtureSource); var filters = new LogicalOrFilter(filterList); //LogicalOrFilter exclusions = new LogicalOrFilter(ignores); fec.WherePasses(filters).WhereElementIsNotElementType(); return fec; }
public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { try { // Create new ribbon panel RibbonPanel ribbonPanel = application.CreateRibbonPanel("Visual Programming"); //MDJ todo - move hard-coded strings out to resource files //Create a push button in the ribbon panel PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo", "Dynamo", m_AssemblyName, "Dynamo.Applications.DynamoRevit")) as PushButton; System.Drawing.Bitmap dynamoIcon = Dynamo.Applications.Properties.Resources.Nodes_32_32; BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( dynamoIcon.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; // MDJ = element level events and dyanmic model update // Register sfm updater with Revit //DynamoUpdater updater = new DynamoUpdater(application.ActiveAddInId); //UpdaterRegistry.RegisterUpdater(updater); //// Change Scope = any spatial field element //ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); ////ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); //// Change type = element addition //UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), SpatialFieldFilter, //Element.GetChangeTypeAny()); // Element.GetChangeTypeElementAddition() DynamoUpdater updater = new DynamoUpdater(application.ActiveAddInId);//, sphere.Id, view.Id); if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(updater); ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); IList<ElementFilter> filterList = new List<ElementFilter>(); filterList.Add(SpatialFieldFilter); filterList.Add(familyFilter); filterList.Add(massFilter); LogicalOrFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeGeometry()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); return Result.Succeeded; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return Result.Failed; } }
public override void PopulateItems() { base.PopulateItems(); Items.Clear(); //find all the structural framing family types in the project var collector = new FilteredElementCollector(dynRevitSettings.Doc.Document); var catFilter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming); collector.OfClass(typeof(FamilySymbol)).WherePasses(catFilter); foreach (var e in collector.ToElements()) Items.Add(new DynamoDropDownItem(e.Name, e)); }
public static void FilterWalls(Document document, StringBuilder sb, Repositorio rep) { sb.AppendLine("== Tratando Paredes =="); StringBuilder temp = new StringBuilder(); // Find all Wall instances in the document by using category filter ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); // Apply the filter to the elements in the active document // Use shortcut WhereElementIsNotElementType() to find wall instances only FilteredElementCollector collector = new FilteredElementCollector(document); IList<Element> walls = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); sb.AppendLine(string.Format("Paredes encontradas: {0}", walls.Count)); String prompt = string.Format("Total Walls: {0}. The walls in the current document are:\n", walls.Count); Wall wall; double total = 0d; Parameter parameter; int areaPerHour = 3; double totalTime = 0; int index = 0; double areaSquareMeters; double timePerWall; int bricksPerRootSquare = 30; int bricksPerWall = 0; int totalBricks = 0; decimal cost100Bricks = 100; decimal costBricksPerWall = 0; decimal totalBricksCost = 0; // Orcamento via Banco List<int> visitedTypes = new List<int>(); ElementId currElemId; int currType; Wall newWall; IList<Element> currElems; foreach (Element e in walls) { wall = e as Wall; // Convert areaSquareMeters = UnitUtils.ConvertFromInternalUnits(wall.GetOrderedParameters()[20].AsDouble(), DisplayUnitType.DUT_SQUARE_METERS); prompt += string.Format("Parede:{0}, Área: {1}. Tempo Necessário: {2} horas.\n", ++index, wall.GetOrderedParameters()[20].AsValueString(), totalTime); // Timer timePerWall = areaSquareMeters / areaPerHour; // Material // Total bricks equal to total area per number of bricker per wall square meters bricksPerWall = (int) Math.Ceiling(areaSquareMeters * bricksPerRootSquare); // Values costBricksPerWall = bricksPerWall * cost100Bricks / 100; // Update Totals totalTime += timePerWall; totalBricks += bricksPerWall; totalBricksCost += costBricksPerWall; currElemId = wall.GetTypeId(); currType = currElemId.IntegerValue; if(visitedTypes.Contains(currType)) { // Wall Type already visited continue; } currElems = FilterElementsByTypeId(document, currElemId); foreach(Element e2 in currElems) { newWall = e2 as Wall; // TODO - Continuar daqui } // Log temp.AppendLine(string.Format("Parede {0}: {1} (Type: {2})", index, wall.Name, wall.GetTypeId())); temp.AppendLine(string.Format("Tempo de Construção: {0} horas", timePerWall)); temp.AppendLine(string.Format("Área: {0}", wall.get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsValueString())); temp.AppendLine(string.Format("Volume: {0}", wall.get_Parameter(BuiltInParameter.HOST_VOLUME_COMPUTED).AsValueString())); temp.AppendLine(string.Format("Comprimento: {0} m", wall.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH).AsValueString())); temp.AppendLine(string.Format("Altura: {0} m", wall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM).AsValueString())); temp.AppendLine(string.Format("Tijolos Necessários: {0} unidades", bricksPerWall)); temp.AppendLine(string.Format("Custo do Tijolo: {0:C2}", costBricksPerWall)); // Calculates Materials temp.AppendLine(); } prompt = "Tempo Total de Construção das paredes: " + totalTime+"\n"+prompt; TaskDialog.Show("Revit", prompt); sb.AppendLine(string.Format("Tempo Total de Construção das Paredes: {0} horas", totalTime)); sb.AppendLine(string.Format("Total de tijolos necessários: {0} unidades", totalBricks)); sb.AppendLine(string.Format("Custo Total de tijolos: {0:C2}", totalBricksCost)); sb.AppendLine("--").AppendLine().Append(temp.ToString()); sb.AppendLine("== Fim Tratando Paredes =="); }
public static IList<Element> FilterElementsByTypeId(Document document, ElementId id) { // Find all Wall instances in the document by using category filter ElementCategoryFilter filter = new ElementCategoryFilter(id); // Apply the filter to the elements in the active document // Use shortcut WhereElementIsNotElementType() to find wall instances only FilteredElementCollector collector = new FilteredElementCollector(document); return collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); }
public static void FilterDoors(Document document) { // Create a Filter to get all the doors in the document ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter doorsCategoryfilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); LogicalAndFilter doorInstancesFilter = new LogicalAndFilter(familyInstanceFilter, doorsCategoryfilter); FilteredElementCollector collector = new FilteredElementCollector(document); ICollection<ElementId> doors = collector.WherePasses(doorInstancesFilter).ToElementIds(); String prompt = "The ids of the doors in the current document are: "; String temp = ""; Element element; foreach (ElementId id in doors) { // Get the category instance from the Category property temp = ""; element = document.GetElement(id); Category category = element.Category; BuiltInCategory enumCategory = (BuiltInCategory)category.Id.IntegerValue; //temp += Enum.GetName(typeof(BuiltInCategory), enumCategory); // Get the level object to which the element is assigned. if (element.LevelId.Equals(ElementId.InvalidElementId)) { TaskDialog.Show("Revit", "The element isn't based on a level."); } else { Level level = element.Document.GetElement(element.LevelId) as Level; // Format the prompt information(Name and elevation) temp = "The element is based on a level."; temp += "\nThe level name is: " + level.Name; temp += "\nThe level elevation is: " + level.Elevation; // Show the information to the user. //TaskDialog.Show("Revit", prompt); } prompt += "\n\t" + id.IntegerValue + "(" + temp + ")"; } // Give the user some information TaskDialog.Show("Revit", prompt); // Get settings of current document Settings documentSettings = document.Settings; // Get all categories of current document Categories groups = documentSettings.Categories; // Show the number of all the categories to the user prompt = "Number of all categories in current Revit document:" + groups.Size; // get Floor category according to OST_Floors and show its name Category floorCategory = groups.get_Item(BuiltInCategory.OST_Walls); prompt += floorCategory.Name; // Give the user some information TaskDialog.Show("Revit", prompt); // foreach (var item in uidoc.Selection.GetElementIds()) // { // if (Units.) //} //if (0 == selectedIds.Count) //{ // // If no elements selected. // TaskDialog.Show("Revit", "You haven't selected any elements."); //} //else //{ // String info = "Ids of selected elements in the document are: "; // foreach (ElementId id in selectedIds) // { // info += "\n\t" + id.IntegerValue; // } // TaskDialog.Show("Revit", info); //} }
public Result OnStartup(UIControlledApplication a) { //add the UI button on start up AddButtons(a); //Register sheet updater with Revit RenameViewUpdater updater = new RenameViewUpdater(a.ActiveAddInId); UpdaterRegistry.RegisterUpdater(updater); UpdaterRegistry.SetIsUpdaterOptional(updater.GetUpdaterId(), true); //filter by Class ElementClassFilter sheet = new ElementClassFilter(typeof(ViewSheet)); ElementClassFilter viewPort = new ElementClassFilter(typeof(Viewport)); ElementClassFilter view = new ElementClassFilter(typeof(View)); ElementCategoryFilter viewPortFilter = new ElementCategoryFilter(BuiltInCategory.OST_Viewports); ElementCategoryFilter viewFilter = new ElementCategoryFilter(BuiltInCategory.OST_Views); LogicalOrFilter filter = new LogicalOrFilter(viewPortFilter, viewFilter); //Paramter to send to the trigger ElementId sheetId = new ElementId(BuiltInParameter.SHEET_NUMBER); ElementId viewPortNumberId = new ElementId(BuiltInParameter.VIEWPORT_DETAIL_NUMBER); ElementId viewPortNameId = new ElementId(BuiltInParameter.VIEWPORT_VIEW_NAME); ElementId titleOnSheetId = new ElementId(BuiltInParameter.VIEW_DESCRIPTION); ElementId viewPortSheetNumber = new ElementId(BuiltInParameter.VIEWPORT_SHEET_NUMBER); //Set trigger to send to execute when modified UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), sheet, Element.GetChangeTypeParameter(sheetId)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), viewPort, Element.GetChangeTypeParameter(viewPortNumberId)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), view, Element.GetChangeTypeParameter(viewPortNameId)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), view, Element.GetChangeTypeParameter(titleOnSheetId)); //Set trigger to send when added UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); return Result.Succeeded; }
/// <summary> /// Get all of the egresses /// </summary> /// <returns>All egresses' set</returns> private ICollection<Element> getAllEgresses() { FilteredElementCollector collector = new FilteredElementCollector(m_doc); ElementClassFilter filterFamilyInstance = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter filterDoorCategory = new ElementCategoryFilter(BuiltInCategory.OST_Doors); LogicalAndFilter filterDoorInstance = new LogicalAndFilter(filterDoorCategory, filterFamilyInstance); return collector.WherePasses(filterDoorInstance).ToElements(); }
public Result OnStartup(UIControlledApplication application) { try { //TAF load english_us TODO add a way to localize res = Resource_en_us.ResourceManager; // Create new ribbon panel RibbonPanel ribbonPanel = application.CreateRibbonPanel(res.GetString("App_Description")); //Create a push button in the ribbon panel var pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo", res.GetString("App_Name"), m_AssemblyName, "Dynamo.Applications.DynamoRevit")) as PushButton; Bitmap dynamoIcon = Resources.logo_square_32x32; BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( dynamoIcon.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; IdlePromise.RegisterIdle(application); Updater = new DynamoUpdater(application.ActiveAddInId, application.ControlledApplication); if (!UpdaterRegistry.IsUpdaterRegistered(Updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(Updater); var SpatialFieldFilter = new ElementClassFilter(typeof (SpatialFieldManager)); var familyFilter = new ElementClassFilter(typeof (FamilyInstance)); var refPointFilter = new ElementCategoryFilter(BuiltInCategory.OST_ReferencePoints); var modelCurveFilter = new ElementClassFilter(typeof (CurveElement)); var sunFilter = new ElementClassFilter(typeof (SunAndShadowSettings)); IList<ElementFilter> filterList = new List<ElementFilter>(); filterList.Add(SpatialFieldFilter); filterList.Add(familyFilter); filterList.Add(modelCurveFilter); filterList.Add(refPointFilter); filterList.Add(sunFilter); ElementFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeAny()); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); env = new ExecutionEnvironment(); return Result.Succeeded; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return Result.Failed; } }
/// <summary> /// Set value(uuid) to Unique ID parameter /// </summary> public void SetValueToUniqueIDParameter() { ElementClassFilter beamClassFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementClassFilter slabClassFilter = new ElementClassFilter(typeof(Floor)); ElementCategoryFilter beamTypeFilter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming); ElementCategoryFilter slabTypeFilter = new ElementCategoryFilter(BuiltInCategory.OST_Floors); LogicalAndFilter beamFilter = new LogicalAndFilter(beamClassFilter,beamTypeFilter); LogicalAndFilter slabFilter = new LogicalAndFilter(slabClassFilter,slabTypeFilter); LogicalOrFilter beamandslabFilter = new LogicalOrFilter(beamFilter, slabFilter); IEnumerable<Element> elems = from elem in new FilteredElementCollector(m_revit.ActiveUIDocument.Document).WherePasses(beamandslabFilter).ToElements() let category = elem.Category where category!=null && (category.Name =="Structural Framing" || category.Name == "Floors") select elem; foreach (Element elem in elems) { // Find the parameter which is named "Unique ID" // belongs to a specifically beam or slab ParameterSet attributes = elem.Parameters; IEnumerator iter = attributes.GetEnumerator(); iter.Reset(); while (iter.MoveNext()) { Parameter attribute = iter.Current as Autodesk.Revit.DB.Parameter; Definition information = attribute.Definition; if ((null != information)&&("Unique ID" == information.Name) && (null == attribute.AsString()) ) { // The shared parameter "Unique ID" then be set to a UUID Guid uuid = Guid.NewGuid(); attribute.Set(uuid.ToString()); } } } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { try { UIApplication uiApp = commandData.Application; UIDocument uidoc = uiApp.ActiveUIDocument; Application app = uiApp.Application; Document doc = uidoc.Document; Stopwatch sw = Stopwatch.StartNew(); // f5 = f1 && f4 // = f1 && (f2 || f3) // = family instance and (door or window) #region Filters and collector definitions ElementClassFilter f1 = new ElementClassFilter( typeof( FamilyInstance ) ); ElementCategoryFilter f2 = new ElementCategoryFilter( BuiltInCategory.OST_Doors ); ElementCategoryFilter f3 = new ElementCategoryFilter( BuiltInCategory.OST_Windows ); LogicalOrFilter f4 = new LogicalOrFilter( f2, f3 ); LogicalAndFilter f5 = new LogicalAndFilter( f1, f4 ); FilteredElementCollector collector = new FilteredElementCollector( doc ); #endregion //#region Filtering with a class filter //List<Element> openingInstances = // collector.WherePasses(f5).ToElements() // as List<Element>; //#endregion //#region Filtering with an anonymous method //List<Element> openings = collector // .WherePasses(f4) // .ToElements() as List<Element>; //List<Element> openingInstances // = openings.FindAll( // e => e is FamilyInstance ); //#endregion #region Filtering with LINQ List<Element> openings = collector .WherePasses( f4 ) .ToElements() as List<Element>; List<Element> openingInstances = ( from instances in openings where instances is FamilyInstance select instances ).ToList<Element>(); #endregion int n = openingInstances.Count; sw.Stop(); Debug.WriteLine( string.Format( "Time to get {0} elements: {1}ms", n, sw.ElapsedMilliseconds ) ); return Result.Succeeded; } catch( Exception ex ) { message = ex.Message + ex.StackTrace; return Result.Failed; } }
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, ElementSet elements) { try { Document document = revit.Application.ActiveUIDocument.Document; // 创建一个类过滤器来过滤出所有的FamilyInstance类的元素。 ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance)); // 创建一个类别过滤器来过滤出所有的内建类型为OST_Doors的元素。 ElementCategoryFilter doorsCategoryfilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); // 创建一个逻辑过滤器来组合前面两个过滤器,实现过滤出所有Door元素。 LogicalAndFilter doorInstancesFilter = new LogicalAndFilter(familyInstanceFilter, doorsCategoryfilter); FilteredElementCollector collector = new FilteredElementCollector(document); ICollection<ElementId> doors = collector.WherePasses(doorInstancesFilter).ToElementIds(); String prompt = "The ids of the doors in the current document are:"; foreach (ElementId id in doors) { prompt += "\n\t" + id.IntegerValue; } TaskDialog.Show("Revit", prompt); } catch (Exception e) { message = e.Message; return Autodesk.Revit.UI.Result.Failed; } return Autodesk.Revit.UI.Result.Succeeded; }