public IList <FamilyInstance> FindConn(Document doc, FamilyInstance instance) { IList <FamilyInstance> list = new List <FamilyInstance>(); var Frame = doc.GetElement((from x in instance.GetSubComponentIds() where doc.GetElement(x).Name.Contains("Frame") select x).First()) as FamilyInstance; List <FamilyInstance> source = new List <FamilyInstance>(); foreach (var i in Frame.GetSubComponentIds()) { FamilyInstance gh = doc.GetElement(i) as FamilyInstance; source.Add(gh); } foreach (FamilyInstance familyInstance in source) { BoundingBoxXYZ boundingBoxXYZ = familyInstance.get_BoundingBox(doc.ActiveView); Outline outline = new Outline(boundingBoxXYZ.Min, boundingBoxXYZ.Max); BoundingBoxIntersectsFilter filter = new BoundingBoxIntersectsFilter(outline); BoundingBoxIsInsideFilter filter2 = new BoundingBoxIsInsideFilter(outline); LogicalOrFilter filter3 = new LogicalOrFilter(filter, filter2); FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc, doc.ActiveView.Id); ICollection <ElementId> ids = filteredElementCollector.OfClass(typeof(FamilyInstance)).WherePasses(filter3).ToElementIds(); IList <Solid> list2 = this.AllSolids(familyInstance); List <ElementId> nestedIds = this.GetNestedIds(doc, ids); foreach (Solid solid in list2) { IList <FamilyInstance> fromList = this.IntersectPart(doc, solid, nestedIds); this.AddListFamilyInstance(fromList, list); } } return(list); }
internal static List <Element> GetInsideElements(Document doc, IEnumerable <Element> elementsToCheck, BoundingBoxXYZ boundingBoxXYZ) { ElementFilter _filter = new BoundingBoxIsInsideFilter(new Outline(boundingBoxXYZ.Min, boundingBoxXYZ.Max)); List <Element> _elements = new FilteredElementCollector(doc, elementsToCheck.Select(p => p.Id).ToList()) //.WhereElementIsNotElementType() //.WhereElementIsViewIndependent() .WherePasses(_filter).ToList(); return(_elements); }
private List <int> FindMass(AreaProperties ap) { List <int> massIds = new List <int>(); try { Outline outline = new Outline(minXYZ, maxXYZ); BoundingBoxIntersectsFilter intersectFilter = new BoundingBoxIntersectsFilter(outline); BoundingBoxIsInsideFilter insideFilter = new BoundingBoxIsInsideFilter(outline); LogicalOrFilter orFilter = new LogicalOrFilter(intersectFilter, insideFilter); FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfCategory(BuiltInCategory.OST_Mass); IList <Element> elements = collector.WherePasses(orFilter).ToElements(); foreach (Element element in elements) { #if RELEASE2015 || RELEASE2016 || RELEASE2017 Parameter parameter = element.LookupParameter("Building Function"); #else Parameter parameter = element.get_Parameter("Building Function"); #endif if (null != parameter) { MassProperties mp = new MassProperties(element); if (mp.GrossFloorArea != 0 && null != mp.Centroid) { if (null != ap.BaseFace.Project(mp.Centroid)) { mp.AreaId = ap.AreaId; mp.PlotCode = ap.PlotCode; mp.DistricCode = ap.DistricCode; if (!massDictionary.ContainsKey(mp.MassId)) { massDictionary.Add(mp.MassId, mp); } massIds.Add(mp.MassId); } } } } } catch (Exception ex) { MessageBox.Show("Failed to find mass instances within an area object.\n" + ex.Message, "FARCacalculator:FindMass", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(massIds); }
public IList <FamilyInstance> FindMemberForAssembly(Document doc, FamilyInstance familyInstance) { IList <FamilyInstance> list = new List <FamilyInstance>(); BoundingBoxXYZ boundingBoxXYZ = familyInstance.get_BoundingBox(doc.ActiveView); Outline outline = new Outline(boundingBoxXYZ.Min, boundingBoxXYZ.Max); BoundingBoxIntersectsFilter filter = new BoundingBoxIntersectsFilter(outline); BoundingBoxIsInsideFilter filter2 = new BoundingBoxIsInsideFilter(outline); LogicalOrFilter filter3 = new LogicalOrFilter(filter, filter2); FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc, doc.ActiveView.Id); ICollection <ElementId> ids = filteredElementCollector.OfClass(typeof(FamilyInstance)).WherePasses(filter3).ToElementIds(); IList <Solid> list2 = this.AllSolids(familyInstance); List <ElementId> nestedIds = this.GetNestedIds(doc, ids); foreach (Solid solid in list2) { IList <FamilyInstance> fromList = this.IntersectPart(doc, solid, nestedIds); this.AddListFamilyInstance(fromList, list); } return(list); }
internal static ICollection<ElementId> GetElementIdsInLayer(Document doc, Element host, bool bottomLayer) { RebarHostData hostData = RebarHostData.GetRebarHostData(host); ICollection<ElementId> rebarsInHost = hostData.GetRebarsInHost().Select(r => r.Id).ToList(); BoundingBoxXYZ box = host.get_BoundingBox(null); double midZ = 0.5 * (box.Max.Z + box.Min.Z); Outline outline; if (bottomLayer) { outline = new Outline(box.Min, new XYZ(box.Max.X, box.Max.Y, midZ)); } else { outline = new Outline(new XYZ(box.Min.X, box.Min.Y, midZ), box.Max); } BoundingBoxIsInsideFilter filter = new BoundingBoxIsInsideFilter(outline); FilteredElementCollector collector = new FilteredElementCollector(doc, rebarsInHost); return collector.WherePasses(filter).ToElementIds(); }
static internal IList <Element> GetElementsInLevelBounds(Document targetDoc, ElementId targetLevelId, double targetToleranceInCm, BuiltInCategory targetCategory) { Level targetLevel = targetDoc.GetElement(targetLevelId) as Level; double levelElevation = targetLevel.ProjectElevation; double minHeight = levelElevation - Utils.ConvertM.cmToFeet(targetToleranceInCm); double maxHeight = levelElevation + Utils.ConvertM.cmToFeet(targetToleranceInCm); XYZ minPoint = new XYZ(-999, -999, minHeight); XYZ maxPoint = new XYZ(999, 999, maxHeight); Outline targetOutline = new Outline(minPoint, maxPoint); BoundingBoxIntersectsFilter bbIntersect = new BoundingBoxIntersectsFilter(targetOutline); BoundingBoxIsInsideFilter bbInside = new BoundingBoxIsInsideFilter(targetOutline); LogicalOrFilter orFilter = new LogicalOrFilter(bbInside, bbIntersect); IList <Element> elementsToReturn = new FilteredElementCollector(targetDoc).OfCategory(targetCategory).WherePasses(orFilter).WhereElementIsNotElementType().ToList(); return(elementsToReturn); }
private static Result createVisualizationSheets(UIDocument uiDoc, BuildingLoadModel buildingLoadModel, IEnumerable <ILoadModel> levelLiveLoadPerSquareFoots) { //Setup Document _doc = uiDoc.Document; double _concreteDensityPoundsForcePerCubicFoot = 153.0; XYZ _capacityViewCoordinate = new XYZ(2.17649771769026, 0.766954561856788, 0); XYZ _combinedViewCoordinate = new XYZ(0.780872717690263, 0.766954561856788, 0); XYZ _demandViewCoordinate = new XYZ(0.780872717690263, 1.83481042377296, 0); var _levels = Getters.GetLevels(_doc).OrderByDescending(p => p.Elevation).ToList(); var _floors = Getters.GetFloors(_doc).OrderBy(p => p.get_BoundingBox(null)?.Max.Z).ToList(); var _structuralColumns = new FilteredElementCollector(_doc).OfCategory(BuiltInCategory.OST_StructuralColumns).OfType <FamilyInstance>().OrderBy(p => p.get_BoundingBox(null)?.Max.Z).ToList(); var _structuralFraming = new FilteredElementCollector(_doc).OfCategory(BuiltInCategory.OST_StructuralFraming).OfType <FamilyInstance>().OrderBy(p => p.get_BoundingBox(null)?.Max.Z).ToList(); var _walls = new FilteredElementCollector(_doc).OfClass(typeof(Wall)).OfType <Wall>().OrderBy(p => p.get_BoundingBox(null)?.Max.Z).ToList(); BoundingBoxXYZ _modelExtents = GeometryHelpers.GetElementsBBox( new FilteredElementCollector(_doc).WhereElementIsViewIndependent().WhereElementIsNotElementType().ToList()); _modelExtents.Min = new XYZ(_modelExtents.Min.X, _modelExtents.Min.Y, _levels.LastOrDefault().Elevation - 1.0); Category _directShapeCategory = Category.GetCategory(_doc, BuiltInCategory.OST_GenericModel); Level _levelAbove = null; Level _bottomLevel = _levels.LastOrDefault(); Level _topLevel = _levels.FirstOrDefault(); //Begin to generate our VisualizationDeliverables - these are sheets with 3 plan-orientation isometric views. // NOTE - isometric views were used so that semi-transparent color overrides can be overlayed over each other to represent demands vs capacities // ToDo: it would be valuable to scale transparency by percentage of overall demand/capacity List <VisualizationDeliverable> _visualizationDeliverables = new List <VisualizationDeliverable>(); foreach (Level _level in _levels) { if (_levelAbove == null) { _levelAbove = _level; } //Get the elements that are on our current Level List <Floor> _currentLevelFloors = _floors.Where(p => p.LevelId == _level.Id).ToList(); List <FamilyInstance> _currentLevelStructuralColumns = new List <FamilyInstance>(); List <FamilyInstance> _currentLevelStructuralFraming = new List <FamilyInstance>(); List <Wall> _currentLevelWalls = new List <Wall>(); BoundingBoxXYZ _levelBounds = new BoundingBoxXYZ { Min = new XYZ(_modelExtents.Min.X, _modelExtents.Min.Y, _level.Elevation), Max = new XYZ(_modelExtents.Max.X, _modelExtents.Max.Y, _levelAbove.Elevation) }; BoundingBoxIsInsideFilter _withinLevelBoundsFilter = new BoundingBoxIsInsideFilter(new Outline(_levelBounds.Min, _levelBounds.Max)); BoundingBoxIntersectsFilter _intersectsLevelBoundsFilter = new BoundingBoxIntersectsFilter(new Outline(_levelBounds.Min, _levelBounds.Max)); if (_structuralColumns.Count > 0) { _currentLevelStructuralColumns = new FilteredElementCollector(_doc, _structuralColumns.Select(p => p.Id).ToList()).WherePasses(_intersectsLevelBoundsFilter).OfType <FamilyInstance>().ToList(); } else { _currentLevelStructuralColumns = new List <FamilyInstance>(); } if (_structuralFraming.Count > 0) { _currentLevelStructuralFraming = new FilteredElementCollector(_doc, _structuralFraming.Select(p => p.Id).ToList()).WherePasses(_withinLevelBoundsFilter).OfType <FamilyInstance>().ToList(); } else { _currentLevelStructuralFraming = new List <FamilyInstance>(); } if (_walls.Count > 0) { _currentLevelWalls = new FilteredElementCollector(_doc, _walls.Select(p => p.Id).ToList()).WherePasses(_withinLevelBoundsFilter).OfType <Wall>().ToList(); } else { _currentLevelWalls = new List <Wall>(); } //Generate LoadModels to populate a full LevelLoadModel LevelLoadModel _currentLevelLoadModel = LevelLoadModel.Create(_level); foreach (Floor _floor in _currentLevelFloors) { //The "top" floor is where the initial Demand is determined, which is to be supported via reshores propagating down through the building //ToDo: it would be valuable to be able to pick which Level to start from if (_level.Id == _topLevel.Id) { Parameter _floorThicknessParameter = _floor.get_Parameter(BuiltInParameter.FLOOR_ATTR_THICKNESS_PARAM); double _floorThickness = _floorThicknessParameter == null ? 0.0 : _floorThicknessParameter.AsDouble(); _currentLevelLoadModel.addFloorDemandLoadModel(_floor, _concreteDensityPoundsForcePerCubicFoot * _floorThickness); } //Add loads from other sources that are also distributed evenly along a level ILoadModel _floorCapacityLoadModel = levelLiveLoadPerSquareFoots.FirstOrDefault(p => p.Name == _level.Name); if (_floorCapacityLoadModel == null) { continue; } List <LoadModel> _floorLoadModels = _currentLevelLoadModel.addFloorCapacityLoadModel(_floor, _floorCapacityLoadModel.PoundsForcePerSquareFoot); foreach (ILoadModel _loadModel in levelLiveLoadPerSquareFoots.Where(p => p.Name.Equals(_level.Name))) { List <ILoadModel> _otherLoadModels = new List <ILoadModel>(); foreach (LoadModel _floorLoadModel in _floorLoadModels) { LoadModel _otherLoadModel = LoadModel.Create(); _otherLoadModel.Name = _loadModel.Name; _otherLoadModel.LoadType = _loadModel.LoadType; _otherLoadModel.PoundsForcePerSquareFoot = _loadModel.PoundsForcePerSquareFoot; _otherLoadModel.AreaSquareFeetXY = _floorLoadModel.AreaSquareFeetXY; _otherLoadModel.HeightFeetZ = _floorLoadModel.HeightFeetZ; _otherLoadModel.OriginXFeet = _floorLoadModel.OriginXFeet; _otherLoadModel.OriginYFeet = _floorLoadModel.OriginYFeet; _otherLoadModel.Curves = _floorLoadModel.Curves; _otherLoadModel.PlanarFace = _floorLoadModel.PlanarFace; _otherLoadModel.Element = _floorLoadModel.Element; _currentLevelLoadModel.addLoadModel(_otherLoadModel); } } } foreach (FamilyInstance _structuralColumn in _currentLevelStructuralColumns) { _currentLevelLoadModel.addFamilyInstanceLoadModel(_structuralColumn, LoadType.Demand, buildingLoadModel.StructuralColumnWeightPerSquareFoot); _currentLevelLoadModel.addFamilyInstanceLoadModel(_structuralColumn, LoadType.Capacity, buildingLoadModel.StructuralColumnWeightPerSquareFoot); } foreach (FamilyInstance _structuralFrame in _currentLevelStructuralFraming) { _currentLevelLoadModel.addFamilyInstanceLoadModel(_structuralFrame, LoadType.Demand, buildingLoadModel.StructuralBeamWeightPerSquareFoot); } foreach (Wall _wall in _currentLevelWalls) { _currentLevelLoadModel.addWallLoadModel(_wall, LoadType.Demand, buildingLoadModel.StructuralWallWeightPerSquareFoot); _currentLevelLoadModel.addWallLoadModel(_wall, LoadType.Capacity, buildingLoadModel.StructuralWallWeightPerSquareFoot); } //Set the Solid elements that we will project through the building, to represent demands/capacities LoadModel.SetSolids(_currentLevelLoadModel.LoadModels.OfType <LoadModel>(), _level, _topLevel, _bottomLevel); VisualizationDeliverable _visualizationDeliverable = new VisualizationDeliverable(_currentLevelLoadModel) { Floors = _currentLevelFloors, StructuralColumns = _currentLevelStructuralColumns, StructuralFraming = _currentLevelStructuralFraming, Walls = _currentLevelWalls, }; _visualizationDeliverables.Add(_visualizationDeliverable); _levelAbove = _level; } //Now that we've gathered all of our LoadModels, let's read the data about their actual demands/capacities buildingLoadModel.LevelLoadModels = _visualizationDeliverables.Select(p => p.LevelLoadModel as ILevelLoadModel).Where(p => p != null).ToList(); buildingLoadModel.ReadLoads(); foreach (LoadModel _loadModel in _visualizationDeliverables.Select(p => p.LevelLoadModel).SelectMany(p => p.LoadModels)) { _loadModel.SetDirectShapeWithParameters(_doc, _directShapeCategory.Id, _loadModel.Name); } //Update Levels in the model with Load details foreach (LevelLoadModel _levelLoadModel in _visualizationDeliverables.Select(p => p.LevelLoadModel)) { _levelLoadModel.SetLevelParameters(); } //Color our active View for the visualization colorActiveView(_doc, _visualizationDeliverables); //ToDo: something happened which broke colors being correctly applied to these sheets - will need to sort this out //createSheetsAndViews(_doc, _visualizationDeliverables, _modelExtents); // //colorViews(_doc, _visualizationDeliverables); // //createViewports(_doc, _visualizationDeliverables, _capacityViewCoordinate, _combinedViewCoordinate, _demandViewCoordinate); return(Result.Succeeded); }
private List <Element> FindRevitElements(ParameterMapProperties pmp, SpatialElementProperties sep) { List <Element> revitElements = new List <Element>(); try { BoundingBoxXYZ boundingBox = null; Room room = null; Space space = null; if (sep.CategoryId == (int)BuiltInCategory.OST_Rooms) { room = sep.ElementObj as Room; boundingBox = room.get_BoundingBox(null); } else if (sep.CategoryId == (int)BuiltInCategory.OST_MEPSpaces) { space = sep.ElementObj as Space; boundingBox = space.get_BoundingBox(null); } if (null != boundingBox) { XYZ minXYZ = boundingBox.Min; XYZ maxXYZ = boundingBox.Max; if (sep.IsLinked && null != sep.LinkProperties) { minXYZ = sep.LinkProperties.TransformValue.OfPoint(minXYZ); maxXYZ = sep.LinkProperties.TransformValue.OfPoint(maxXYZ); } //bounding box quick filter Outline outline = new Outline(minXYZ, maxXYZ); BoundingBoxIntersectsFilter intersectFilter = new BoundingBoxIntersectsFilter(outline); BoundingBoxIsInsideFilter insideFilter = new BoundingBoxIsInsideFilter(outline); LogicalOrFilter orFilter = new LogicalOrFilter(intersectFilter, insideFilter); FilteredElementCollector collector = new FilteredElementCollector(m_doc); List <Element> elements = collector.OfCategoryId(pmp.RevitCategory.CategoryObj.Id).WherePasses(orFilter).ToElements().ToList(); if (checkBoxIntersect.IsChecked == true) { revitElements.AddRange(elements); } else { //slow solid filter if (elements.Count > 0) { foreach (Element element in elements) { LocationPoint locationPt = element.Location as LocationPoint; if (null != locationPt) { XYZ point = locationPt.Point; if (sep.IsLinked && null != sep.LinkProperties) { point = sep.LinkProperties.TransformValue.Inverse.OfPoint(point); } if (null != room) { if (room.IsPointInRoom(point)) { revitElements.Add(element); } } else if (null != space) { if (space.IsPointInSpace(point)) { revitElements.Add(element); } } } LocationCurve locationCurve = element.Location as LocationCurve; if (null != locationCurve) { Curve curve = locationCurve.Curve; XYZ firstPt = curve.GetEndPoint(0); XYZ secondPt = curve.GetEndPoint(1); XYZ centerPt = curve.Evaluate(0.5, true); if (sep.IsLinked && null != sep.LinkProperties) { firstPt = sep.LinkProperties.TransformValue.Inverse.OfPoint(firstPt); secondPt = sep.LinkProperties.TransformValue.Inverse.OfPoint(secondPt); } if (null != room) { //modification: pick centroid if (room.IsPointInRoom(centerPt)) { revitElements.Add(element); } /* * if (room.IsPointInRoom(firstPt) || room.IsPointInRoom(secondPt)) * { * revitElements.Add(element); * }*/ } else if (null != space) { if (space.IsPointInSpace(centerPt)) { revitElements.Add(element); } } } } } } } } catch (Exception ex) { errorMessages.AppendLine("Cannot find model elements from - " + sep.ElementObj.Number + " : " + sep.ElementObj.Name); errorMessages.AppendLine(ex.Message); } return(revitElements); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="dataAccess"> /// The DA object is used to retrieve from inputs and store in outputs. /// </param> protected override void SolveInstance(IGH_DataAccess dataAccess) { int index = -1; bool run = false; index = Params.IndexOfInputParam("_run"); if (index != -1) { if (!dataAccess.GetData(index, ref run) || !run) { return; } } GH_ObjectWrapper objectWrapper = null; index = Params.IndexOfInputParam("revitLinkInstance_"); if (index != -1) { dataAccess.GetData(index, ref objectWrapper); } Transform tranform = null; Document document = null; if (objectWrapper != null && Core.Grasshopper.Revit.Query.TryGetElement(objectWrapper, out RevitLinkInstance revitLinkInstance) && revitLinkInstance != null) { document = revitLinkInstance.GetLinkDocument(); tranform = revitLinkInstance.GetTotalTransform(); } else if (objectWrapper?.Value is RhinoInside.Revit.GH.Types.ProjectDocument) { document = ((RhinoInside.Revit.GH.Types.ProjectDocument)objectWrapper.Value).Value; } if (document == null) { document = RhinoInside.Revit.Revit.ActiveDBDocument; } if (document == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data"); return; } if (tranform == null) { tranform = Transform.Identity; } index = Params.IndexOfInputParam("_view"); if (index == -1 || !dataAccess.GetData(index, ref objectWrapper) || objectWrapper.Value == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data"); return; } IEnumerable <ElementId> elementIds = null; if (Core.Grasshopper.Revit.Query.TryGetElement(objectWrapper, out ViewPlan viewPlan)) { Outline outline = Core.Revit.Query.Outline(viewPlan, tranform); if (outline != null) { //LogicalOrFilter logicalOrFilter = new LogicalOrFilter(new BoundingBoxIsInsideFilter(outline), new BoundingBoxIntersectsFilter(outline)); //elementIds = new FilteredElementCollector(document_Linked).WherePasses(logicalOrFilter)?.ToElementIds(); BoundingBoxIsInsideFilter boundingBoxIsInsideFilter = new BoundingBoxIsInsideFilter(outline, Core.Tolerance.MacroDistance); elementIds = new FilteredElementCollector(document).WherePasses(boundingBoxIsInsideFilter).ToElementIds(); } } if (elementIds == null || elementIds.Count() == 0) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data"); return; } ConvertSettings convertSettings = new ConvertSettings(true, true, true); IEnumerable <Core.ISAMObject> sAMObjects = null; List <Panel> panels = Analytical.Revit.Convert.ToSAM_Panels(document, elementIds, convertSettings); if (panels != null) { sAMObjects = panels.Cast <Core.ISAMObject>(); } dataAccess.SetDataList(0, sAMObjects); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //Get application and document objects UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; using (PSDOptions_form inputForm = new PSDOptions_form()) { inputForm.ShowDialog(); if (inputForm.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return(Result.Cancelled); } if (inputForm.DialogResult == System.Windows.Forms.DialogResult.OK) { if (inputForm.isStructural == true) { StructSelected = true; } else { StructSelected = false; } } } //check to see if the PSD titleblock is in the current document. FilteredElementCollector titleblockCollector = new FilteredElementCollector(doc).OfClass(typeof(Family)); Family family = titleblockCollector.FirstOrDefault <Element>(e => e.Name.Equals(titleBlock)) as Family; string FamilyPath = @"C:\ProgramData\Autodesk\Revit\Addins\2016\KrahnTools\PSDCreator\" + titleBlock; //if the titleblock doesn't exist in the current document, it is imported. if (null == family) { // It is not present, so check for the file to load it from: if (!File.Exists(FamilyPath)) { TaskDialog.Show("Error", "The PSD Template is missing from the addins folder."); return(Result.Failed); } using (Transaction t = new Transaction(doc)) { t.Start("Load Titleblock"); doc.LoadFamily(FamilyPath, out family); t.Commit(); } } //makes sure the correct view templates have been created in the project. FilteredElementCollector viewTemplateCollector = new FilteredElementCollector(doc).OfClass(typeof(View)); View embedtitleblock = viewTemplateCollector.FirstOrDefault <Element>(e => e.Name.Equals(geometryViewTemplate)) as View; View rebartitleblock = viewTemplateCollector.FirstOrDefault <Element>(e => e.Name.Equals(rebarViewTemplate)) as View; //if they don't exist in the project, warning is shown and application is terminated if ((embedtitleblock == null || rebartitleblock == null)) { TaskDialog.Show("Error", "You are missing the required PSD view templates, please add them to continue"); return(Result.Failed); } while (true) { Reference myRef = null; try { //Prompts the user to select a wall (and only a wall) using the MySelectionFilter Class created below myRef = uidoc.Selection.PickObject(ObjectType.Element, new MySelectionFilter("Walls"), "Select a wall"); //myRef = uidoc.Selection.PickObject(ObjectType.Face, new MySelectionFilter("Walls"), "Select a Wall"); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { //this exception is called when the user presses the escape key. It is handled, ignored and the addin is terminated. return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.ArgumentOutOfRangeException) { } if (myRef == null) { return(Result.Succeeded); } //Creates an element e from the selected object reference -- this will be the wall element Element e = doc.GetElement(myRef); View sectionView = CreateViewAndSectionMark(uidoc, e); //get the mark parameter and set it to the panel number variable if (e.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString() == null) { TaskDialog.Show("No Panel Number", "Selected Panel does not have a Type Mark (Panel Number).\nPlease ensure all panels are numbered prior to creating PSD views."); return(Result.Failed); } else { panelNumber = e.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString(); } //duplicate the active view using the the DuplicateViewEmbeds Function created below View Embedview = SetupViewEmbeds(doc, panelNumber, sectionView); //Creates a selection filter to dump objects in for later selection ICollection <ElementId> selSet = new List <ElementId>(); //Gets the bounding box of the selected wall element picked above BoundingBoxXYZ bb = e.get_BoundingBox(Embedview); //adds a buffer to the bounding box to ensure all elements are contained within the box XYZ buffer = new XYZ(0.1, 0.1, 0.1); //creates an ouline based on the boundingbox corners of the panel and adds the buffer Outline outline = new Outline(bb.Min - buffer, bb.Max + buffer); //filters the selection by the bounding box of the selected object //the "true" statement inverts the selection and selects all other objects BoundingBoxIsInsideFilter bbfilter = new BoundingBoxIsInsideFilter(outline, true); //creates a new filtered element collector that filters by the active view settings FilteredElementCollector collector = new FilteredElementCollector(doc, Embedview.Id); //collects all objects that pass through the requirements of the bbfilter collector.WherePasses(bbfilter); //adds each element that passed the bbfilter to the current selection collector //also checks to see if the element can be hidden. if it can't, it appents it to the failedtohide string foreach (Element el in collector) { if (el.CanBeHidden(Embedview) == true) { selSet.Add(el.Id); } } ICollection <BuiltInCategory> bcat = new List <BuiltInCategory>(); //add all levels and grids to filter -- these are filtered out by the viewtemplate, but are nice to have bcat.Add(BuiltInCategory.OST_Levels); bcat.Add(BuiltInCategory.OST_Grids); //this removes the dimesnsions from the current selection, currently turned off because //dimensions changes the size of the viewport which makes it difficult to place on sheet. //bcat.Add(BuiltInCategory.OST_Dimensions); //create new multi category filter ElementMulticategoryFilter multiCatFilter = new ElementMulticategoryFilter(bcat); //create new filtered element collector, add the passing levels and grids, then remove them from the selection foreach (Element el in new FilteredElementCollector(doc) .WherePasses(multiCatFilter)) { selSet.Remove(el.Id); } //makes the selection of the current selection collector, doesn't need to be done as we can hide directly from the creates list //uidoc.Selection.SetElementIds(selSet); using (Transaction t = new Transaction(doc, "Hide Elements")) { t.Start(); Embedview.HideElements(selSet); //DOESN'T WORK BECAUSE THESE SET NUMBERS ARE BASED ON WHERE THE ELEVATION IS PLACED //IN PLAN VIEW....CAN'T RELATE THIS LOCATION TO THE PANEL LOCATION. //MAYBE PLACE NEW ELEVATION VIEW AT CENTER OF PANEL? //view.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_LEFT).Set(-15); //DISTANCE FROM EL TAG IN PLAN //view.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_RIGHT).Set(15); t.Commit(); } try { TagElement(uidoc, myRef, Embedview); //creates a new PSD sheet ViewSheet PSDsheet = CreatePSDSheet(doc, panelNumber); //place view on PSDsheet PlaceOnSheet(doc, PSDsheet, Embedview); //creates rebar view View rebarView = DuplicateViewRebar(doc, panelNumber, Embedview); //place rebar view on PSDsheet PlaceOnSheet(doc, PSDsheet, rebarView); //display a message ox indicating success TaskDialog.Show("PSD Created", "PSD for Panel: " + panelNumber + "created sucessfully.\nSelect another panel or hti escape to quit."); } catch { TaskDialog.Show("Error", "Revit Encountered an Error. Sheet probably already exists."); return(Result.Failed); } } }//end Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
private bool CopyLinkedRoomData(List <FamilyInstance> doorInstances) { bool result = true; try { Dictionary <int, LinkedInstanceProperties> linkedInstanceDictionary = CollectLinkedInstances(); StringBuilder strBuilder = new StringBuilder(); using (TransactionGroup tg = new TransactionGroup(m_doc, "Set Door Parameters")) { tg.Start(); try { foreach (FamilyInstance door in doorInstances) { using (Transaction trans = new Transaction(m_doc, "Set Parameter")) { trans.Start(); try { DoorProperties dp = new DoorProperties(door); if (null != dp.FromPoint && null != dp.ToPoint) { GeometryElement geomElem = door.get_Geometry(new Options()); XYZ direction = door.FacingOrientation; Dictionary <int, LinkedRoomProperties> linkedRooms = new Dictionary <int, LinkedRoomProperties>(); foreach (LinkedInstanceProperties lip in linkedInstanceDictionary.Values) { GeometryElement trnasformedElem = geomElem.GetTransformed(lip.TransformValue.Inverse); BoundingBoxXYZ bb = trnasformedElem.GetBoundingBox(); //extended bounding box XYZ midPt = 0.5 * (bb.Min + bb.Max); XYZ extMin = bb.Min + (bb.Min - midPt).Normalize(); XYZ extMax = bb.Max + (bb.Max - midPt).Normalize(); Outline outline = new Outline(extMin, extMax); BoundingBoxIntersectsFilter bbIntersectFilter = new BoundingBoxIntersectsFilter(outline); BoundingBoxIsInsideFilter bbInsideFilter = new BoundingBoxIsInsideFilter(outline); LogicalOrFilter orFilter = new LogicalOrFilter(bbIntersectFilter, bbInsideFilter); FilteredElementCollector collector = new FilteredElementCollector(lip.LinkedDocument); List <Room> roomList = collector.OfCategory(BuiltInCategory.OST_Rooms).WherePasses(orFilter).WhereElementIsNotElementType().ToElements().Cast <Room>().ToList(); if (roomList.Count > 0) { foreach (Room room in roomList) { LinkedRoomProperties lrp = new LinkedRoomProperties(room); lrp.LinkedInstance = lip; if (!linkedRooms.ContainsKey(lrp.RoomId)) { linkedRooms.Add(lrp.RoomId, lrp); } } } } LinkedRoomProperties fromRoom = null; LinkedRoomProperties toRoom = null; if (linkedRooms.Count > 0) { foreach (LinkedRoomProperties lrp in linkedRooms.Values) { XYZ tFrom = lrp.LinkedInstance.TransformValue.Inverse.OfPoint(dp.FromPoint); XYZ tTo = lrp.LinkedInstance.TransformValue.Inverse.OfPoint(dp.ToPoint); if (lrp.RoomObject.IsPointInRoom(tFrom)) { dp.FromRoom = lrp.RoomObject; fromRoom = lrp; } if (lrp.RoomObject.IsPointInRoom(tTo)) { dp.ToRoom = lrp.RoomObject; toRoom = lrp; } } } if (null != fromRoom) { Parameter fParam = door.LookupParameter(fromRoomNumber); if (null != fParam) { fParam.Set(fromRoom.RoomNumber); } fParam = door.LookupParameter(fromRoomName); if (null != fParam) { fParam.Set(fromRoom.RoomName); } } if (null != toRoom) { Parameter tParam = door.LookupParameter(toRoomNumber); if (null != tParam) { tParam.Set(toRoom.RoomNumber); } tParam = door.LookupParameter(toRoomName); if (null != tParam) { tParam.Set(toRoom.RoomName); } } if (!doorDictionary.ContainsKey(dp.DoorId)) { doorDictionary.Add(dp.DoorId, dp); } } trans.Commit(); } catch (Exception ex) { trans.RollBack(); string message = ex.Message; result = false; strBuilder.AppendLine(door.Id.IntegerValue + "\t" + door.Name + ": " + ex.Message); } } } tg.Assimilate(); } catch (Exception ex) { tg.RollBack(); string message = ex.Message; } if (strBuilder.Length > 0) { MessageBox.Show("The following doors have been skipped due to some issues.\n\n" + strBuilder.ToString(), "Skipped Door Elements", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } catch (Exception ex) { MessageBox.Show("Failed to collect door data.\n" + ex.Message, "Collect Door Data", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(result); }
public void LEED() { // Get the current Document Document curDoc = this.Application.ActiveUIDocument.Document; //Get the current View View curView = this.Application.ActiveUIDocument.Document.ActiveView; BoundingBoxXYZ curViewBoundary = curView.CropBox; //View3D curView = this.Application.ActiveUIDocument.Document.ActiveView; FilteredElementCollector viewCollector = new FilteredElementCollector(curDoc); viewCollector.OfClass(typeof(View3D)); List <View3D> view3dList = viewCollector.ToElements().Cast <View3D>().Where(x => x.IsTemplate == false).ToList(); //TaskDialog.Show("test", view3dList.First().ViewName.ToString()); //Build eyeLevel and eyeLevel sketchplane double eyeLevel = 5; XYZ eyeNormal = new XYZ(0, 0, 1); XYZ xAxis = new XYZ(1, 0, 0); XYZ yAxis = new XYZ(0, 1, 0); //Isovist variables int numRays = 600; double isoRadius = 300; double isoStartAngle = 0; double isoEndAngle = 360; //Convert to radians double radIsoStartAngle = (Math.PI / 180) * isoStartAngle; double radIsoEndAngle = (Math.PI / 180) * isoEndAngle; //Get all walls FilteredElementCollector wallCollector = new FilteredElementCollector(curDoc, curView.Id); wallCollector.OfCategory(BuiltInCategory.OST_Walls); //Get all stacked walls FilteredElementCollector stackedWallCollector = new FilteredElementCollector(curDoc, curView.Id); stackedWallCollector.OfCategory(BuiltInCategory.OST_StackedWalls); stackedWallCollector.UnionWith(wallCollector).WhereElementIsNotElementType(); //TaskDialog.Show("Test", stackedWallCollector.Count().ToString() + " Walls"); List <Face> wallFaces = new List <Face>(); double totalArea = 0; List <Solid> wallSolids = new List <Solid>(); foreach (Element curWall in stackedWallCollector) { Options opt = new Options(); GeometryElement geomElem = curWall.get_Geometry(opt); foreach (GeometryObject geomObj in geomElem) { Solid geomSolid = geomObj as Solid; wallSolids.Add(geomSolid); if (null != geomSolid) { foreach (Face geomFace in geomSolid.Faces) { totalArea += geomFace.Area; wallFaces.Add(geomFace); } } } } //TaskDialog.Show("test", wallFaces.Count().ToString() + " Faces"); //Determine All Defaults for stuff later ElementId defaultView3d = curDoc.GetDefaultElementTypeId(ElementTypeGroup.ViewType3D); ElementId defaultTxtId = curDoc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType); ElementId defaultFRId = curDoc.GetDefaultElementTypeId(ElementTypeGroup.FilledRegionType); //Create View Boundary filter for roomCollector Outline outline = new Outline(new XYZ(curViewBoundary.Min.X, curViewBoundary.Min.Y, -100), new XYZ(curViewBoundary.Max.X, curViewBoundary.Max.Y, 100)); BoundingBoxIsInsideFilter bbFilter = new BoundingBoxIsInsideFilter(outline); //FilteredElementCollector roomList = roomCollector.WherePasses(bbFilter); // Get all rooms; Divide into point grid; Return points in curPointList RoomFilter filter = new RoomFilter(); FilteredElementCollector roomCollector = new FilteredElementCollector(curDoc, curView.Id); roomCollector.WherePasses(filter).WherePasses(bbFilter); TaskDialog.Show("Magic View Region Drawing Machine", "Be sure to set the crop region around the rooms you would like to test, encompassing at least one exterior wall and all bounding elements." + "Only rooms located fully within the bounds of the view range will be calculated."); TaskDialog.Show("Magic View Region Drawing Machine", roomCollector.Count().ToString() + " rooms fully visible in current view. The more rooms you run, the longer this will take!"); Transaction t = new Transaction(curDoc, "Draw Some Lines"); t.Start(); View3D curView3d = View3D.CreateIsometric(curDoc, defaultView3d); IEnumerable <Element> extWalls = GetExteriorWalls(curDoc, curView); //TaskDialog.Show("test", extWalls.Count().ToString() +" Exterior Walls"); List <XYZ> somePoints = new List <XYZ>(); foreach (Element wall in extWalls) { List <XYZ> pointsList = new List <XYZ>(); pointsList = GetWallOpenings(wall, eyeLevel, curView3d); somePoints.AddRange(pointsList); } //TaskDialog.Show("test", somePoints.Count.ToString()+" points"); List <List <Curve> > viewCones = new List <List <Curve> >(); foreach (XYZ curPoint in somePoints) { Plane eyePlane = Plane.CreateByNormalAndOrigin(eyeNormal, curPoint); SketchPlane eyeSketchPlane = SketchPlane.Create(curDoc, eyePlane); //Arc arc = Arc.Create(curPoint, 2, 0, 360, xAxis, yAxis); //ModelCurve newArc = curDoc.Create.NewModelCurve(arc, eyeSketchPlane); List <Curve> outLineList = createIsovist(curPoint, numRays, isoRadius, radIsoStartAngle, radIsoEndAngle, curView, curDoc, eyeSketchPlane, wallFaces, defaultFRId); viewCones.Add(outLineList); } //Convert to polygons in int values Polygons polys = GetBoundaryLoops(viewCones); //TaskDialog.Show("test", polys.Count.ToString()+ " Polygons"); //Calculate Intersection Polygons union = new Polygons(); Clipper c = new Clipper(); c.AddPath(polys[0], PolyType.ptSubject, true); for (int i = 1; i < polys.Count - 1; i++) { c.AddPath(polys[i], PolyType.ptClip, true); } c.Execute(ClipType.ctUnion, union, PolyFillType.pftPositive); /* * * TaskDialog.Show("test", union.Count.ToString()+ " Polygons"); * * if (0 < union.Count) * { * List<CurveLoop>regionLoops = new List<CurveLoop>(); * * for (int p = 0; p < union.Count -1; p++) * { * List<Curve> unionLineList = new List<Curve>(); * Polygon poly = union[p]; * * for (int i = 1; i <= poly.Count-1; i++) * { * unionLineList.Add(Line.CreateBound(GetXyzPoint(poly[i-1]), GetXyzPoint(poly[i]))); * * } * unionLineList.Add(Line.CreateBound(GetXyzPoint(poly[poly.Count-1]), GetXyzPoint(poly[0]))); * * CurveLoop regionLoop = CurveLoop.Create(unionLineList); * * regionLoops.Add(regionLoop); * * } * * FilledRegion region = FilledRegion.Create(curDoc, defaultFRId, curView.Id, regionLoops); * * * } */ foreach (Room curRoom in roomCollector) { SpatialElementBoundaryOptions bo = new SpatialElementBoundaryOptions(); List <Curve> roomCurves = new List <Curve>(); foreach (List <BoundarySegment> lstBs in curRoom.GetBoundarySegments(bo)) { foreach (BoundarySegment bs in lstBs) { roomCurves.Add(bs.GetCurve()); } } XYZ sketchPoint = new XYZ(0, 0, 0); Plane eyePlane = Plane.CreateByNormalAndOrigin(eyeNormal, sketchPoint); SketchPlane eyeSketchPlane = SketchPlane.Create(curDoc, eyePlane); List <List <Curve> > roomLoops = new List <List <Curve> >(); roomLoops.Add(roomCurves); //Convert to polygon in int values Polygon roomPoly = GetBoundaryLoop(roomCurves); //Calculate Intersection Polygons intersection = new Polygons(); Clipper c2 = new Clipper(); c2.AddPath(roomPoly, PolyType.ptClip, true); c2.AddPaths(union, PolyType.ptSubject, true); c2.Execute(ClipType.ctIntersection, intersection, PolyFillType.pftPositive); //TaskDialog.Show("test", intersection.Count.ToString()); if (0 < intersection.Count) { List <CurveLoop> regionLoops = new List <CurveLoop>(); List <Curve> intersectionLineList = new List <Curve>(); Polygon poly = intersection[0]; IntPoint?p0 = null; IntPoint?p = null; foreach (IntPoint q in poly) { if (null == p0) { p0 = q; } if (null != p) { intersectionLineList.Add(Line.CreateBound(GetXyzPoint(p.Value), GetXyzPoint(q))); } p = q; } intersectionLineList.Add(Line.CreateBound(GetXyzPoint(poly[poly.Count - 1]), GetXyzPoint(poly[0]))); foreach (Curve cur in intersectionLineList) { //ModelCurve newArc = curDoc.Create.NewModelCurve(cur, eyeSketchPlane); } CurveLoop regionLoop = CurveLoop.Create(intersectionLineList); regionLoops.Add(regionLoop); //TaskDialog.Show("test", intersectionLineList.Count.ToString()); FilledRegion region = FilledRegion.Create(curDoc, defaultFRId, curView.Id, regionLoops); } } t.Commit(); TaskDialog.Show("Magic View Region Drawing Machine", "Always double check the results, sometimes walls are missed. Tip: Curtain wall is prone to gliches and watch your door openings... Enjoy!"); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Add an EventLogTraceListener object System.Diagnostics.Trace.Listeners.Add( new System.Diagnostics.EventLogTraceListener("Application")); // Lay the hands on the active document UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; // Set up a timer Timing myTimer = new Timing(); myTimer.StartTime(); StringBuilder strBld = new StringBuilder(); try { // Check the active view Level curLvl = doc.ActiveView.GenLevel; if (curLvl == null) { TaskDialog.Show("Execption", "Add-in only operates in Floor Plans!"); return(Result.Failed); } // Take care of the shared parameters if (!CheckNessarySharedParameters(doc)) { TaskDialog.Show("Exception", "Necessary parameters do not exit!"); return(Result.Failed); } // Get scope boxes IList <Element> boxes = GetScopeBoxes(doc); // Ensure that both, rooms and boxes, are present if (boxes.Count == 0) { TaskDialog.Show("Execption", "No scope box!"); return(Result.Failed); } // Generate level name string lvlName = GenLvlName(doc); // Pull in all rooms intersected by each scope box // and get their parameters set for (int i = 0; i < boxes.Count; ++i) { BoundingBoxXYZ boundingBox = boxes[i].get_BoundingBox(doc.ActiveView); Outline outline = new Outline(boundingBox.Min, boundingBox.Max); BoundingBoxIsInsideFilter insideBndBoxFltr = new BoundingBoxIsInsideFilter(outline); RoomFilter roomFltr = new RoomFilter(); LogicalAndFilter roomAndIntersectBndBox = new LogicalAndFilter(insideBndBoxFltr, roomFltr); IList <Element> rooms = new FilteredElementCollector(doc, doc.ActiveView.Id) .WherePasses(roomAndIntersectBndBox) .ToElements(); string blockNo = GenBlockName(boxes[i]); using (Transaction t = new Transaction(doc, "Set rooms' parameters")) { t.Start(); for (int j = 0; j < rooms.Count; ++j) { Element rm = rooms[j]; rm.LookupParameter(PRM_BLOCK_NO).Set(blockNo); rm.LookupParameter(PRM_LEVEL).Set(lvlName); string commentsContent = rm.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString(); if (commentsContent != null && commentsContent.Length != 0) { rm.LookupParameter(PRM_FUNCTION_NO).Set(commentsContent.Substring(0, 1)); } } t.Commit(); } } return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { TaskDialog.Show("Exception", string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); System.Diagnostics.Trace.Write(string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); return(Result.Failed); } finally { myTimer.StopTime(); System.Diagnostics.Trace .Write(string.Format("Time elapsed: {0}s", myTimer.Duration.TotalSeconds)); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; doc = uidoc.Document; Selection sel = uidoc.Selection; try { IList <FamilyWithImage> allBeamsInfo = Utils.GetInformation.GetAllBeamFamilies(doc); if (allBeamsInfo.Count < 1) { message = Properties.Messages.BeamsForBuilding_NoBeamFamilyLoaded; return(Result.Failed); } BeamsFromEntireBuildingUI currentUI = new BeamsFromEntireBuildingUI(this, allBeamsInfo); currentUI.ShowDialog(); if (currentUI.DialogResult == false) { return(Result.Cancelled); } FamilyWithImage currentFamilyWithImage = currentUI.CurrentFamilyWithImage; Family currentFamily = doc.GetElement(new ElementId(currentFamilyWithImage.FamilyID)) as Family; //for now we will set the symbol for the first beam of that family //later on we will duplicate it and check if it exist or not ElementId fsID = currentFamily.GetFamilySymbolIds().First(); FamilySymbol fs = doc.GetElement(fsID) as FamilySymbol; double beamHeight = Utils.ConvertM.cmToFeet(currentUI.BeamHeight); double beamWidth = Utils.ConvertM.cmToFeet(currentUI.BeamWidth); bool createBeamsInIntermediateLevels = currentUI.CreateBeamsInIntermediateLevels; bool ignoreStandardLevels = currentUI.GroupAndDuplicateLevels; bool isLinked = currentUI.IsLinked; double minWallWidth = Utils.ConvertM.cmToFeet(currentUI.MinWallWidth); IList <LevelInfo> allLevelInfo = currentUI.LevelInfoList; string standardLevelName = currentUI.StandardLevelName; bool pickStandardLevelsByName = currentUI.PickStandardLevelsByName; bool isCaseSensitive = currentUI.IsCaseSensitive; bool isJoinBeams = (bool)currentUI.checkJoinBeams.IsChecked; //Will be set if needed int linkedInstanceID = -1; Transform linkedInstanceTransf = null; IList <string> listOfNames = new List <string>(); listOfNames.Add(standardLevelName); if (isLinked == false) { currentDoc = doc; } else { RevitLinkInstance rvtInstance = doc.GetElement(new ElementId(currentUI.SelectedRevitLinkInfo.Id)) as RevitLinkInstance; currentDoc = rvtInstance.GetLinkDocument(); linkedInstanceTransf = rvtInstance.GetTotalTransform(); linkedInstanceID = currentUI.SelectedRevitLinkInfo.Id; } if (pickStandardLevelsByName) { foreach (LevelInfo currentLevelInfo in allLevelInfo) { if (LevelNameContainsString(currentLevelInfo.levelName, listOfNames, isCaseSensitive)) { currentLevelInfo.isStandardLevel = true; } } } string beamWidthInCm = Math.Round(Utils.ConvertM.feetToCm(beamWidth)).ToString(); string beamHeigthInCm = Math.Round(Utils.ConvertM.feetToCm(beamHeight)).ToString(); string newTypeName = beamWidthInCm + " x " + beamHeigthInCm + "cm"; FamilySymbol currentFamilySymbol = null; using (Transaction t = new Transaction(doc, Properties.Messages.BeamsForBuilding_Transaction)) { t.Start(); if (!Utils.FindElements.thisTypeExist(newTypeName, currentFamily.Name, BuiltInCategory.OST_StructuralFraming, doc)) { currentFamilySymbol = fs.Duplicate(newTypeName) as FamilySymbol; Parameter parameterB = currentFamilySymbol.LookupParameter("b"); Parameter parameterH = currentFamilySymbol.LookupParameter("h"); //TODO check for code like this that can throw exceptions parameterB.Set(beamWidth); parameterH.Set(beamHeight); } else { currentFamilySymbol = Utils.FindElements.findElement(newTypeName, currentFamily.Name, BuiltInCategory.OST_StructuralFraming, doc) as FamilySymbol; } currentFamilySymbol.Activate(); bool isThisTheFirstStandardLevel = true; foreach (LevelInfo currentLevelInfo in allLevelInfo) { if (currentLevelInfo == null) { continue; } if (!currentLevelInfo.willBeNumbered) { continue; } Level currentLevel = currentDoc.GetElement(new ElementId(currentLevelInfo.levelId)) as Level; XYZ minPoint = new XYZ(-9999, -9999, currentLevel.ProjectElevation - 0.1); XYZ maxPoint = new XYZ(9999, 9999, currentLevel.ProjectElevation + 0.1); Outline levelOutLine = new Outline(minPoint, maxPoint); BoundingBoxIntersectsFilter levelBBIntersect = new BoundingBoxIntersectsFilter(levelOutLine, 0.05); BoundingBoxIsInsideFilter levelBBInside = new BoundingBoxIsInsideFilter(levelOutLine, 0.05); LogicalOrFilter levelInsideOrIntersectFilter = new LogicalOrFilter(levelBBInside, levelBBIntersect); IList <Element> wallsThatIntersectsCurrentLevel = new FilteredElementCollector(currentDoc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType() .WherePasses(levelInsideOrIntersectFilter).ToList(); if (currentLevelInfo.isStandardLevel && ignoreStandardLevels) { if (isThisTheFirstStandardLevel) { isThisTheFirstStandardLevel = false; } else { continue; } } foreach (Element currentWallElment in wallsThatIntersectsCurrentLevel) { Wall currentWall = currentWallElment as Wall; //wall is valid? if (currentWall == null) { continue; } if (currentWall.Width < minWallWidth) { continue; } if (!createBeamsInIntermediateLevels) { if (currentWallElment.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId() != currentLevel.Id && currentWallElment.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId() != currentLevel.Id) { continue; } } LocationCurve wallLocationCurve = currentWall.Location as LocationCurve; //we need to verify if this wall has locationCurve if (wallLocationCurve == null) { continue; } Curve wallCurve = ((currentWall.Location) as LocationCurve).Curve; if (isLinked) { wallCurve = wallCurve.CreateTransformed(linkedInstanceTransf); } double wallBaseOffset = currentWall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).AsDouble(); Level wallBaseLevel = currentDoc.GetElement(currentWall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId()) as Level; double wallBaseTotalHeight = wallBaseLevel.ProjectElevation + wallBaseOffset; double wallTotalHeight = currentWall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM).AsDouble(); if (wallTotalHeight < beamHeight) { continue; } double levelHeight = currentLevel.ProjectElevation; Level currentLevelInProject = null; if (isLinked) { levelHeight += linkedInstanceTransf.Origin.Z; IList <Level> allLevelsInProject = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(Level)).Cast <Level>().ToList(); foreach (Level levelCanditate in allLevelsInProject) { if (Math.Abs(levelHeight - levelCanditate.ProjectElevation) <= 0.1) { currentLevelInProject = levelCanditate; break; } } if (currentLevelInProject == null) { currentLevelInProject = Level.Create(doc, levelHeight); } } else { currentLevelInProject = currentLevel; } FamilyInstance currentBeamInstance = doc.Create.NewFamilyInstance(wallCurve, currentFamilySymbol, currentLevelInProject, Autodesk.Revit.DB.Structure.StructuralType.Beam); AdjustBeamParameters(currentBeamInstance, currentLevelInProject); doc.Regenerate(); Utils.CheckFamilyInstanceForIntersection.CheckForDuplicatesAndIntersectingBeams(currentBeamInstance, doc); } } if (isJoinBeams) { IList <FamilyInstance> allBeamsInstances = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming) .OfClass(typeof(FamilyInstance)).WhereElementIsNotElementType().Cast <FamilyInstance>().ToList(); foreach (FamilyInstance currentBeam in allBeamsInstances) { Utils.CheckFamilyInstanceForIntersection.JoinBeamToWalls(currentBeam, doc); } } t.Commit(); } } catch (Exception excep) { ExceptionManager eManager = new ExceptionManager(excep); } return(Result.Succeeded); }
public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements) { try { var document = revit.Application.ActiveUIDocument.Document; GetSomeShit(document, out string error); if (error != null) { TaskDialog.Show("Ошибка", error); return(Result.Succeeded); } var systemsByEquipmentIds = new Dictionary <ElementId, List <ElementId> >(); foreach (var system in ElectricalSystems) { var equipment = system.BaseEquipment; if (equipment == null) { continue; } if (!systemsByEquipmentIds.ContainsKey(equipment.Id)) { systemsByEquipmentIds.Add(equipment.Id, new List <ElementId>()); } systemsByEquipmentIds[equipment.Id].Add(system.Id); } var conduitTypes = new Dictionary <string, ElementId>(); foreach (ConduitType type in ConduitTypes) { conduitTypes.Add(type.FamilyName + ": " + type.Name, type.Id); } var gui = new UserForm(document, systemsByEquipmentIds, conduitTypes); if (gui.ShowDialog() != DialogResult.OK) { return(Result.Cancelled); } var conduitTypeId = gui.SelectedConduitType; var electricalCircuitsWithLevelId = new List <Tuple <ElementId, List <XYZ> > >(); foreach (var systemId in gui.SelectedCircuits) { var system = (ElectricalSystem)document.GetElement(systemId); var circuit = system.GetCircuitPath().ToList(); electricalCircuitsWithLevelId.Add(new Tuple <ElementId, List <XYZ> >(system.LevelId, circuit)); } Transaction tr = new Transaction(document, "Создание коробов по электрической цепи"); tr.Start(); foreach (var x in electricalCircuitsWithLevelId) { var createdConduits = new List <Conduit>(); for (var i = 0; i < x.Item2.Count() - 1; i++) { var startPoint = new XYZ( Math.Min(x.Item2[i].X, x.Item2[i + 1].X) - 0.01, Math.Min(x.Item2[i].Y, x.Item2[i + 1].Y) - 0.01, Math.Min(x.Item2[i].Z, x.Item2[i + 1].Z) - 0.01 ); var endPoint = new XYZ( Math.Max(x.Item2[i].X, x.Item2[i + 1].X) + 0.01, Math.Max(x.Item2[i].Y, x.Item2[i + 1].Y) + 0.01, Math.Max(x.Item2[i].Z, x.Item2[i + 1].Z) + 0.01 ); var myOutLn = new Outline(startPoint, endPoint); var conduits = new List <ElementId>(); if (!myOutLn.IsEmpty) { var filter = new BoundingBoxIsInsideFilter(myOutLn); var collector = new FilteredElementCollector(document); conduits = collector .WherePasses(filter) .OfClass(typeof(Conduit)) .Cast <Conduit>() .Select(a => a.Id) .ToList(); } document.Delete(conduits); var conduit = Conduit.Create(document, conduitTypeId, x.Item2.ElementAt(i), x.Item2.ElementAt(i + 1), x.Item1); createdConduits.Add(conduit); } //for (var i = 0; i < createdConduits.Count() - 1; i++) //{ // var connector1 = new Connector(); // var connector2; // foreach (Connector c in createdConduits.ElementAt(i).ConnectorManager.Connectors) // { // // моя тут сломался фмгня получается // connector1 = c; // break; // } // foreach (Connector c in createdConduits.ElementAt(i+1).ConnectorManager.Connectors) // { // // connector2 = c; // break; // } // document.Create.NewElbowFitting( // connector1, // connector2); //} } tr.Commit(); return(Result.Succeeded); } catch (Exception e) { TaskDialog.Show("Error", e.ToString()); return(Result.Failed); } return(Result.Succeeded); }
public void TagElement(UIDocument uidoc, Reference myRef, View view) { Document doc = uidoc.Document; if (myRef == null) { return; } Element e = doc.GetElement(myRef); Wall wall = e as Wall; //Creates a selection filter to dump objects in for later selection ICollection <ElementId> selec = new List <ElementId>(); //Gets the bounding box of the selected wall element picked above BoundingBoxXYZ bb = e.get_BoundingBox(view); //adds a buffer to the bounding box to ensure all elements are contained within the box XYZ buffer = new XYZ(0.1, 0.1, 0.1); //creates an ouline based on the boundingbox corners of the panel and adds the buffer Outline outline = new Outline(bb.Min - buffer, bb.Max + buffer); //filters the selection by the bounding box of the selected object //the "true" statement inverts the selection and selects all other objects BoundingBoxIsInsideFilter bbfilter = new BoundingBoxIsInsideFilter(outline, false); //creates a new filtered element collector that filters by the active view settings FilteredElementCollector collector = new FilteredElementCollector(doc, view.Id); //collects all objects that pass through the requirements of the bbfilter collector.WherePasses(bbfilter); //adds each element that passed the bbfilter to the current selection collector //also checks to see if the element can be hidden ICollection <Element> Embeds = new List <Element>(); foreach (Element el in collector) { if (el.Name.Contains("EM")) { selec.Add(el.Id); Embeds.Add(el); } } // define tag mode and tag orientation for new tag TagMode tagMode = TagMode.TM_ADDBY_CATEGORY; TagOrientation tagorn = TagOrientation.Horizontal; //Tag the wall and place it in the middle of the wall LocationCurve wallLoc = wall.Location as LocationCurve; XYZ wallStart = wallLoc.Curve.GetEndPoint(0); XYZ wallEnd = wallLoc.Curve.GetEndPoint(1); XYZ wallMid = wallLoc.Curve.Evaluate(0.5, true); using (Transaction t = new Transaction(doc, "Create Structural connection tag.")) { t.Start(); IndependentTag newTag = doc.Create.NewTag(view, wall, false, tagMode, tagorn, wallMid); if (newTag == null) { throw new Exception("Create IndependentTag Failed."); } foreach (Element el in Embeds) { LocationPoint embedpoint = el.Location as LocationPoint; XYZ embedXyz = embedpoint.Point; IndependentTag embedTag = doc.Create.NewTag(view, el, false, tagMode, tagorn, embedXyz); if (embedTag == null) { throw new Exception("Create IndependentTag Failed."); } } //move panel tag 15' up from bottom of panel newTag.Location.Move(new XYZ(0, 0, 15)); // newTag.TagText is read-only, so we change the Type Mark type parameter to // set the tag text. The label parameter for the tag family determines // what type parameter is used for the tag text. //WallType type = wall.WallType; //Parameter foundParameter = type.LookupParameter("Type Mark"); //bool result = foundParameter.Set("Hello"); // set leader mode free // otherwise leader end point move with elbow point //newTag.LeaderEndCondition = LeaderEndCondition.Free; //XYZ elbowPnt = wallMid + new XYZ(5.0, 5.0, 0.0); //newTag.LeaderElbow = elbowPnt; //headerPnt = wallMid + new XYZ(10.0, 10.0, 0.0); //newTag.TagHeadPosition = headerPnt; t.Commit(); } }
public void test(UIDocument uidoc) { Document doc = uidoc.Document; ReferenceArray refs = new ReferenceArray(); Reference myRef = uidoc.Selection.PickObject( ObjectType.Element, new MySelectionFilter("Walls"), "Select a wall"); Wall wall = doc.GetElement(myRef) as Wall; // Creates an element e from the selected object // reference -- this will be the wall element Element e = doc.GetElement(myRef); // Creates a selection filter to dump objects // in for later selection ICollection <ElementId> selSet = new List <ElementId>(); // Gets the bounding box of the selected wall // element picked above BoundingBoxXYZ bb = e.get_BoundingBox(doc.ActiveView); // adds a buffer to the bounding box to ensure // all elements are contained within the box XYZ buffer = new XYZ(0.1, 0.1, 0.1); // creates an ouline based on the boundingbox // corners of the panel and adds the buffer Outline outline = new Outline( bb.Min - buffer, bb.Max + buffer); // filters the selection by the bounding box of the selected object // the "true" statement inverts the selection and selects all other objects BoundingBoxIsInsideFilter bbfilter = new BoundingBoxIsInsideFilter(outline, false); ICollection <BuiltInCategory> bcat = new List <BuiltInCategory>(); //creates a new filtered element collector that // filters by the active view settings FilteredElementCollector collector = new FilteredElementCollector( doc, doc.ActiveView.Id); //collects all objects that pass through the // requirements of the bbfilter collector.WherePasses(bbfilter); //add all levels and grids to filter -- these // are filtered out by the viewtemplate, but // are nice to have bcat.Add(BuiltInCategory.OST_StructConnections); //create new multi category filter ElementMulticategoryFilter multiCatFilter = new ElementMulticategoryFilter(bcat); //create new filtered element collector, add the // passing levels and grids, then remove them // from the selection foreach (Element el in collector.WherePasses( multiCatFilter)) { if (el.Name.Equals("EMBEDS")) { selSet.Add(el.Id); } } XYZ[] pts = new XYZ[99]; //View3D view = doc.ActiveView as View3D; View3D view = Get3dView(doc); // THIS IS WHERE IT RETURNS THE WALL OPENING REFERENCES. // HOWEVER THEY ONLY ARE ABLE TO BE USED FOR DIMENSIONS // IF THE OPENING IS CREATED USING A FAMILY SUCH AS A // WINDOW OR DOOR. OPENING BY FACE/WALL DOES NOT WORK, // EVEN THOUGH IT RETURNS PROPER REFERENCES List <Reference> openings = GetWallOpenings(e as Wall, view); foreach (Reference reference in openings) { refs.Append(reference); } TaskDialog.Show("REFERE", refs.Size.ToString()); Curve wallLocation = (wall.Location as LocationCurve).Curve; int i = 0; foreach (ElementId ele in selSet) { FamilyInstance fi = doc.GetElement(ele) as FamilyInstance; Reference reference = ScottWilsonVoodooMagic.GetSpecialFamilyReference( fi, ScottWilsonVoodooMagic.SpecialReferenceType.CenterLR, doc); refs.Append(reference); pts[i] = (fi.Location as LocationPoint).Point; i++; } XYZ offset = new XYZ(0, 0, 4); Line line = Line.CreateBound( pts[0] + offset, pts[1] + offset); using (Transaction t = new Transaction(doc)) { t.Start("dimension embeds"); Dimension dim = doc.Create.NewDimension(doc.ActiveView, line, refs); t.Commit(); } }
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); }