/// <summary> /// Return the first wall found that /// uses the given wall type. /// </summary> static Wall GetFirstWallUsingType( Document doc, WallType wallType) { // built-in parameter storing this // wall's wall type element id: BuiltInParameter bip = BuiltInParameter.ELEM_TYPE_PARAM; ParameterValueProvider provider = new ParameterValueProvider( new ElementId(bip)); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); FilterRule rule = new FilterElementIdRule( provider, evaluator, wallType.Id); ElementParameterFilter filter = new ElementParameterFilter(rule); FilteredElementCollector collector = new FilteredElementCollector(doc) .OfClass(typeof(Wall)) .WherePasses(filter); return(collector.FirstElement() as Wall); }
/// <summary> /// Convert FilterRule to our custom FilterRuleBuilder which will be displayed in form controls /// </summary> /// <param name="param">Parameter to which the FilterRule is applied.</param> /// <param name="rule">FilterRule to be converted.</param> /// <returns>Custom FilterRuleBuilder data converted from FilterRule</returns> public static FilterRuleBuilder CreateFilterRuleBuilder(BuiltInParameter param, FilterRule rule) { // Maybe FilterRule is inverse rule, we need to find its inner rule(FilterValueRule) // Note that the rule may be inversed more than once. bool inverted = false; FilterRule innerRule = ReflectToInnerRule(rule, out inverted); if (innerRule is FilterStringRule) { FilterStringRule strRule = innerRule as FilterStringRule; FilterStringRuleEvaluator evaluator = strRule.GetEvaluator(); return(new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), strRule.RuleString, strRule.RuleString.ToLower() == strRule.RuleString ? false : true)); } else if (innerRule is FilterDoubleRule) { FilterDoubleRule dbRule = innerRule as FilterDoubleRule; FilterNumericRuleEvaluator evaluator = dbRule.GetEvaluator(); return(new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), dbRule.RuleValue, dbRule.Epsilon)); } else if (innerRule is FilterIntegerRule) { FilterIntegerRule intRule = innerRule as FilterIntegerRule; FilterNumericRuleEvaluator evaluator = intRule.GetEvaluator(); return(new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), intRule.RuleValue)); } else if (innerRule is FilterElementIdRule) { FilterElementIdRule idRule = innerRule as FilterElementIdRule; FilterNumericRuleEvaluator evaluator = idRule.GetEvaluator(); return(new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), idRule.RuleValue)); } // // for other rule, not supported yet throw new System.NotImplementedException("The filter rule is not recognizable and supported yet!"); }
public static ICollection <ElementId> GetTypeBICInPhase(Document doc, Type thisType, BuiltInCategory bic, Phase phase) { // http://spiderinnet.typepad.com/blog/2011/07/ // elementparameterfilter-using-filterelementidrule-to-filter-element-parameters-in-c.html // // • An ElementParameterFilter needs a filter rule, the FilterElementIdRule in this case. // • The FilterElementIdRule needs a parameter value provider (ParameterValueProvider) and // a filter rule evaluator (FilterStringRuleEvaluator), specifically the FilterNumericEquals here. // • Do not feel surprised that the FilterNumericEquals evaluator also works with the FilterElementIdRule // as the ElementId is effectively nothing more than an integer value. // • The ParameterValueProvider needs an argument of parameter, as the phase created parameter // BuiltInParameter.PHASE_CREATED in this case. // • The parameter is represented by an ElementId, which is the numeric value of the specified BuiltInParameter. // • A fast filter, ElementClassFilter, represented by its shortcut method (OfClass), is also used to // narrow down the FilteredElementCollector first. It not only speeds up the search but also makes sure only walls are returned. ParameterValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterElementIdRule rule1 = new FilterElementIdRule(provider, new FilterNumericEquals(), phase.Id); ElementParameterFilter filter1 = new ElementParameterFilter(rule1); FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(thisType); collector.OfCategory(bic); collector.WherePasses(filter1); return(collector.ToElementIds()); }
public static FilteredElementCollector WhereTypeIdEqualsTo(this FilteredElementCollector collector, ElementId value) { using (var provider = new ParameterValueProvider(new ElementId(BuiltInParameter.ELEM_TYPE_PARAM))) using (var evaluator = new FilterNumericEquals()) using (var rule = new FilterElementIdRule(provider, evaluator, value)) using (var filter = new ElementParameterFilter(rule)) return(collector.WherePasses(filter)); }
/** param name="level" the level for which the stairs should be retrieved for. * The list always consists of two elements. * The first list contains the list of stairs, that start on this level. * The second list contains the list of stairs, that end on this level. * * returns a List of all stairs that start or end at the current level. */ public List <KeyValuePair <string, List <Stairs> > > GetAllStairsFromLevel(UIDocument currentDocument, List <Stairs> allStairs, Level currentLevel) { var filteredStairs = new List <KeyValuePair <string, List <Stairs> > >(); var baseStairsOnLevel = new List <Stairs>(); var topStairsOnLevel = new List <Stairs>(); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); BuiltInParameter baseLevelParameter = BuiltInParameter.STAIRS_BASE_LEVEL_PARAM; ParameterValueProvider baseLevelProvider = new ParameterValueProvider(new ElementId(baseLevelParameter)); FilterRule baseLevelRule = new FilterElementIdRule(baseLevelProvider, evaluator, currentLevel.Id); ElementParameterFilter baseLevelFilter = new ElementParameterFilter(baseLevelRule); FilteredElementCollector baseStairsCollector = new FilteredElementCollector(currentDocument.Document).WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_Stairs); ICollection <ElementId> baseStairIds = baseStairsCollector.WherePasses(baseLevelFilter).ToElementIds(); foreach (ElementId currentBaseStairsId in baseStairIds) { if (Stairs.IsByComponent(currentDocument.Document, currentBaseStairsId)) { Stairs currentBaseStairs = currentDocument.Document.GetElement(currentBaseStairsId) as Stairs; if (!StairsListContainsElement(baseStairsOnLevel, currentBaseStairs) && !StairsListContainsElement(topStairsOnLevel, currentBaseStairs)) { baseStairsOnLevel.Add(currentBaseStairs); } } } BuiltInParameter topLevelParameter = BuiltInParameter.STAIRS_TOP_LEVEL_PARAM; ParameterValueProvider topLevelProvider = new ParameterValueProvider(new ElementId(topLevelParameter)); FilterRule topLevelRule = new FilterElementIdRule(topLevelProvider, evaluator, currentLevel.Id); ElementParameterFilter topLevelFilter = new ElementParameterFilter(topLevelRule); FilteredElementCollector topStairsCollector = new FilteredElementCollector(currentDocument.Document).WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_Stairs); ICollection <ElementId> topStairsIds = topStairsCollector.WherePasses(topLevelFilter).ToElementIds(); foreach (ElementId currentTopStairsId in topStairsIds) { if (Stairs.IsByComponent(currentDocument.Document, currentTopStairsId)) { Stairs currentTopStairs = currentDocument.Document.GetElement(currentTopStairsId) as Stairs; if (!StairsListContainsElement(baseStairsOnLevel, currentTopStairs) && !StairsListContainsElement(topStairsOnLevel, currentTopStairs)) { topStairsOnLevel.Add(currentTopStairs); } } } filteredStairs.Add(new KeyValuePair <string, List <Stairs> >(BASE_LEVEL_KEY, baseStairsOnLevel)); filteredStairs.Add(new KeyValuePair <string, List <Stairs> >(TOP_LEVEL_KEY, topStairsOnLevel)); return(filteredStairs); }
/// <summary> /// Return all elements from the given collector /// whose element id is greater than 'lastId'. /// </summary> FilteredElementCollector GetElementsAfter( FilteredElementCollector input, ElementId lastId) { BuiltInParameter bip = BuiltInParameter.ID_PARAM; ParameterValueProvider provider = new ParameterValueProvider( new ElementId(bip)); FilterNumericRuleEvaluator evaluator = new FilterNumericGreater(); FilterRule rule = new FilterElementIdRule( provider, evaluator, lastId); ElementParameterFilter filter = new ElementParameterFilter(rule); return(input.WherePasses(filter)); }
protected override void SolveInstance(IGH_DataAccess DA) { var typeIds = new List <Autodesk.Revit.DB.ElementId>(); if (!DA.GetDataList("Types", typeIds)) { return; } var inverted = false; if (!DA.GetData("Inverted", ref inverted)) { return; } var provider = new ParameterValueProvider(new ElementId(BuiltInParameter.ELEM_TYPE_PARAM)); if (typeIds.Count == 1) { var rule = new FilterElementIdRule(provider, new FilterNumericEquals(), typeIds[0]); DA.SetData("Filter", new Autodesk.Revit.DB.ElementParameterFilter(rule, inverted)); } else { if (inverted) { var rules = typeIds.Select(x => new FilterInverseRule(new FilterElementIdRule(provider, new FilterNumericEquals(), x))).ToArray(); DA.SetData("Filter", new Autodesk.Revit.DB.ElementParameterFilter(rules)); } else { var filters = typeIds.Select(x => new FilterElementIdRule(provider, new FilterNumericEquals(), x)).Select(x => new Autodesk.Revit.DB.ElementParameterFilter(x)).ToArray(); DA.SetData("Filter", new LogicalOrFilter(filters)); } } }
/// <summary> /// ElementParameterFilter 参数过滤器:找到一个房间内的所有对象 /// </summary> /// <remarks>提示: 参数过滤条件可能比其他的类型过滤条件要快,但是这要视条件而定。毕竟这是一个慢过,使用时请按照过滤标准的复杂程度而异。</remarks> public void ElementParameterFilter_FindOjbectsInSpecificRoom(ExternalCommandData commandData) { UIApplication app = commandData.Application; Document document = app.ActiveUIDocument.Document; //pick a room Selection sel = app.ActiveUIDocument.Selection; Reference ref1 = sel.PickObject(ObjectType.Element, "Please pick a room"); Room room = document.GetElement(ref1) as Room; // 定义要过滤哪个参数 ParameterValueProvider :表示Element的房间Id的参数。 ParameterValueProvider provider = new ParameterValueProvider(new ElementId(BuiltInParameter.ELEM_ROOM_ID)); // 定义过滤规则的表达式 FilterNumericRuleEvaluator 或者 FilterStringRuleEvaluator FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); // 定义要过滤的类型 FilterRule FilterElementIdRule rule = new FilterElementIdRule(provider, evaluator, room.Id); // 最终得到参数过滤器 ElementParameterFilter ElementParameterFilter filter = new ElementParameterFilter(rule); // 在什么范围内进行过滤 FilteredElementCollector collector = new FilteredElementCollector(document); // 执行过滤操作,并得到过滤后的结果 collector.WherePasses(filter); }
/// <summary> /// Retrieve all stairs on a given level. /// </summary> FilteredElementCollector GetStairsOnLevel( Document doc, Level level) { ElementId id = level.Id; BuiltInCategory bic = BuiltInCategory.OST_Stairs; FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfCategory( bic ); // explicit iteration and manual // checking of a property: List<Element> stairs = new List<Element>(); foreach( Element e in collector ) { if( e.LevelId.Equals( id ) ) { stairs.Add( e ); } } // using LINQ: IEnumerable<Element> stairsOnLevelLinq = from e in collector where e.LevelId.Equals( id ) select e; // using an anonymous method: IEnumerable<Element> stairsOnLevelAnon = collector.Where<Element>( e => e.LevelId.Equals( id ) ); // using a parameter filter: BuiltInParameter bip = BuiltInParameter.STAIRS_BASE_LEVEL_PARAM; ParameterValueProvider provider = new ParameterValueProvider( new ElementId( bip ) ); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); FilterRule rule = new FilterElementIdRule( provider, evaluator, id ); ElementParameterFilter filter = new ElementParameterFilter( rule ); return collector.WherePasses( filter ); }
protected override void SolveInstance(IGH_DataAccess DA) { var parameterId = ElementId.InvalidElementId; if (!DA.GetData("ParameterKey", ref parameterId)) { return; } DA.DisableGapLogic(); if (!TryGetParameterDefinition(Revit.ActiveDBDocument, parameterId, out var storageType, out var parameterType)) { if (parameterId.TryGetBuiltInParameter(out var builtInParameter)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Failed to found parameter '{LabelUtils.GetLabelFor(builtInParameter)}' in Revit document."); } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Failed to found parameter '{parameterId.IntegerValue}' in Revit document."); } return; } var provider = new ParameterValueProvider(parameterId); Autodesk.Revit.DB.FilterRule rule = null; if (storageType == StorageType.String) { FilterStringRuleEvaluator ruleEvaluator = null; switch (Condition) { case ConditionType.NotEquals: case ConditionType.Equals: ruleEvaluator = new FilterStringEquals(); break; case ConditionType.Greater: ruleEvaluator = new FilterStringGreater(); break; case ConditionType.GreaterOrEqual: ruleEvaluator = new FilterStringGreaterOrEqual(); break; case ConditionType.Less: ruleEvaluator = new FilterStringLess(); break; case ConditionType.LessOrEqual: ruleEvaluator = new FilterStringLessOrEqual(); break; } var goo = default(GH_String); if (DA.GetData("Value", ref goo)) { rule = new FilterStringRule(provider, ruleEvaluator, goo.Value, true); } } else { FilterNumericRuleEvaluator ruleEvaluator = null; switch (Condition) { case ConditionType.NotEquals: case ConditionType.Equals: ruleEvaluator = new FilterNumericEquals(); break; case ConditionType.Greater: ruleEvaluator = new FilterNumericGreater(); break; case ConditionType.GreaterOrEqual: ruleEvaluator = new FilterNumericGreaterOrEqual(); break; case ConditionType.Less: ruleEvaluator = new FilterNumericLess(); break; case ConditionType.LessOrEqual: ruleEvaluator = new FilterNumericLessOrEqual(); break; } switch (storageType) { case StorageType.Integer: { var goo = default(GH_Integer); if (DA.GetData("Value", ref goo)) { rule = new FilterIntegerRule(provider, ruleEvaluator, goo.Value); } } break; case StorageType.Double: { var goo = default(GH_Number); if (DA.GetData("Value", ref goo)) { if (Condition == ConditionType.Equals || Condition == ConditionType.NotEquals) { if (parameterType == ParameterType.Length || parameterType == ParameterType.Area || parameterType == ParameterType.Volume) { rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), ToHost(Revit.VertexTolerance, parameterType)); } else { rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), 1e-6); } } else { rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), 0.0); } } } break; case StorageType.ElementId: { switch (parameterType) { case (ParameterType)int.MaxValue: // Category { var value = default(Types.Category); if (DA.GetData("Value", ref value)) { rule = new FilterElementIdRule(provider, ruleEvaluator, value); } } break; case ParameterType.FamilyType: { var value = default(Types.ElementType); if (DA.GetData("Value", ref value)) { rule = new FilterElementIdRule(provider, ruleEvaluator, value); } } break; default: { var value = default(Types.Element); if (DA.GetData("Value", ref value)) { rule = new FilterElementIdRule(provider, ruleEvaluator, value); } } break; } } break; } } if (rule is object) { if (Condition == ConditionType.NotEquals) { DA.SetData("Rule", new FilterInverseRule(rule)); } else { DA.SetData("Rule", rule); } } }
/// <summary> /// A function to number Family Instances /// </summary> /// <param name="doc"></param> /// <param name="builtInCategory"></param> public static void numberFamilyInstance(Document doc, Phase phase, Boolean numeric, string separator, BuiltInCategory builtInCategory, ref int countInstances, Parameter parameter) { // Create dictionary to store window-room values Dictionary <FamilyInstance, string> instanceNumbers = new Dictionary <FamilyInstance, string>(); // Create dictionary to store number of windows in room Dictionary <string, int> instancesInRoomCount = new Dictionary <string, int>(); // Design option filter ElementDesignOptionFilter designOptionFilter = new ElementDesignOptionFilter(ElementId.InvalidElementId); // Select elements in phase ElementId idPhase = phase.Id; ParameterValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); FilterElementIdRule rule = new FilterElementIdRule(provider, evaluator, idPhase); ElementParameterFilter paraFilter = new ElementParameterFilter(rule); // Collect all windows in project using (FilteredElementCollector instances = new FilteredElementCollector(doc).OfCategory(builtInCategory) .WhereElementIsNotElementType().WherePasses(designOptionFilter).WherePasses(paraFilter)) { string roomNumber = ""; // Retrieve rooms from windows foreach (FamilyInstance inst in instances) { if (builtInCategory == BuiltInCategory.OST_Doors) { if (inst.ToRoom != null) { roomNumber = inst.ToRoom.Number; } else if (inst.FromRoom != null) { roomNumber = inst.FromRoom.Number; } } else { if (inst.FromRoom != null) { roomNumber = inst.FromRoom.Number; } else if (inst.ToRoom != null) { roomNumber = inst.ToRoom.Number; } } if (numeric) { Helpers.InstanceFromToRoomNumber(instancesInRoomCount, roomNumber, separator, instanceNumbers, inst); } else { Helpers.InstanceFromToRoom(instancesInRoomCount, roomNumber, separator, instanceNumbers, inst); } } } // Create transaction and make changes in Revit using (Transaction t = new Transaction(doc, "Number Instances")) { t.Start(); // Empty Mark parameter to avoid duplicated values foreach (KeyValuePair <FamilyInstance, string> entry in instanceNumbers) { Parameter instanceMark = entry.Key.LookupParameter(parameter.Definition.Name); instanceMark.Set(""); } // Populate Mark parameter foreach (KeyValuePair <FamilyInstance, string> entry in instanceNumbers) { Parameter instanceMark = entry.Key.LookupParameter(parameter.Definition.Name); if (entry.Value != "") { instanceMark.Set(entry.Value); countInstances += 1; } } t.Commit(); } }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; //GlobalParameter. //GlobalParameter one = ; FinishForm questions = new FinishForm(doc); questions.Show(); questions.Activate(); double FT = 0.3048; PhaseArray xcom = doc.Phases; Phase lastPhase = xcom.get_Item(xcom.Size - 1); ElementId idPhase = lastPhase.Id; FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc) .OfClass(typeof(SharedParameterElement)) .Cast <SharedParameterElement>() .ToList(); //SharedParameterElement shParam = shParamElements.Where(x => x.Name == "ADSK_Номер здания").First(); //Фильтр: Помещения на последней стадии FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID)); FilterElementIdRule rRule = new FilterElementIdRule(providerRoom, evaluator, idPhase); ElementParameterFilter room_filter = new ElementParameterFilter(rRule); //FilterableValueProvider provRoomSchool = new ParameterValueProvider(shParam.Id); FilterStringRuleEvaluator StrEvaluator = new FilterStringEquals(); //FilterRule rScRule = new FilterStringRule(provRoomSchool, StrEvaluator, "",false); //ElementParameterFilter roomSc_filter = new ElementParameterFilter(rScRule); IList <Element> rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms) .WhereElementIsNotElementType() .WherePasses(room_filter) //.WherePasses(roomSc_filter) .ToElements(); //Фильтр: Стены созданные на последней стадии FilterableValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterElementIdRule fRule = new FilterElementIdRule(provider, evaluator, idPhase); ElementParameterFilter door_filter = new ElementParameterFilter(fRule); IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls) .WhereElementIsNotElementType() .WherePasses(door_filter) .ToElements(); //Фильтр: экземпляры дверей List <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors) .WhereElementIsNotElementType() .Cast <FamilyInstance>() .ToList(); List <FamilySymbol> ento = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Entourage) .WhereElementIsElementType() .Cast <FamilySymbol>() .ToList(); List <String> entoName = new List <string>(); foreach (FamilySymbol i in ento) { entoName.Add(i.Name); } List <String> entoFamily = new List <string>(); //List<otdelka> otd = new List<otdelka>(); foreach (FamilySymbol f in ento) { //otd.Add(new otdelka(f.FamilyName+':'+f.Name,f.getP("АР_Состав отделки"))); entoFamily.Add(f.FamilyName); } //List<String> one = new List<string>(); //foreach (FamilySymbol f in ento) //{ // one.Add(f.getP("АР_Состав отделки")); //} //string two = doc.GetElement(rooms[0].LookupParameter("ОТД_Пол").AsElementId()).Name; List <Element> walls = new List <Element>(); List <GhostWall> cWalls = new List <GhostWall>(); foreach (Element item in allWalls) { if (item.LookupParameter("Помещение").AsString() != null & item.LookupParameter("Помещение").AsString() != "") { bool isLocal = (item as Wall).WallType.LookupParameter("rykomoika").AsInteger() == 1 ? true : false; walls.Add(item); cWalls.Add(new GhostWall( item.getP("Помещение"), item.LevelId, item.get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble(), isLocal )); } } List <ElementId> Levels = new List <ElementId>(); rooms = rooms.OrderBy(x => x.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()).ToList(); List <RoomFinishing> novaRooms = new List <RoomFinishing>(); foreach (Element e in rooms) { novaRooms.Add(new RoomFinishing(e)); } novaRooms = novaRooms.OrderBy(x => x.Num).ToList(); List <ElementId> wallLevels = new List <ElementId>(); foreach (Element i in rooms) { Levels.Add(i.LevelId); } foreach (Element i in walls) { wallLevels.Add(i.LevelId); } IEnumerable <String> LevelsName = new List <String>(); //Levels=Levels.Distinct().ToList(); //Levels = Levels.OrderBy(x=>doc.GetElement(x).Name).ToList(); foreach (ElementId i in Levels.Distinct().OrderBy(x => doc.GetElement(x).Name)) { LevelsName = LevelsName.Append(doc.GetElement(i).Name); } String str = String.Join(",", LevelsName); IEnumerable <bool> isNewC = new List <bool>(); IEnumerable <bool> isNewW = new List <bool>(); IEnumerable <bool> SecFin = new List <bool>(); List <String> CeilText = new List <String>(); List <String> MainText = new List <String>(); List <String> FloorText = new List <String>(); List <string> WallsLocal = new List <string>(); List <List <Element> > roomByLevel = new List <List <Element> >(); List <List <String> > roomNumByLevel = new List <List <String> >(); List <List <String> > CeilTextByLevel = new List <List <string> >(); List <List <String> > MainTextByLevel = new List <List <string> >(); List <List <String> > FloorTextByLevel = new List <List <string> >(); List <List <List <Element> > > FinishTable = new List <List <List <Element> > >(); List <List <List <String> > > FinishTableNum = new List <List <List <String> > >(); List <List <List <double> > > FinishTableW3S = new List <List <List <double> > >(); List <List <Element> > wallByLevel = new List <List <Element> >(); List <List <String> > wallNumByLevel = new List <List <String> >(); List <List <double> > wallAreaByLevel = new List <List <double> >(); List <List <double> > WallS1 = new List <List <double> >(); List <List <double> > WallS2 = new List <List <double> >(); List <List <string> > WallsLocalText = new List <List <string> >(); List <List <List <Element> > > floorTable = new List <List <List <Element> > >(); List <List <List <string> > > floorTableNum = new List <List <List <string> > >(); List <List <List <double> > > plintTable = new List <List <List <double> > >(); List <List <double> > plintByLevel = new List <List <double> >(); List <List <double> > perimByLevel = new List <List <double> >(); foreach (ElementId lev in Levels.Distinct().OrderBy(x => doc.GetElement(x).Name)) { List <Element> s = new List <Element>(); List <String> n = new List <String>(); List <String> ct = new List <String>(); List <String> mt = new List <String>(); List <String> ft = new List <String>(); List <double> ws = new List <double>(); List <double> ws2 = new List <double>(); List <string> wt = new List <string>(); List <double> pl = new List <double>(); List <double> pr = new List <double>(); for (int i = 0; i < Levels.Count(); i++) { if (Levels[i] == lev) { s.Add(rooms.ElementAt(i)); n.Add(rooms.ElementAt(i).get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); ct.Add(rooms.ElementAt(i).LookupParameter("ОТД_Потолок").AsValueString()); mt.Add(rooms.ElementAt(i).LookupParameter("ОТД_Стены").AsValueString()); ft.Add(rooms.ElementAt(i).LookupParameter("ОТД_Пол").AsValueString()); pr.Add(rooms.ElementAt(i).get_Parameter(BuiltInParameter.ROOM_PERIMETER).AsDouble()); ws.Add(0); ws2.Add(0); pl.Add(0); wt.Add(""); CeilText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Потолок").AsValueString()); MainText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Стены").AsValueString()); FloorText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Пол").AsValueString()); } } roomByLevel.Add(s); roomNumByLevel.Add(n); CeilTextByLevel.Add(ct); MainTextByLevel.Add(mt); FloorTextByLevel.Add(ft); WallS1.Add(ws); WallS2.Add(ws2); WallsLocalText.Add(wt); plintByLevel.Add(pl); perimByLevel.Add(pr); List <Element> w = new List <Element>(); List <String> wn = new List <String>(); List <double> wa = new List <double>(); //List<Wall> est = walls as List<Wall>; for (int i = 0; i < wallLevels.Count(); i++) { if (wallLevels[i] == lev) { w.Add(walls[i]); wn.Add(walls[i].LookupParameter("Помещение").AsString()); wa.Add(walls[i].get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble()); } } wallAreaByLevel.Add(wa); wallByLevel.Add(w); wallNumByLevel.Add(wn); } //Плинтус foreach (FamilyInstance d in doors) { foreach (RoomFinishing r in novaRooms) { try { if (d.get_FromRoom(lastPhase).Id == r.Id | d.get_ToRoom(lastPhase).Id == r.Id) { r.Perimeter -= d.LookupParameter("сп_Ширина проёма").AsDouble(); } } catch (Exception) { } } } //Задаём площади отделки помещений и указываем неизменные помещения foreach (ElementId lev in novaRooms.Select(x => x.Level).Distinct()) { foreach (RoomFinishing r in novaRooms.Where(x => x.Level == lev)) { //Стены for (int i = 0; i < novaRooms.Select(x => x.Level).Distinct().Count(); i++) { for (int w = 0; w < wallNumByLevel[i].Count(); w++) { if (wallByLevel[i][w].LevelId != lev) { continue; } Wall checkWall = (Wall)wallByLevel[i][w]; if (r.Num == wallNumByLevel[i][w]) { if (checkWall.WallType.LookupParameter("rykomoika").AsInteger() == 1) { r.LocalWallVal += wallAreaByLevel[i][w]; r.LocalWallText = checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString(); WallsLocal.Add(checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString()); continue; } r.MainWallVal += wallAreaByLevel[i][w]; WallsLocal.Add(""); } } } } } for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { for (int r = 0; r < roomNumByLevel[lev].Count(); r++) { //Плинтус for (int i = 0; i < doors.Count(); i++) { try { if (doors[i].get_FromRoom(lastPhase).Id == roomByLevel[lev][r].Id | doors[i].get_ToRoom(lastPhase).Id == roomByLevel[lev][r].Id) { plintByLevel[lev][r] += doors[i].LookupParameter("Ширина").AsDouble(); } } catch (Exception) { } } //Стены for (int w = 0; w < wallNumByLevel[lev].Count(); w++) { Wall checkWall = (Wall)wallByLevel[lev][w]; if (roomNumByLevel[lev][r] == wallNumByLevel[lev][w]) { if (checkWall.WallType.LookupParameter("rykomoika").AsInteger() == 1) { WallS2[lev][r] += wallAreaByLevel[lev][w]; WallsLocalText[lev][r] = checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString(); WallsLocal.Add(checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString()); continue; } WallS1[lev][r] += wallAreaByLevel[lev][w]; WallsLocal.Add(""); } } } } WallsLocal = WallsLocal.OrderBy(x => x).ToList(); //Сортируем помещения по типу отделки потолка и стен int finishTypes = 0; List <List <RoomFinishing> > novaFinishTable = new List <List <RoomFinishing> >(); if (WallsLocal.Count == 0) { foreach (string c in novaRooms.Select(x => x.CeilType).Distinct()) { foreach (string w in novaRooms.Select(x => x.WallType).Distinct()) { List <RoomFinishing> cw = novaRooms .Where(x => x.CeilType == c) .Where(y => y.WallType == w) .ToList(); novaFinishTable.Add(cw); foreach (RoomFinishing r in cw) { r.SimilarWallVal = cw.Sum(x => x.MainWallVal); } } } } else { foreach (string wt3 in WallsLocal.Distinct()) { foreach (string c in novaRooms.Select(x => x.CeilType).Distinct()) { foreach (string w in novaRooms.Select(x => x.WallType).Distinct()) { List <RoomFinishing> cw = novaRooms .Where(x => x.CeilType == c) .Where(y => y.WallType == w) .ToList(); novaFinishTable.Add(cw); foreach (RoomFinishing r in cw) { r.SimilarWallVal = cw.Sum(x => x.MainWallVal); } } } } } if (WallsLocal.Count == 0) { foreach (String i in CeilText.Distinct()) { foreach (String j in MainText.Distinct()) { FinishTable.Add(new List <List <Element> >()); FinishTableNum.Add(new List <List <string> >()); FinishTableW3S.Add(new List <List <double> >()); for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { List <Element> SimilarFinish = new List <Element>(); List <String> SimilarFinishNum = new List <String>(); List <double> SimW3S = new List <double>(); for (int r = 0; r < roomByLevel[lev].Count(); r++) { if (CeilTextByLevel[lev][r] == i & MainTextByLevel[lev][r] == j) { SimilarFinish.Add(roomByLevel[lev][r]); SimilarFinishNum.Add(roomNumByLevel[lev][r]); SimW3S.Add(WallS2[lev][r]); } } FinishTable[finishTypes].Add(SimilarFinish); FinishTableNum[finishTypes].Add(SimilarFinishNum); FinishTableW3S[finishTypes].Add(SimW3S); } finishTypes++; } } } else { foreach (string wt3 in WallsLocal.Distinct()) { foreach (String i in CeilText.Distinct()) { foreach (String j in MainText.Distinct()) { FinishTable.Add(new List <List <Element> >()); FinishTableNum.Add(new List <List <string> >()); FinishTableW3S.Add(new List <List <double> >()); for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { List <Element> SimilarFinish = new List <Element>(); List <String> SimilarFinishNum = new List <String>(); List <double> SimW3S = new List <double>(); for (int r = 0; r < roomByLevel[lev].Count(); r++) { if (CeilTextByLevel[lev][r] == i & MainTextByLevel[lev][r] == j & WallsLocalText[lev][r] == wt3) { SimilarFinish.Add(roomByLevel[lev][r]); SimilarFinishNum.Add(roomNumByLevel[lev][r]); SimW3S.Add(WallS2[lev][r]); } } FinishTable[finishTypes].Add(SimilarFinish); FinishTableNum[finishTypes].Add(SimilarFinishNum); FinishTableW3S[finishTypes].Add(SimW3S); } finishTypes++; } } } } List <List <RoomFinishing> > novaFloorTable = new List <List <RoomFinishing> >(); foreach (string i in novaRooms.Select(x => x.FloorType).Distinct()) { foreach (string pl in novaRooms.Select(x => x.PlintusType).Distinct()) { List <RoomFinishing> flpl = novaRooms .Where(x => x.FloorType == i) .Where(y => y.PlintusType == pl) .ToList(); novaFloorTable.Add(flpl); foreach (RoomFinishing r in flpl) { r.SimilarPlintusVal = flpl.Sum(x => x.Perimeter); } } } //Сортируем помещения по типу пола int floorTypes = 0; foreach (string i in FloorText.Distinct()) { floorTable.Add(new List <List <Element> >()); floorTableNum.Add(new List <List <string> >()); plintTable.Add(new List <List <double> >()); for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { List <Element> simFloor = new List <Element>(); List <string> simFloorNum = new List <string>(); List <double> simPlint = new List <double>(); for (int r = 0; r < roomByLevel[lev].Count(); r++) { if (FloorTextByLevel[lev][r] == i) { simFloor.Add(roomByLevel[lev][r]); simFloorNum.Add(roomNumByLevel[lev][r]); simPlint.Add(perimByLevel[lev][r] - plintByLevel[lev][r]); } } floorTable[floorTypes].Add(simFloor); floorTableNum[floorTypes].Add(simFloorNum); plintTable[floorTypes].Add(simPlint); } floorTypes++; } using (Transaction tr = new Transaction(doc, "otdelka")) { tr.Start(); GlobalParameter ohohoh = GlobalParametersManager.FindByName(doc, "НесколькоЭтажей") != ElementId.InvalidElementId ? doc.GetElement(GlobalParametersManager.FindByName(doc, "НесколькоЭтажей")) as GlobalParameter : GlobalParameter.Create(doc, "НесколькоЭтажей", ParameterType.YesNo); int MoreThenOneLevel = ((IntegerParameterValue)ohohoh.GetValue()).Value; //Передаем номера помещений с одинаковым типом отделки стен и потолка for (int lev = 0; lev < roomByLevel.Count(); lev++) { for (int r = 0; r < roomByLevel[lev].Count(); r++) { roomByLevel[lev][r].LookupParameter("SanT").Set(WallsLocalText[lev][r]); roomByLevel[lev][r].LookupParameter("ДлинаПроемов").Set(plintByLevel[lev][r]); } } for (int i = 0; i < FinishTable.Count(); i++) { String fillText = ""; //String fillText2 = ""; double sumW3S = 0; for (int lev = 0; lev < FinishTable[i].Count(); lev++) { sumW3S += FinishTableW3S[i][lev].Sum() * (FT * FT); if (FinishTable[i][lev].Count() == 0) { continue; } else { if (MoreThenOneLevel == 1) { fillText += (lev + 1).ToString() + " этаж:\n"; } fillText += Meta.shortLists(FinishTableNum[i][lev]); fillText += "\n"; } } for (int lev = 0; lev < FinishTable[i].Count(); lev++) { for (int r = 0; r < FinishTable[i][lev].Count(); r++) { try { FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ"); //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ"); } try { //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ"); FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ"); } FinishTable[i][lev][r].LookupParameter("testW").Set(fillText); //FinishTable[i][lev][r].LookupParameter("unitTest").Set(fillText2); FinishTable[i][lev][r].LookupParameter("SanS").Set(sumW3S > 0 ? sumW3S.ToString("F1") : ""); FinishTable[i][lev][r].LookupParameter("snS").Set(FinishTableW3S[i][lev][r]); } } } for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { for (int r = 0; r < roomByLevel[lev].Count(); r++) { roomByLevel[lev][r].LookupParameter("WallS1n").Set(WallS1[lev][r]); } } int withNames = questions.withnames; //Если нужны имена помещений //Передаем номера помещений с одинаковым типом стен потолка foreach (List <RoomFinishing> item in novaFinishTable) { if (item == null) { continue; } String fillText = ""; foreach (ElementId lev in item.Select(x => x.Level).Distinct()) { if (MoreThenOneLevel == 1) { fillText += doc.GetElement(lev).LookupParameter("Название уровня").AsString() + ":\n"; } if (withNames == 1) { foreach (RoomFinishing gg in item.Where(x => x.Level == lev)) { fillText += gg.Name + "-" + gg.Num + ", "; } fillText = fillText.Remove(fillText.Length - 2, 2) + "\n"; continue; } fillText += Meta.shortLists(item.Where(x => x.Level == lev).Select(y => y.Num).ToList()) + "\n"; } foreach (ElementId lev in item.Select(x => x.Level).Distinct()) { foreach (RoomFinishing r in item.Where(x => x.Level == lev)) { try { r.refElement.LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { r.refElement.LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ"); } try { r.refElement.LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { r.refElement.LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ"); } r.refElement.LookupParameter("testW").Set(fillText); //r.refElement.LookupParameter("ОТД_Кол.Стены").Set(0); r.refElement.LookupParameter("ОТД_Кол.Стены").Set(r.SimilarWallVal); //r.refElement.LookupParameter("PlintusTotal").Set(r.Perimeter); //item.Select(x => x.refElement.LookupParameter("testF").Set(fillText)); //item.Select(x => x.refElement.LookupParameter("PlintusTotal").Set(x.SimilarPlintusVal)); } } } //Передаем номера помещений с одинаковым типом отделки пола foreach (List <RoomFinishing> item in novaFloorTable) { if (item == null) { continue; } String fillText = ""; foreach (ElementId lev in item.Select(x => x.Level).Distinct()) { if (MoreThenOneLevel == 1) { fillText += doc.GetElement(lev).LookupParameter("Название уровня").AsString() + ":\n"; } if (withNames == 1) { foreach (RoomFinishing gg in item.Where(x => x.Level == lev)) { fillText += gg.Name + "-" + gg.Num + ", "; } fillText = fillText.Remove(fillText.Length - 2, 2) + "\n"; continue; } fillText += Meta.shortLists(item.Where(x => x.Level == lev).Select(y => y.Num).ToList()) + "\n"; } foreach (ElementId lev in item.Select(x => x.Level).Distinct()) { foreach (RoomFinishing r in item.Where(x => x.Level == lev)) { r.refElement.LookupParameter("ОТД_Состав.Пол").Set(""); try { r.refElement.LookupParameter("ОТД_Состав.Пол").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Пол").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { r.refElement.LookupParameter("ОТД_Состав.Пол").Set("НЕТ ОТДЕЛКИ"); } try { r.refElement.LookupParameter("ОТД_Состав.Плинтус").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Плинтус").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { r.refElement.LookupParameter("ОТД_Состав.Плинтус").Set("НЕТ ОТДЕЛКИ"); } r.refElement.LookupParameter("testF").Set(fillText); r.refElement.LookupParameter("ОТД_Кол.Плинтус").Set(""); if (r.PlintusType != "__Отделка : ---") { r.refElement.LookupParameter("ОТД_Кол.Плинтус").Set((r.SimilarPlintusVal * FT).ToString("F1")); } r.refElement.LookupParameter("PlintusTotal").Set(r.Perimeter); //item.Select(x => x.refElement.LookupParameter("testF").Set(fillText)); //item.Select(x => x.refElement.LookupParameter("PlintusTotal").Set(x.SimilarPlintusVal)); } } } // for (int i = 0; i < floorTable.Count(); i++) // { // double sumPlint = 0; // String fillText = ""; // for (int lev = 0; lev < floorTable[i].Count(); lev++) // { // sumPlint += plintTable[i][lev].Sum() * FT; // if (floorTable[i][lev].Count() == 0) // { // continue; // } // else // { // if (MoreThenOneLevel==1) // { // fillText += (lev + 1).ToString() + " этаж:\n"; // } // fillText += Meta.shortLists(floorTableNum[i][lev]); // fillText += "\n"; // } // } // for (int lev = 0; lev < floorTable[i].Count(); lev++) // { //for (int r = 0; r < floorTable[i][lev].Count(); r++) //{ // try // { // floorTable[i][lev][r].LookupParameter("ОТД_Состав.Пол").Set(doc.GetElement(floorTable[i][lev][r].LookupParameter("ОТД_Пол").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); // } // catch (Exception) // { // floorTable[i][lev][r].LookupParameter("ОТД_Состав.Пол").Set("НЕТ ОТДЕЛКИ"); // } // floorTable[i][lev][r].LookupParameter("testF").Set(fillText); // floorTable[i][lev][r].LookupParameter("PlintusTotal").Set(sumPlint); // if (floorTable[i][lev][r].LookupParameter("плинтус").AsInteger() == 1) // { // floorTable[i][lev][r].setP("PlintusTotalT", (sumPlint * FT).ToString("F1")); // } // } // } // } tr.Commit(); } //String output = String.Join(", ", roomNumByLevel[0]); TaskDialog msg = new TaskDialog("Info"); msg.MainInstruction = "Ok"; //output;// FinishTable.Count().ToString(); msg.Show(); return(Result.Succeeded); }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; PhaseArray xcom = doc.Phases; Phase lastPhase = xcom.get_Item(xcom.Size - 1); ElementId idPhase = lastPhase.Id; FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); GlobalParameter GlobePar2 = GlobalParametersManager.FindByName(doc, "FinData") != ElementId.InvalidElementId ? doc.GetElement(GlobalParametersManager.FindByName(doc, "FinData")) as GlobalParameter :null; FinishForm MainForm = new FinishForm(doc); MainForm.ShowDialog(); using (Transaction tr = new Transaction(doc, "setGP")) { tr.Start(); GlobalParameter GlobePar = GlobalParametersManager.FindByName(doc, "FinData") != ElementId.InvalidElementId ? doc.GetElement(GlobalParametersManager.FindByName(doc, "FinData")) as GlobalParameter : GlobalParameter.Create(doc, "FinData", ParameterType.Text); GlobePar.SetValue(new StringParameterValue(string.Join("|", MainForm.wTypeBoxes))); //int MoreThenOneLevel = ((IntegerParameterValue)GlobePar.GetValue()).Value; tr.Commit(); } lastPhase = MainForm.retPhase; idPhase = lastPhase.Id; List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc) .OfClass(typeof(SharedParameterElement)) .Cast <SharedParameterElement>() .ToList(); //Фильтр: Помещения на последней стадии FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID)); FilterElementIdRule rRule = new FilterElementIdRule(providerRoom, evaluator, idPhase); ElementParameterFilter room_filter = new ElementParameterFilter(rRule); //FilterableValueProvider provRoomSchool = new ParameterValueProvider(shParam.Id); FilterStringRuleEvaluator StrEvaluator = new FilterStringEquals(); IList <Element> rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms) .WhereElementIsNotElementType() .WherePasses(room_filter) //.WherePasses(roomSc_filter) .ToElements(); //Фильтр: Стены созданные на последней стадии FilterableValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterElementIdRule fRule = new FilterElementIdRule(provider, evaluator, idPhase); ElementParameterFilter door_filter = new ElementParameterFilter(fRule); IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls) .WhereElementIsNotElementType() .WherePasses(door_filter) .ToElements(); //Фильтр: экземпляры дверей List <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors) .WhereElementIsNotElementType() .Cast <FamilyInstance>() .ToList(); foreach (Element e in rooms) { RoomFinishing.Rooms.Add(new RoomFinishing(e)); } RoomFinishing.Rooms = RoomFinishing.Rooms.OrderBy(x => x.Num).ToList(); List <GhostWall> cWalls = new List <GhostWall>(); foreach (Element wall in allWalls) { if (wall.LookupParameter("Помещение").AsString() != null & wall.LookupParameter("Помещение").AsString() != "") { cWalls.Add(new GhostWall(wall, MainForm.LocType)); } } foreach (GhostWall w in cWalls) { foreach (RoomFinishing r in RoomFinishing.Rooms) { if (r.Num == w.Room) { if (w.typeName == MainForm.LocType.Name) { r.unitLocalWallVal += w.Area; r.LocalWallText = w.sostav; } else if (w.typeName == MainForm.ColType.Name) { r.unitKolonWallVal += w.Area; r.KolonWallText = w.sostav; } else { r.unitMainWallVal += w.Area; } if (w.countNewW) { r.unitNewWallVal += w.Area; } } } } //Плинтус foreach (FamilyInstance d in doors) { foreach (RoomFinishing r in RoomFinishing.Rooms) { try { if (d.get_FromRoom(lastPhase).Id == r.Id | d.get_ToRoom(lastPhase).Id == r.Id) { r.Perimeter -= d.LookupParameter("сп_Ширина проёма").AsDouble(); } } catch (Exception) { } } } RoomFinishing.makeFinish(MainForm); RoomFinishing.makeFloor(MainForm.splitLevel); using (Transaction tr = new Transaction(doc, "otdelka")) { tr.Start(); GlobalParameter GlobePar = GlobalParametersManager.FindByName(doc, "НесколькоЭтажей") != ElementId.InvalidElementId ? doc.GetElement(GlobalParametersManager.FindByName(doc, "НесколькоЭтажей")) as GlobalParameter : GlobalParameter.Create(doc, "НесколькоЭтажей", ParameterType.YesNo); int MoreThenOneLevel = ((IntegerParameterValue)GlobePar.GetValue()).Value; int withNames = MainForm.withnames; MoreThenOneLevel = MainForm.levels; RoomFinishing.FinishTableCommit(doc, MainForm); RoomFinishing.FloorTableCommit(MoreThenOneLevel, withNames, doc); tr.Commit(); } TaskDialog msg = new TaskDialog("Info"); msg.MainInstruction = $"Выполнен расчет отделки для стадии \"{MainForm.retPhase.Name}\""; msg.Show(); return(Result.Succeeded); }
private List <Element> GetLightingFixtures(Area area, out Room correlatedRoom) { correlatedRoom = null; var lightingFixtures = new List <Element>(); try { var fromHost = new List <Element>(); var fromLink = new List <Element>(); var profiles = new CurveArrArray(); var outline = GetBoundingBox(area, out profiles); var topFace = GetAreaFace(profiles); var intersectFilter = new BoundingBoxIntersectsFilter(outline); var insideFilter = new BoundingBoxIsInsideFilter(outline); var orFilter = new LogicalOrFilter(intersectFilter, insideFilter); var collector = new FilteredElementCollector(m_doc); collector.OfCategory(BuiltInCategory.OST_LightingFixtures); var elementIds = collector.WherePasses(orFilter).ToElementIds().ToList(); var roomCollector = new FilteredElementCollector(m_doc); roomCollector.OfCategory(BuiltInCategory.OST_Rooms); var roomsFound = roomCollector.WherePasses(orFilter).ToElements().Cast <Room>().ToList(); foreach (var room in roomsFound) { if (area.LevelId.IntegerValue == room.LevelId.IntegerValue) { correlatedRoom = room; break; } } var bltParam1 = BuiltInParameter.INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM; var pvp1 = new ParameterValueProvider(new ElementId((int)bltParam1)); var bltParam2 = BuiltInParameter.FAMILY_LEVEL_PARAM; var pvp2 = new ParameterValueProvider(new ElementId((int)bltParam2)); FilterNumericRuleEvaluator fnrv = new FilterNumericEquals(); var ruleValueId = new ElementId(area.LevelId.IntegerValue); FilterRule filterRule1 = new FilterElementIdRule(pvp1, fnrv, ruleValueId); FilterRule filterRule2 = new FilterElementIdRule(pvp2, fnrv, ruleValueId); var paramFilter1 = new ElementParameterFilter(filterRule1); var paramFilter2 = new ElementParameterFilter(filterRule2); var paramFilter = new LogicalOrFilter(paramFilter1, paramFilter2); if (elementIds.Count > 0) { collector = new FilteredElementCollector(m_doc, elementIds); fromHost = collector.WherePasses(paramFilter).ToElements().ToList(); fromHost = GetPolygonIntersect(topFace, fromHost); } if (lightingSelection != ModelSelection.Host) { if (linkedDocuments.Count > 0) { foreach (Document doc in m_app.Application.Documents) { if (linkedDocuments.Contains(doc.Title)) { if (null == correlatedRoom) { roomCollector = new FilteredElementCollector(doc); roomCollector.OfCategory(BuiltInCategory.OST_Rooms); roomsFound = roomCollector.WherePasses(orFilter).ToElements().Cast <Room>().ToList(); foreach (var room in roomsFound) { if (area.LevelId.IntegerValue == room.LevelId.IntegerValue) { correlatedRoom = room; break; } } } collector = new FilteredElementCollector(doc); collector.OfCategory(BuiltInCategory.OST_LightingFixtures); elementIds = collector.WherePasses(orFilter).ToElementIds().ToList(); if (elementIds.Count > 0) { collector = new FilteredElementCollector(doc, elementIds); var elements = collector.WherePasses(paramFilter).ToElements().ToList(); elements = GetPolygonIntersect(topFace, elements); fromLink.AddRange(elements); } } } } } switch (lightingSelection) { case ModelSelection.Host: lightingFixtures = fromHost; break; case ModelSelection.Link: lightingFixtures = fromLink; break; case ModelSelection.Both: lightingFixtures.AddRange(fromHost); lightingFixtures.AddRange(fromLink); break; } } catch (Exception ex) { MessageBox.Show("Failed to get lighting fixtures.\n" + ex.Message, "Get Lighting Fixtures", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(lightingFixtures); }
/// <summary> /// Return all elements from the given collector /// whose element id is greater than 'lastId'. /// </summary> FilteredElementCollector GetElementsAfter( FilteredElementCollector input, ElementId lastId) { BuiltInParameter bip = BuiltInParameter.ID_PARAM; ParameterValueProvider provider = new ParameterValueProvider( new ElementId( bip ) ); FilterNumericRuleEvaluator evaluator = new FilterNumericGreater(); FilterRule rule = new FilterElementIdRule( provider, evaluator, lastId ); ElementParameterFilter filter = new ElementParameterFilter( rule ); return input.WherePasses( filter ); }
/// <summary> /// Return the all elements that /// use the given ElementType. /// </summary> static FilteredElementCollector GetAllElementsUsingType( Document doc, ElementType et) { // built-in parameter storing the type element id: BuiltInParameter bip = BuiltInParameter.ELEM_TYPE_PARAM; ParameterValueProvider provider = new ParameterValueProvider( new ElementId( bip ) ); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); FilterRule rule = new FilterElementIdRule( provider, evaluator, et.Id ); ElementParameterFilter filter = new ElementParameterFilter( rule ); FilteredElementCollector collector = new FilteredElementCollector( doc ) .WhereElementIsNotElementType() .WherePasses( filter ); return collector; }
private static void HostedFamilyInstanceOpenings(Wall wall, double minOpeningValue) { double wallOpeningArea = 0.0; double wallTotalOpeningArea = 0.0; // Filter all Family Instances where the HOST_ID_PARAM // equals the wall ID // // More information at // http://thebuildingcoder.typepad.com/ // blog/2010/06/parameter-filter.html#4 BuiltInParameter testParam = BuiltInParameter.HOST_ID_PARAM; ParameterValueProvider pvp = new ParameterValueProvider( new ElementId((int)testParam)); FilterNumericRuleEvaluator fnrv = new FilterNumericEquals(); ElementId ruleValId = wall.Id; FilterRule paramFr = new FilterElementIdRule (pvp, fnrv, ruleValId); ElementParameterFilter epf = new ElementParameterFilter(paramFr); FilteredElementCollector collector = new FilteredElementCollector(wall.Document); collector.OfClass(typeof(FamilyInstance)).WherePasses(epf); IList<Element> hostedFamilyInstances = collector.ToElements(); // Now iterate through the collected family instances Document doc = wall.Document; double previousArea = wall.get_Parameter( BuiltInParameter.HOST_AREA_COMPUTED).AsDouble(); foreach (FamilyInstance instance in hostedFamilyInstances) { // Delete the hosted family instace and regenerate doc.Delete(instance); doc.Regenerate(); // Get the new area to compare double newArea = wall.get_Parameter( BuiltInParameter.HOST_AREA_COMPUTED).AsDouble(); // So the instance opening equals: double instanceAreaOnTheWall = Math.Abs(newArea - previousArea); // The element area (on wall) is smaller than // the minOpeningValue? if (instanceAreaOnTheWall <= minOpeningValue) wallOpeningArea += instanceAreaOnTheWall; else wallTotalOpeningArea += instanceAreaOnTheWall; if (System.Diagnostics.Debugger.IsAttached) TaskDialog.Show( "Wall opening (by inst) found (in sq feet)", string.Format("Area: {0}", instanceAreaOnTheWall)); previousArea = newArea; } AddWallArea(wall.Id, wallOpeningArea, wallTotalOpeningArea); }
/// <summary> /// Return the first wall found that /// uses the given wall type. /// </summary> static Wall GetFirstWallUsingType( Document doc, WallType wallType) { // built-in parameter storing this // wall's wall type element id: BuiltInParameter bip = BuiltInParameter.ELEM_TYPE_PARAM; ParameterValueProvider provider = new ParameterValueProvider( new ElementId( bip ) ); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); FilterRule rule = new FilterElementIdRule( provider, evaluator, wallType.Id ); ElementParameterFilter filter = new ElementParameterFilter( rule ); FilteredElementCollector collector = new FilteredElementCollector( doc ) .OfClass( typeof( Wall ) ) .WherePasses( filter ); return collector.FirstElement() as Wall; }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; PhaseArray xcom = doc.Phases; Phase lastPhase = xcom.get_Item(xcom.Size - 1); ElementId idPhase = lastPhase.Id; FinishForm MainForm = new FinishForm(doc); MainForm.disFElements("Number"); MainForm.ShowDialog(); lastPhase = MainForm.retPhase; idPhase = lastPhase.Id; FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); FilterableValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterElementIdRule fRule = new FilterElementIdRule(provider, evaluator, idPhase); ElementParameterFilter door_filter = new ElementParameterFilter(fRule); IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls) .WhereElementIsNotElementType() .WherePasses(door_filter) .ToElements(); List <Element> otdWalls = allWalls.Where(x => x.Name.StartsWith("I__Отделка")).ToList(); List <Room> roomofWall = new List <Room>(); using (Transaction tr = new Transaction(doc, "creating")) { tr.Start(); foreach (Element i in otdWalls) { BoundingBoxXYZ bBox = i.get_BoundingBox(null); if (bBox != null) { XYZ origin = new XYZ((bBox.Max.X + bBox.Min.X) / 2, (bBox.Max.Y + bBox.Min.Y) / 2, (bBox.Max.Z + bBox.Min.Z) / 2); try { i.setP("Помещение", doc.GetRoomAtPoint(origin, lastPhase).Number); } catch (Exception) { } } } tr.Commit(); } return(Result.Succeeded); }
private ElementFilter CreateParamFilter(int paramId, string strOperator, string paramValue, bool emptyValue) { try { ParameterProperties pp = selectedParameters[paramId]; ParameterValueProvider pvp = new ParameterValueProvider(new ElementId(pp.ParamId)); switch (pp.ParamStorageType) { case StorageType.ElementId: if (pp.ParamName == "Phase Created" || pp.ParamName == "Phase Demolished") { FilterNumericRuleEvaluator fnre1 = new FilterNumericEquals(); var phaseId = from phase in phases where phase.Value.Name == paramValue select phase.Key; int pId = phaseId.First(); ElementId ruleValId = new ElementId(pId); FilterRule filterRule1 = new FilterElementIdRule(pvp, fnre1, ruleValId); if (strOperator == "does not equal") { return(new ElementParameterFilter(filterRule1, true)); } else { return(new ElementParameterFilter(filterRule1)); } } return(null); case StorageType.Double: if (emptyValue) { FilterNumericRuleEvaluator fnre = new FilterNumericGreater(); FilterDoubleRule doubleRule = new FilterDoubleRule(pvp, fnre, 0, double.Epsilon); return(new ElementParameterFilter(doubleRule, true)); } FilterNumericRuleEvaluator fnre2 = FindFilterNumericRuleEvaluator(strOperator); double dblValue = 0; if (!string.IsNullOrEmpty(paramValue)) { double.TryParse(paramValue, out dblValue); } FilterRule filterRule2 = new FilterDoubleRule(pvp, fnre2, dblValue, double.Epsilon); if (strOperator == "does not equal") { return(new ElementParameterFilter(filterRule2, true)); } else { return(new ElementParameterFilter(filterRule2)); } case StorageType.Integer: if (emptyValue) { FilterNumericRuleEvaluator fnre = new FilterNumericGreater(); FilterIntegerRule integerRule = new FilterIntegerRule(pvp, fnre, 0); return(new ElementParameterFilter(integerRule, true)); } FilterNumericRuleEvaluator fnre3 = FindFilterNumericRuleEvaluator(strOperator); int intValue = 0; if (pp.ParamName == "Workset") { var worksetId = from ws in worksets where ws.Value.Name == paramValue select ws.Key; intValue = worksetId.First(); } else if (!string.IsNullOrEmpty(paramValue)) { int.TryParse(paramValue, out intValue); } FilterRule filterRule3 = new FilterIntegerRule(pvp, fnre3, intValue); if (strOperator == "does not equal") { return(new ElementParameterFilter(filterRule3, true)); } else { return(new ElementParameterFilter(filterRule3)); } case StorageType.String: if (emptyValue) { FilterStringRuleEvaluator fsre = new FilterStringGreater(); FilterStringRule stringRule = new FilterStringRule(pvp, fsre, "", false); return(new ElementParameterFilter(stringRule, true)); } FilterStringRuleEvaluator fnre4 = FindFilterStringRuleEvaluator(strOperator); string strValue = paramValue; FilterStringRule filterRule4 = new FilterStringRule(pvp, fnre4, strValue, false); if (strOperator.Contains("does not")) { return(new ElementParameterFilter(filterRule4, true)); } else { return(new ElementParameterFilter(filterRule4, false)); } default: return(null); } } catch (Exception ex) { MessageBox.Show("Failed to create parameter filters.\n" + ex.Message, "CreateParamFilter", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(null); }
void f4( Document doc ) { // Use numeric evaluator and integer rule to test ElementId parameter // Filter levels whose id is greater than specified id value BuiltInParameter testParam = BuiltInParameter.ID_PARAM; ParameterValueProvider pvp = new ParameterValueProvider( new ElementId( (int) testParam ) ); FilterNumericRuleEvaluator fnrv = new FilterNumericGreater(); // filter elements whose Id is greater than 99 ElementId ruleValId = new ElementId( 99 ); FilterRule paramFr = new FilterElementIdRule( pvp, fnrv, ruleValId ); ElementParameterFilter epf = new ElementParameterFilter( paramFr ); FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( ViewPlan ) ) .WherePasses( epf ); // only deal with ViewPlan // Use numeric evaluator and integer rule to test bool parameter // Filter levels whose crop view is false int ruleValInt = 0; testParam = BuiltInParameter.VIEWER_CROP_REGION; pvp = new ParameterValueProvider( new ElementId( (int) testParam ) ); fnrv = new FilterNumericEquals(); paramFr = new FilterIntegerRule( pvp, fnrv, ruleValInt ); epf = new ElementParameterFilter( paramFr ); collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( ViewPlan ) ) .WherePasses( epf ); // only deal with ViewPlan // Use numeric evaluator and double rule to test double parameter // Filter levels whose top offset is greater than specified value double ruleValDb = 10; testParam = BuiltInParameter.VIEWER_BOUND_OFFSET_TOP; pvp = new ParameterValueProvider( new ElementId( (int) testParam ) ); fnrv = new FilterNumericGreater(); paramFr = new FilterDoubleRule( pvp, fnrv, ruleValDb, double.Epsilon ); collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( ViewPlan ) ) .WherePasses( epf ); // only deal with ViewPlan // Use string evaluator and string rule to test string parameter // Filter all elements whose view name contains level String ruleValStr = "Level"; testParam = BuiltInParameter.VIEW_NAME; pvp = new ParameterValueProvider( new ElementId( (int) testParam ) ); FilterStringRuleEvaluator fnrvStr = new FilterStringContains(); paramFr = new FilterStringRule( pvp, fnrvStr, ruleValStr, false ); collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( ViewPlan ) ) .WherePasses( epf ); // only deal with ViewPlan }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; PhaseArray xcom = doc.Phases; Phase lastPhase = xcom.get_Item(xcom.Size - 1); FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID)); FilterableValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); double FT = 0.3048; ElementId idPhase = lastPhase.Id; FilterElementIdRule rRule = new FilterElementIdRule(providerRoom, evaluator, idPhase); FilterElementIdRule fRule = new FilterElementIdRule(provider, evaluator, idPhase); ElementParameterFilter room_filter = new ElementParameterFilter(rRule); ElementParameterFilter door_filter = new ElementParameterFilter(fRule); IList <Element> rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms) .WhereElementIsNotElementType() .WherePasses(room_filter) .ToElements(); IList <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors) .WhereElementIsNotElementType() .WherePasses(door_filter).Cast <FamilyInstance>().ToList(); IList <FamilyInstance> windows = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Windows) .WhereElementIsNotElementType() .WherePasses(door_filter).Cast <FamilyInstance>().ToList(); FamilySymbol neocube = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Where(q => q.Name == "cube").First() as FamilySymbol; IList <XYZ> a = new List <XYZ>(); IList <String> b = new List <String>(); //Room two = rooms[0] as Room; int g = 0; FilterStringRuleEvaluator cubeEval = new FilterStringEquals(); FilterableValueProvider cubeProv = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME)); FilterStringRule cubeRule = new FilterStringRule(cubeProv, cubeEval, "cube", false); ElementParameterFilter cubeFilter = new ElementParameterFilter(cubeRule); List <FamilyInstance> existCubes = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsNotElementType().WherePasses(cubeFilter).Cast <FamilyInstance>().ToList(); using (Transaction tr = new Transaction(doc, "creating")) { tr.Start(); foreach (FamilyInstance i in existCubes) { doc.Delete(i.Id); } foreach (Element i in rooms) { for (int ind = 0; ind < doors.Count; ind++) { FamilyInstance dr = doors[ind]; try { if (dr.get_FromRoom(lastPhase).Id == i.Id | dr.get_ToRoom(lastPhase).Id == i.Id) { BoundingBoxXYZ bBox = i.get_BoundingBox(null); LocationPoint origin = (LocationPoint)i.Location; XYZ center = origin.Point; if (!neocube.IsActive) { neocube.Activate(); } FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString()); cubeIns.setType(); b.Append("ok"); //dr.LookupParameter("ADSK_Марка").AsValueString()); doors.Remove(dr); ind--; } } catch (Exception) { } } /* * foreach (FamilyInstance dr in doors) * { * try * { * if (dr.get_FromRoom(lastPhase).Id == i.Id | dr.get_ToRoom(lastPhase).Id == i.Id) * { * * BoundingBoxXYZ bBox = i.get_BoundingBox(null); * LocationPoint origin = (LocationPoint)i.Location; * * XYZ center = origin.Point; * if (!neocube.IsActive) * neocube.Activate(); * FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); * cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); * cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString()); * cubeIns.LookupParameter("isAreo").Set(0); * * b.Append("ok");//dr.LookupParameter("ADSK_Марка").AsValueString()); * * } * } * catch (Exception) * { * * } * } */ foreach (FamilyInstance dr in windows) { try { if (dr.get_FromRoom(lastPhase).Id == i.Id) { LocationPoint origin = (LocationPoint)i.Location; XYZ center = origin.Point; if (!neocube.IsActive) { neocube.Activate(); } FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString()); cubeIns.setType(); FamilyInstance winOtkos = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); winOtkos.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); winOtkos.LookupParameter("MainText").Set("Площадь откосов: "); winOtkos.LookupParameter("Area").Set(dr.LookupParameter("ADSK_Откосы_Глубина").AsDouble() * (dr.LookupParameter("VIDNAL_Высота проема").AsDouble() * 2 + dr.LookupParameter("VIDNAL_Ширина проема").AsDouble())); winOtkos.setType("area"); FamilyInstance winPodok = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); winPodok.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); String output = String.Format("Подоконник {0:f2}x{1:f2}", dr.LookupParameter("VIDNAL_Ширина проема").AsDouble() * FT, dr.LookupParameter("ADSK_Откосы_Глубина").AsDouble() * FT); winPodok.LookupParameter("MainText").Set(output); winPodok.setType(); FamilyInstance winUgol = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); winUgol.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); winUgol.LookupParameter("MainText").Set("ПВХ уголок 60х60"); winUgol.LookupParameter("dlina").Set(dr.LookupParameter("VIDNAL_Высота проема").AsDouble() * 2 + dr.LookupParameter("VIDNAL_Ширина проема").AsDouble()); winUgol.setType("len"); } } catch (Exception) { } } } foreach (Element i in rooms) { if (i.LookupParameter("ЗаменаПокрытияПола").AsInteger() == 1) { LocationPoint origin = (LocationPoint)i.Location; XYZ center = origin.Point; if (!neocube.IsActive) { neocube.Activate(); } FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); cubeIns.LookupParameter("MainText").Set(i.LookupParameter("snosF").AsString()); cubeIns.LookupParameter("Area").Set(i.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble()); cubeIns.setType("area"); if (cubeIns.LookupParameter("MainText").AsString() == "") { doc.Delete(cubeIns.Id); } } if (i.LookupParameter("НоваяОтделка").AsInteger() == 1) { LocationPoint origin = (LocationPoint)i.Location; XYZ center = origin.Point; if (!neocube.IsActive) { neocube.Activate(); } FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); cubeIns.LookupParameter("MainText").Set("Демонтаж штукатурки"); cubeIns.LookupParameter("Area").Set(i.LookupParameter("WallS").AsDouble()); cubeIns.setType("area"); } } tr.Commit(); } //XYZ origin = new XYZ(0,0,0); /* * using (Transaction tr = new Transaction(doc,"creating")) * { * tr.Start(); * * for (int i = 0; i < a.Count; i++) * { * if (!neocube.IsActive) * neocube.Activate(); * FamilyInstance cubeIns = doc.Create.NewFamilyInstance(a[i], neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); * cubeIns.LookupParameter("MainText").Set(b[i]); * } * * * tr.Commit(); * * } */ //FamilySymbol elt = doors[0].Symbol; //FamilySymbol one=elt as FamilySymbol; TaskDialog msg = new TaskDialog("Info"); msg.MainInstruction = g.ToString(); msg.Show(); return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string messages, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; Transaction tx = new Transaction( doc, "Test" ); tx.Start(); // use the view filter FilteredElementCollector collector = new FilteredElementCollector( doc, doc.ActiveView.Id ); // use the parameter filter. // get the phase id "New construction" ElementId idPhase = GetPhaseId( "New Construction", doc ); ParameterValueProvider provider = new ParameterValueProvider( new ElementId( (int) BuiltInParameter.PHASE_CREATED ) ); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); FilterElementIdRule rule = new FilterElementIdRule( provider, evaluator, idPhase ); ElementParameterFilter parafilter = new ElementParameterFilter( rule ); collector.WherePasses( parafilter ); TaskDialog.Show( "Element Count", "There are " + collector.Count().ToString() + " elements in the current view created" + " with phase New Construction" ); tx.Commit(); return Result.Succeeded; }
public static ElementFilter createParameterFilter(Document doc, ParameterData parameter, string operation, string ruleString) { ElementId parameterId = parameter.Id; ParameterValueProvider fvp = new ParameterValueProvider(parameterId); StorageType storageType = parameter.StorageType; FilterRule fRule = null; FilterInverseRule fInvRule = null; ElementParameterFilter filter = null; switch (storageType) { case StorageType.String: case StorageType.Integer: FilterStringRuleEvaluator fsre = null; switch (operation) { case "равно": fsre = new FilterStringEquals(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); filter = new ElementParameterFilter(fRule); break; case "не равно": fsre = new FilterStringEquals(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "содержит": fsre = new FilterStringContains(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); filter = new ElementParameterFilter(fRule); break; case "не содержит": fsre = new FilterStringContains(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "начинается с": fsre = new FilterStringBeginsWith(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); filter = new ElementParameterFilter(fRule); break; case "не начинается с": fsre = new FilterStringBeginsWith(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "заканчивается на": fsre = new FilterStringEndsWith(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); filter = new ElementParameterFilter(fRule); break; case "не заканчивается на": fsre = new FilterStringEndsWith(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; } break; case StorageType.Double: FilterNumericRuleEvaluator fnre = null; double ruleValue = Convert.ToDouble(ruleString); switch (operation) { case "равно": fnre = new FilterNumericEquals(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; case "не равно": fnre = new FilterNumericEquals(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "больше": fnre = new FilterNumericGreater(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; case "больше или равно": fnre = new FilterNumericGreaterOrEqual(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; case "меньше": fnre = new FilterNumericLess(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; case "меньше или равно": fnre = new FilterNumericLessOrEqual(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; } break; case StorageType.ElementId: var levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).ToElements(); var level = levels.Where(i => i.Name == ruleString).FirstOrDefault(); ElementId ruleId = level.Id; fnre = null; switch (operation) { case "равно": fnre = new FilterNumericEquals(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; case "не равно": fnre = new FilterNumericEquals(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "выше": fnre = new FilterNumericGreater(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; case "ровно или выше": fnre = new FilterNumericGreaterOrEqual(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; case "ниже": fnre = new FilterNumericLess(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; case "ровно или ниже": fnre = new FilterNumericLessOrEqual(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; } break; } return(filter); }
void f2( Document doc, Level level ) { FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfCategory( BuiltInCategory.OST_StructuralFraming ); collector.OfClass( typeof( FamilyInstance ) ); BuiltInParameter bip = BuiltInParameter .INSTANCE_REFERENCE_LEVEL_PARAM; ParameterValueProvider provider = new ParameterValueProvider( new ElementId( bip ) ); FilterNumericRuleEvaluator evaluator = new FilterNumericGreater(); ElementId idRuleValue = level.Id; FilterElementIdRule rule = new FilterElementIdRule( provider, evaluator, idRuleValue ); ElementParameterFilter filter = new ElementParameterFilter( rule ); collector.WherePasses( filter ); }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; ElementId idPhase = doc.Phases.get_Item(doc.Phases.Size - 1).Id; //Фильтр по общему параметру "ADSK_Номер здания" List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc) .OfClass(typeof(SharedParameterElement)) .Cast <SharedParameterElement>() .ToList(); SharedParameterElement shParam = shParamElements.Where(x => x.Name == "ADSK_Номер здания").First(); //Фильтр помещений FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID)); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); FilterElementIdRule rRule = new FilterElementIdRule(providerRoom, evaluator, idPhase); ElementParameterFilter room_filter = new ElementParameterFilter(rRule); FilterableValueProvider provRoomSchool = new ParameterValueProvider(shParam.Id); FilterStringRuleEvaluator StrEvaluator = new FilterStringEquals(); FilterRule rScRule = new FilterStringRule(provRoomSchool, StrEvaluator, "", false); ElementParameterFilter roomSc_filter = new ElementParameterFilter(rScRule); IList <Element> revit_rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms) .WhereElementIsNotElementType() .WherePasses(room_filter) .WherePasses(roomSc_filter) .ToElements(); //Фильтр стен FilterableValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterElementIdRule fRule = new FilterElementIdRule(provider, evaluator, idPhase); ElementParameterFilter wall_filter = new ElementParameterFilter(fRule); IList <Element> revit_walls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls) .WhereElementIsNotElementType() .WherePasses(wall_filter) .ToElements(); //Перенос помещений и стен в объекты наших классов List <GhostRoom> rooms = revit_rooms.Select(x => new GhostRoom(x)).ToList(); List <GhostWall> walls = new List <GhostWall>(); foreach (Element w in revit_walls) { if (w.getP("Помещение") != null & w.getP("Помещение") != "") { walls.Add(new GhostWall(w, null)); } } foreach (string i in rooms.Select(x => x.Floor).Distinct()) { } using (Transaction tr = new Transaction(doc, "Otdelka")) { tr.Start(); foreach (GhostRoom r in rooms) { r.Commit(); } tr.Commit(); } return(Result.Succeeded); }