/// <summary> /// Read all BuiltInCategory.OST_Floors elements from a Revit model. /// </summary> private void ReadFloors() { var collector = new FilteredElementCollector(a_doc); List <ElementFilter> filters = new List <ElementFilter>(); var filterCategory = new ElementCategoryFilter(BuiltInCategory.OST_Floors); var filterNotSymbol = new ElementClassFilter(typeof(FamilySymbol), true); var filterNotFloorType = new ElementClassFilter(typeof(FloorType), true); filters.Add(filterCategory); filters.Add(filterNotSymbol); filters.Add(filterNotFloorType); var filter = new LogicalAndFilter(filters); var elements = collector.WherePasses(filter).ToElements(); foreach (var element in elements) { try { if (element is Floor && CheckElementPhase(element)) { Floor floor = element as Floor; var revitElement = new RevitElement(); revitElement.Category = RevitCategory.Floor; revitElement.Id = element.Id.ToString(); revitElement.Name = element.Name; var floorLevelid = floor.LevelId; Level levelElement = a_doc.GetElement(floorLevelid) as Level; revitElement.AssociatedLevel = levelElement != null ? levelElement.Name : a_unknownLevelName; revitElement.AssociatedElevation = levelElement != null ? levelElement.ProjectElevation : a_unknownLevelElevation; revitElement.AssociatedLevel = GetMappedLevel(revitElement.AssociatedLevel); var floorArea = element.GetParameters("Area"); revitElement.Area = floorArea.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(floorArea[0].AsDouble(), DisplayUnitType.DUT_SQUARE_FEET) : 0.0; var elementVolume = element.GetParameters("Volume"); revitElement.Volume = elementVolume.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(elementVolume[0].AsDouble(), DisplayUnitType.DUT_CUBIC_FEET) : 0.0; // Look for metal deck bool addRevitElement = true; var floorTypeId = element.GetTypeId(); var floorType = a_doc.GetElement(floorTypeId) as HostObjAttributes; if (floorType != null) { var elementCompoundStructure = floorType.GetCompoundStructure(); int structuralLayerIndex = elementCompoundStructure.StructuralMaterialIndex; var compoundStructureLayers = elementCompoundStructure.GetLayers(); bool allStructuralDecks = true; for (int i = 0; i < compoundStructureLayers.Count; i++) { var elementLayer = compoundStructureLayers[i]; if (elementLayer.Function == MaterialFunctionAssignment.StructuralDeck) { var elementLayerDeck = a_doc.GetElement(elementLayer.DeckProfileId) as FamilySymbol; var elementLayerMaterial = a_doc.GetElement(elementLayer.MaterialId) as Material; if (elementLayerDeck != null && elementLayerMaterial != null) { // hr = height of rib var hrParam = elementLayerDeck.GetParameters("hr"); double hr = hrParam.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(hrParam[0].AsDouble(), DisplayUnitType.DUT_DECIMAL_FEET) : 0.0; // wr = width of rib var wrParam = elementLayerDeck.GetParameters("wr"); double wr = wrParam.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(wrParam[0].AsDouble(), DisplayUnitType.DUT_DECIMAL_FEET) : 0.0; // rr = root of rib var rrParam = elementLayerDeck.GetParameters("rr"); double rr = rrParam.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(rrParam[0].AsDouble(), DisplayUnitType.DUT_DECIMAL_FEET) : 0.0; // Sr = width of rib var srParam = elementLayerDeck.GetParameters("Sr"); double Sr = srParam.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(srParam[0].AsDouble(), DisplayUnitType.DUT_DECIMAL_FEET) : 0.0; // Thickness var thicknessParam = elementLayerDeck.GetParameters("Thickness"); double thickness = thicknessParam.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(thicknessParam[0].AsDouble(), DisplayUnitType.DUT_DECIMAL_FEET) : 0.0; // Layer Density double layerDensity = GetDensity(elementLayerMaterial); if (revitElement.Area > 0 && Sr > 0 && hr > 0 && wr > 0 && rr > 0 && thickness > 0 && layerDensity > 0) { revitElement.Volume = revitElement.Volume - (revitElement.Area * hr / 2); double flange = Sr - wr; double rib = rr; double web = Math.Sqrt(Math.Pow(hr, 2) + Math.Pow(((wr - rr) / 2), 2)); double deckWidthFlatten = flange + rib + (2 * web); double weightOfOneFootOfDeck = deckWidthFlatten * thickness * 1 * layerDensity; double deckPsf = weightOfOneFootOfDeck / (Sr * 1); double weightOfDeck = revitElement.Area * deckPsf; double volumeOfDeck = weightOfDeck / layerDensity; string deckName = elementLayerDeck.FamilyName + " - " + elementLayerDeck.Name; RevitElement floorDeck = new RevitElement( revitElement.Category, revitElement.Id, deckName, revitElement.AssociatedLevel, revitElement.AssociatedElevation, volumeOfDeck, elementLayerMaterial.Name, GetMaterialType(elementLayerMaterial), layerDensity); a_revitElementData.Add(floorDeck); // Don't add revitElement if added here, avoid double counting and counting deck with full depth volume. if (addRevitElement == true) { addRevitElement = structuralLayerIndex == i ? false : true; } } } } else { allStructuralDecks = false; } } if (allStructuralDecks == false && addRevitElement == false) { addRevitElement = true; } } var framingStructuralMaterial = this.GetStructuralMaterialFromElement(element, a_doc); revitElement.MaterialName = framingStructuralMaterial != null ? framingStructuralMaterial.Name : ""; revitElement.Material = framingStructuralMaterial != null?GetMaterialType(framingStructuralMaterial) : MaterialType.Unknown; double density = framingStructuralMaterial != null?GetDensity(framingStructuralMaterial) : 0.0; revitElement.Density = density; if (addRevitElement) { a_revitElementData.Add(revitElement); } } } catch (Exception e) { ShowElementErrorMessage(element, e); } } }
/// <summary> /// Given the filter in use by a stream returns the document elements that match it /// </summary> /// <returns></returns> private IEnumerable <SpeckleObject> GetSelectionFilterObjects(ISelectionFilter filter, string clientId, string streamId) { var doc = CurrentDoc.Document; IEnumerable <SpeckleObject> objects = new List <SpeckleObject>(); var selectionIds = new List <string>(); if (filter.Name == "Selection") { var selFilter = filter as ElementsSelectionFilter; selectionIds = selFilter.Selection; } else if (filter.Name == "Category") { var catFilter = filter as ListSelectionFilter; var bics = new List <BuiltInCategory>(); var categories = Globals.GetCategories(doc); IList <ElementFilter> elementFilters = new List <ElementFilter>(); foreach (var cat in catFilter.Selection) { elementFilters.Add(new ElementCategoryFilter(categories[cat].Id)); } LogicalOrFilter categoryFilter = new LogicalOrFilter(elementFilters); selectionIds = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .WherePasses(categoryFilter) .Select(x => x.UniqueId).ToList(); } else if (filter.Name == "View") { var viewFilter = filter as ListSelectionFilter; var views = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfClass(typeof(View)) .Where(x => viewFilter.Selection.Contains(x.Name)); foreach (var view in views) { var ids = new FilteredElementCollector(doc, view.Id) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsPhysicalElement()) .Select(x => x.UniqueId).ToList(); selectionIds = selectionIds.Union(ids).ToList(); } } else if (filter.Name == "Parameter") { try { var propFilter = filter as PropertySelectionFilter; var query = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsPhysicalElement()) .Where(fi => fi.LookupParameter(propFilter.PropertyName) != null); propFilter.PropertyValue = propFilter.PropertyValue.ToLowerInvariant(); switch (propFilter.PropertyOperator) { case "equals": query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)) == propFilter.PropertyValue); break; case "contains": query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)).Contains(propFilter.PropertyValue)); break; case "is greater than": query = query.Where(fi => UnitUtils.ConvertFromInternalUnits( fi.LookupParameter(propFilter.PropertyName).AsDouble(), fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) > double.Parse(propFilter.PropertyValue)); break; case "is less than": query = query.Where(fi => UnitUtils.ConvertFromInternalUnits( fi.LookupParameter(propFilter.PropertyName).AsDouble(), fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) < double.Parse(propFilter.PropertyValue)); break; default: break; } selectionIds = query.Select(x => x.UniqueId).ToList(); } catch (Exception e) { Console.WriteLine(e); } } // LOCAL STATE management objects = selectionIds.Select(id => { var temp = new SpeckleObject(); temp.Properties["revitUniqueId"] = id; temp.Properties["__type"] = "Sent Object"; return(temp); }); var myStream = LocalState.FirstOrDefault(st => st.StreamId == streamId); myStream.Objects.Clear(); myStream.Objects.AddRange(objects); var myClient = ClientListWrapper.clients.FirstOrDefault(cl => (string)cl._id == (string)clientId); myClient.objects = JsonConvert.DeserializeObject <dynamic>(JsonConvert.SerializeObject(myStream.Objects)); // Persist state and clients to revit file Queue.Add(new Action(() => { using (Transaction t = new Transaction(CurrentDoc.Document, "Update local storage")) { t.Start(); SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState); SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper); t.Commit(); } })); Executor.Raise(); var plural = objects.Count() == 1 ? "" : "s"; if (objects.Count() != 0) { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = clientId, expired = true, objects = myClient.objects, //message = $"You have added {objects.Count()} object{plural} to this sender." })); } return(objects); }
/// <summary> /// Given the filter in use by a stream returns the document elements that match it. /// </summary> /// <param name="filter"></param> /// <returns></returns> private List <Element> GetSelectionFilterObjects(ISelectionFilter filter) { var doc = CurrentDoc.Document; var selection = new List <Element>(); switch (filter.Name) { case "Category": var catFilter = filter as ListSelectionFilter; var bics = new List <BuiltInCategory>(); var categories = ConnectorRevitUtils.GetCategories(doc); IList <ElementFilter> elementFilters = new List <ElementFilter>(); foreach (var cat in catFilter.Selection) { elementFilters.Add(new ElementCategoryFilter(categories[cat].Id)); } var categoryFilter = new LogicalOrFilter(elementFilters); selection = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .WherePasses(categoryFilter).ToList(); return(selection); case "View": var viewFilter = filter as ListSelectionFilter; var views = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfClass(typeof(View)) .Where(x => viewFilter.Selection.Contains(x.Name)); foreach (var view in views) { var ids = selection.Select(x => x.UniqueId); var viewElements = new FilteredElementCollector(doc, view.Id) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsPhysicalElement()) .Where(x => !ids.Contains(x.UniqueId)) //exclude elements already added from other views .ToList(); selection.AddRange(viewElements); } return(selection); case "Project Info": var projectInfoFilter = filter as ListSelectionFilter; if (projectInfoFilter.Selection.Contains("Project Info")) { selection.Add(doc.ProjectInformation); } if (projectInfoFilter.Selection.Contains("Views 2D")) { selection.AddRange(new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_Views) .Cast <View>() .Where(x => x.ViewType == ViewType.CeilingPlan || x.ViewType == ViewType.FloorPlan || x.ViewType == ViewType.Elevation || x.ViewType == ViewType.Section) .ToList()); } if (projectInfoFilter.Selection.Contains("Views 3D")) { selection.AddRange(new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_Views) .Cast <View>() .Where(x => x.ViewType == ViewType.ThreeD) .ToList()); } if (projectInfoFilter.Selection.Contains("Levels")) { selection.AddRange(new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_Levels).ToList()); } if (projectInfoFilter.Selection.Contains("Families & Types")) { //get all the elementtypes of the categories we support var allCategoryFilter = new LogicalOrFilter(ConnectorRevitUtils.GetCategories(doc).Select(x => new ElementCategoryFilter(x.Value.Id)).Cast <ElementFilter>().ToList()); selection.AddRange(new FilteredElementCollector(doc) .WhereElementIsElementType() .WherePasses(allCategoryFilter).ToList()); } return(selection); case "Parameter": try { var propFilter = filter as PropertySelectionFilter; var query = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsPhysicalElement()) .Where(fi => fi.LookupParameter(propFilter.PropertyName) != null); propFilter.PropertyValue = propFilter.PropertyValue.ToLowerInvariant(); switch (propFilter.PropertyOperator) { case "equals": query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)) == propFilter.PropertyValue); break; case "contains": query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)).Contains(propFilter.PropertyValue)); break; case "is greater than": query = query.Where(fi => UnitUtils.ConvertFromInternalUnits( fi.LookupParameter(propFilter.PropertyName).AsDouble(), fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) > double.Parse(propFilter.PropertyValue)); break; case "is less than": query = query.Where(fi => UnitUtils.ConvertFromInternalUnits( fi.LookupParameter(propFilter.PropertyName).AsDouble(), fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) < double.Parse(propFilter.PropertyValue)); break; } selection = query.ToList(); } catch (Exception e) { Log.CaptureException(e); } return(selection); } return(selection); }
public void CheckModelDoors(Document doc, Application app) { #region Set Collector and Filter /* * // set collector * FilteredElementCollector collector = new FilteredElementCollector(doc); * // set filter * ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); */ #endregion var doorCollector = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)); // FilteredElementCollector a = new FilteredElementCollector(doc).OfClass(typeof(SpatialElement)); doorCollector.OfCategory(BuiltInCategory.OST_Doors); IList <Element> doorList = doorCollector.ToElements(); #region Set Filter on Collector // set filter on the collector //IList<Element> typedoors = collector.WherePasses(filter).WhereElementIsElementType().ToElements(); //IList<Element> instdoors = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); #endregion #region Get Doors and Check their Width List <Double> passedDoors = new List <Double>(); List <Double> failedDoors = new List <Double>(); List <ElementId> failedDoorId = new List <ElementId>(); List <ElementId> passedDoorId = new List <ElementId>(); foreach (Element door in doorList) { //Instance param Parameter doorInstparam = door.get_Parameter(BuiltInParameter.DOOR_WIDTH); //string InstStorage = doorInstparam.StorageType.ToString(); //Parameter parameter = door.LookupParameter("width"); double doorInstWidth = (doorInstparam.HasValue) ? doorInstparam.AsDouble() : 0; //double doorWidthParam = parameter.AsDouble(); //type param ElementId doorTypeId = door.GetTypeId(); ElementType doorType = (ElementType)doc.GetElement(doorTypeId); Parameter doorTypeParam = doorType.get_Parameter(BuiltInParameter.FAMILY_WIDTH_PARAM); //string typeStorage = doorInstparam.StorageType.ToString(); double doorTypeWidth = (doorTypeParam.HasValue) ? doorTypeParam.AsDouble() : 0; double doorInstWidthmm = UnitUtils.ConvertFromInternalUnits(doorInstWidth, DisplayUnitType.DUT_MILLIMETERS); double doorTypeWidthmm = UnitUtils.ConvertFromInternalUnits(doorTypeWidth, DisplayUnitType.DUT_MILLIMETERS); double ttldoorWidth = new double(); if (doorInstWidthmm == 0) { ttldoorWidth = doorTypeWidthmm; } else { ttldoorWidth = doorInstWidthmm; } if (ttldoorWidth <= 800) { ElementId faildoorId = door.GetTypeId(); failedDoorId.Add(faildoorId); failedDoors.Add(ttldoorWidth); } else { ElementId passdoorId = door.GetTypeId(); passedDoorId.Add(passdoorId); passedDoors.Add(ttldoorWidth); } } #endregion #region Write to text file //if ((!File.Exists("FailedDoors.txt"))) //{ StreamWriter File = new StreamWriter("FailedDoors.txt"); for (int i = 0; i < failedDoors.Count; i++) { string fdtxt = "The Door Width is " + failedDoors[i]; File.WriteLine(fdtxt); string fdIdtxt = "The Door Id is " + failedDoorId[i]; File.WriteLine(fdIdtxt); File.WriteLine("++++++++++++++++++++++++++++++"); } File.Close(); StreamWriter file = new StreamWriter("PassedDoors.txt"); for (int i = 0; i < passedDoors.Count; i++) { string pdtxt = "The Door Width is " + passedDoors[i]; File.WriteLine(pdtxt); string pdIdtxt = "The Door Id is " + passedDoorId[i]; File.WriteLine(pdIdtxt); File.WriteLine("++++++++++++++++++++++++++++++"); } file.Close(); //} #endregion TaskDialog.Show("Door Width", "The failed Doors are saved in a text file"); }
private System.Windows.Media.Media3D.Vector3D ConvertToDisplayUnits(System.Windows.Media.Media3D.Vector3D v) { return(new System.Windows.Media.Media3D.Vector3D(UnitUtils.ConvertFromInternalUnits(v.X, BIM.OpenFOAMExport.Exporter.Instance.settings.Units), UnitUtils.ConvertFromInternalUnits(v.Y, BIM.OpenFOAMExport.Exporter.Instance.settings.Units), UnitUtils.ConvertFromInternalUnits(v.Z, BIM.OpenFOAMExport.Exporter.Instance.settings.Units))); }
private String GetWalls() { String tString = ""; //List<Element> walls = new FilteredElementCollector(doc) // .OfClass(typeof(Wall)).WhereElementIsNotElementType().ToElements().ToList(); walls = new FilteredElementCollector(doc) .WhereElementIsNotElementType().WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Walls)).ToElements(); tString += NL + NL + "# WALLS"; foreach (Element e in walls) { if (e is FamilyInstance) { string URI = Util.CreateURI(e, Namespace).Replace(Namespace, "inst:"); ElementDict.Add(e.Id, URI); tString += NL + NL + $"{URI}" + NLT + $"a bot:Element ;" + NLT + $"a beo:Wall ;" + NLT + $"props:geometryType \"FamilyInstance\" ;" + NLT + $"props:revitId \"{e.Id}\" ;" + NLT + $"props:ifcGuid \"{e.GetGUID()}\" ;" + NLT + $"props:uuid \"{e.GetUUID()}\" ."; } else { Wall wall = e as Wall; //string URI = Parameters.GenerateURIifNotExist(doc, e).Replace(Namespace, "inst:"); string URI = Util.CreateURI(e, Namespace).Replace(Namespace, "inst:"); String wallType = doc.GetElement(wall.GetTypeId()).Name.ToString(); //string typeURI = "inst:" + Util.TypeNameToId(wallType); ElementDict.Add(e.Id, URI); // Append classes to tString += NL + NL + $"{URI}" + NLT + $"a bot:Element ;" + NLT + $"a beo:Wall ;" + NLT + $"props:geometryType \"Solid\" ;" + NLT + $"props:revitId \"{e.Id}\" ;" + NLT + $"props:ifcGuid \"{e.GetGUID()}\" ;" + NLT + $"props:uuid \"{e.GetUUID()}\" ;"; string width = Math.Round(UnitUtils.ConvertFromInternalUnits(wall.Width, Autodesk.Revit.DB.DisplayUnitType.DUT_MILLIMETERS), 2).ToString().Replace(",", "."); double curveLength = wall.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH).AsDouble(); string length = Math.Round(UnitUtils.ConvertFromInternalUnits(curveLength, Autodesk.Revit.DB.DisplayUnitType.DUT_MILLIMETERS), 2).ToString().Replace(",", "."); width = $"\"{width}\"^^xsd:decimal"; length = $"\"{length}\"^^xsd:decimal"; string name = $"{e.Name}"; tString += NLT + $"props:identityDataName \"{name}\" ;"; tString += NLT + $"props:dimensionsWidth {width} ;"; tString += NLT + $"props:dimensionsLength {length} ;"; //testString += Util.GetFacesAndEdges(wall) + NL; tString += NLT + $"bot:hasSimple3DModel \"\"\"{Util.GetFacesAndEdges(wall, true)}\"\"\" ."; } } return(tString); }
public static List <Shell> Shells(this Document document, IEnumerable <Autodesk.Revit.DB.Mechanical.Space> spaces = null, double offset = 0.1, double snapTolerance = Core.Tolerance.MacroDistance, double tolerance = Core.Tolerance.Distance) { if (document == null) { return(null); } //Collecting Space list List <Autodesk.Revit.DB.Mechanical.Space> spaces_Temp = new FilteredElementCollector(document).OfCategory(BuiltInCategory.OST_MEPSpaces).Cast <Autodesk.Revit.DB.Mechanical.Space>().ToList(); if (spaces != null) { List <Autodesk.Revit.DB.Mechanical.Space> spaces_New = new List <Autodesk.Revit.DB.Mechanical.Space>(); foreach (Autodesk.Revit.DB.Mechanical.Space space in spaces) { int index = spaces_Temp.FindIndex(x => x.Id.IntegerValue == space.Id.IntegerValue); if (index != -1) { spaces_New.Add(spaces_Temp[index]); } } spaces_Temp = spaces_New; } if (spaces_Temp == null || spaces_Temp.Count == 0) { return(null); } //Dictionary of bottom elevations and tuples (top elevation, location 2D, Space) (Metric Units) Dictionary <double, List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > > dictionary = new Dictionary <double, List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > >(); //Space cut elevations (Imperial Units) HashSet <double> cutElevations = new HashSet <double>(); //Collecting Spaces data foreach (Autodesk.Revit.DB.Mechanical.Space space in spaces_Temp) { XYZ xyz = (space.Location as LocationPoint)?.Point; if (xyz == null) { continue; } double elevation_Top = double.NaN; Parameter parameter = space.get_Parameter(BuiltInParameter.ROOM_UPPER_LEVEL); if (parameter != null && parameter.HasValue) { ElementId elementId = parameter.AsElementId(); if (elementId != null && elementId != ElementId.InvalidElementId) { Level level = document.GetElement(elementId) as Level; if (level != null) { #if Revit2017 || Revit2018 || Revit2019 || Revit2020 elevation_Top = UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS); #else elevation_Top = UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters); #endif } } } BoundingBoxXYZ boundingBoxXYZ = space.get_BoundingBox(null); if (double.IsNaN(elevation_Top) && boundingBoxXYZ != null) { #if Revit2017 || Revit2018 || Revit2019 || Revit2020 elevation_Top = UnitUtils.ConvertFromInternalUnits(boundingBoxXYZ.Max.Z, DisplayUnitType.DUT_METERS); #else elevation_Top = UnitUtils.ConvertFromInternalUnits(boundingBoxXYZ.Max.Z, UnitTypeId.Meters); #endif } double elevation_Bottom = double.NaN; if (boundingBoxXYZ != null) { #if Revit2017 || Revit2018 || Revit2019 || Revit2020 elevation_Bottom = UnitUtils.ConvertFromInternalUnits(boundingBoxXYZ.Min.Z, DisplayUnitType.DUT_METERS); #else elevation_Bottom = UnitUtils.ConvertFromInternalUnits(boundingBoxXYZ.Min.Z, UnitTypeId.Meters); #endif } if (double.IsNaN(elevation_Bottom)) { ElementId elementId = space.LevelId; if (elementId != null && elementId != ElementId.InvalidElementId) { Level level = document.GetElement(elementId) as Level; #if Revit2017 || Revit2018 || Revit2019 || Revit2020 elevation_Bottom = UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS); #else elevation_Bottom = UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters); #endif } } Point3D point3D = Geometry.Revit.Convert.ToSAM(xyz); if (point3D == null) { continue; } Geometry.Planar.Point2D point2D = Geometry.Spatial.Plane.WorldXY.Convert(point3D); if (point2D == null) { continue; } #if Revit2017 || Revit2018 || Revit2019 || Revit2020 cutElevations.Add(UnitUtils.ConvertToInternalUnits(elevation_Bottom + offset, DisplayUnitType.DUT_METERS)); #else cutElevations.Add(UnitUtils.ConvertToInternalUnits(elevation_Bottom + offset, UnitTypeId.Meters)); #endif if (!dictionary.TryGetValue(elevation_Bottom, out List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > tuples)) { tuples = new List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> >(); dictionary[elevation_Bottom] = tuples; } tuples.Add(new Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space>(elevation_Top, point2D, space)); } //Collecting Revit Walls List <Autodesk.Revit.DB.Wall> walls = new FilteredElementCollector(document).OfClass(typeof(Autodesk.Revit.DB.Wall)).Cast <Autodesk.Revit.DB.Wall>().ToList(); if (walls == null || walls.Count == 0) { return(null); } //Converting Revit Walls to SAM Panels List <Panel> panels = new List <Panel>(); foreach (Autodesk.Revit.DB.Wall wall in walls) { BoundingBoxXYZ boundingBoxXYZ = wall?.get_BoundingBox(null); if (boundingBoxXYZ == null) { continue; } bool valid = false; foreach (double cutElevation in cutElevations) { if (boundingBoxXYZ.Max.Z >= cutElevation && boundingBoxXYZ.Min.Z <= cutElevation) { valid = true; break; } } if (!valid) { continue; } List <Panel> panels_Wall = wall.ToSAM(new Core.Revit.ConvertSettings(true, false, false)); if (panels_Wall == null || panels_Wall.Count == 0) { continue; } panels.AddRange(panels_Wall); } if (panels == null || panels.Count == 0) { return(null); } List <Shell> result = new List <Shell>(); //Inerating through elevations and Spaces data foreach (KeyValuePair <double, List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > > keyValuePair in dictionary) { double elevation_Bottom = keyValuePair.Key; double elevation_Cut = elevation_Bottom + offset; Geometry.Spatial.Plane plane_Cut = Geometry.Spatial.Plane.WorldXY.GetMoved(new Vector3D(0, 0, elevation_Cut)) as Geometry.Spatial.Plane; List <Geometry.Planar.Segment2D> segment2Ds = new List <Geometry.Planar.Segment2D>(); foreach (Panel panel in panels) { IClosedPlanar3D closedPlanar3D = panel?.GetFace3D()?.GetExternalEdge3D(); if (closedPlanar3D == null) { continue; } PlanarIntersectionResult planarIntersectionResult = plane_Cut.PlanarIntersectionResult(closedPlanar3D); if (planarIntersectionResult == null || !planarIntersectionResult.Intersecting) { continue; } List <Geometry.Planar.ISegmentable2D> segmentable2Ds_Temp = planarIntersectionResult.GetGeometry2Ds <Geometry.Planar.ISegmentable2D>(); if (segmentable2Ds_Temp == null || segmentable2Ds_Temp.Count == 0) { continue; } segmentable2Ds_Temp?.ForEach(x => segment2Ds.AddRange(x.GetSegments())); } if (panels == null || panels.Count == 0) { continue; } segment2Ds = Geometry.Planar.Query.Split(segment2Ds, tolerance); segment2Ds = Geometry.Planar.Query.Snap(segment2Ds, true, snapTolerance); List <Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> > tuples_Polygon2D = Geometry.Planar.Create.Polygon2Ds(segment2Ds)?.ConvertAll(x => new Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D>(x.GetBoundingBox(tolerance), x)); if (tuples_Polygon2D == null || tuples_Polygon2D.Count == 0) { continue; } Geometry.Spatial.Plane plane_Bottom = Geometry.Spatial.Plane.WorldXY.GetMoved(new Vector3D(0, 0, elevation_Bottom)) as Geometry.Spatial.Plane; List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > tuples_Space = keyValuePair.Value; while (tuples_Space.Count > 0) { Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> tuple = tuples_Space[0]; tuples_Space.RemoveAt(0); Geometry.Spatial.Plane plane_Top = Geometry.Spatial.Plane.WorldXY.GetMoved(new Vector3D(0, 0, tuple.Item1)) as Geometry.Spatial.Plane; Geometry.Planar.Point2D point2D = tuple.Item2; List <Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> > tuples_Polygon2D_External = tuples_Polygon2D.FindAll(x => x.Item1.Inside(point2D, tolerance)).FindAll(x => x.Item2.Inside(point2D, tolerance)); tuples_Polygon2D_External.Sort((x, y) => x.Item1.GetArea().CompareTo(y.Item1.GetArea())); Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> tuple_Polygon2D_External = tuples_Polygon2D_External.FirstOrDefault(); if (tuple_Polygon2D_External == null) { continue; } List <Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> > tuples_Polygon2D_Internal = new List <Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> >(); foreach (Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> tuple_Polygon2D in tuples_Polygon2D) { if (tuple_Polygon2D == tuple_Polygon2D_External) { continue; } if (tuple_Polygon2D_External.Item1.Inside(tuple_Polygon2D.Item1, tolerance) && tuple_Polygon2D_External.Item2.Inside(tuple_Polygon2D.Item2, tolerance)) { tuples_Polygon2D_Internal.Add(tuple_Polygon2D); } } List <Geometry.Planar.Face2D> face2Ds = Geometry.Planar.Query.Difference(new Geometry.Planar.Face2D(tuple_Polygon2D_External.Item2), tuples_Polygon2D_Internal.ConvertAll(x => new Geometry.Planar.Face2D(x.Item2)), tolerance); if (face2Ds == null || face2Ds.Count == 0) { continue; } foreach (Geometry.Planar.Face2D face2D in face2Ds) { tuples_Space.RemoveAll(x => face2D.Inside(x.Item2, tolerance)); } List <Face3D> face3Ds = new List <Face3D>(); face3Ds.AddRange(face2Ds.ConvertAll(x => new Face3D(plane_Bottom, x))); face3Ds.AddRange(face2Ds.ConvertAll(x => new Face3D(plane_Top, x))); List <Shell> shells_Temp = Geometry.Spatial.Create.Shells(face3Ds, new double[] { elevation_Bottom }, offset, snapTolerance: snapTolerance, tolerance_Distance: tolerance); if (shells_Temp == null || shells_Temp.Count == 0) { continue; } result.AddRange(shells_Temp); } } return(result); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; //选择一个点 Reference ref_point = uidoc.Selection.PickObject(ObjectType.PointOnElement); XYZ point1 = ref_point.GlobalPoint; //射线方向及工作平面法向量 XYZ rayDirection = XYZ.BasisZ; XYZ skVector = XYZ.BasisX; //当选择的主体为平面时,射线根据选择的点与此面的法线方向进行放射 if (ref_point.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_SURFACE) { PlanarFace pFace = null; //主体是链接的图元时,获取平面的方法 if (ref_point.LinkedElementId.IntegerValue != -1) { RevitLinkInstance linkIns = doc.GetElement(ref_point) as RevitLinkInstance; Document linkDoc = linkIns.GetLinkDocument(); Element linkElem = linkDoc.GetElement(ref_point.LinkedElementId); Options opt = new Options(); opt.DetailLevel = ViewDetailLevel.Fine; GeometryElement geomElem = linkElem.get_Geometry(opt); pFace = getTarFace(geomElem, point1); } else { //判断是否FamilyInstance类型的族,采用不同的获取方法 Element elem = doc.GetElement(ref_point); if (elem is FamilyInstance) { Options opt = new Options(); opt.DetailLevel = ViewDetailLevel.Fine; GeometryElement ge = elem.get_Geometry(opt); pFace = getTarFace(ge, point1); } else { pFace = elem.GetGeometryObjectFromReference(ref_point) as PlanarFace; } } //修正射线方向及工作平面法向量 if (pFace != null) { rayDirection = pFace.FaceNormal; skVector = pFace.XVector; } } //视图 View3D v3D = doc.ActiveView as View3D; //创建射线测量出第二点 ExclusionFilter filter = new ExclusionFilter(new ElementId[] { ref_point.ElementId, ref_point.LinkedElementId }); ReferenceIntersector refIntersector = new ReferenceIntersector(filter, FindReferenceTarget.All, v3D); refIntersector.FindReferencesInRevitLinks = true; ReferenceWithContext rwc = refIntersector.FindNearest(point1, rayDirection); if (rwc != null) { XYZ point2 = rwc.GetReference().GlobalPoint; //创建模型线 Line line = Line.CreateBound(point1, point2); TaskDialog.Show("距离", Math .Round(UnitUtils.ConvertFromInternalUnits(line.Length, DisplayUnitType.DUT_MILLIMETERS), 2).ToString()); using (Transaction tran = new Transaction(doc, "尺寸")) { tran.Start(); SketchPlane sk = SketchPlane.Create(doc, Plane.CreateByNormalAndOrigin(skVector, point1)); ModelCurve modelCurve = doc.Create.NewModelCurve(line, sk); tran.Commit(); } } else { TaskDialog.Show("返回结果", "为检测到图元"); } return(Result.Succeeded); }
public static double ToMeters(this double feet) { return(UnitUtils.ConvertFromInternalUnits(feet, DisplayUnitType.DUT_METERS)); }
public static void DimClrChngSuffix(Dimension dim, UIDocument uidoc) { //if empty add to cut brick list list //we could also check for multi dims and flag to user, poss with split method... if (dim.Value == null) { uidoc.ActiveView.SetElementOverrides(dim.Id, ClrSettings.ogsJoint()); //we could probably override suffixes here if we wanted...dim.Suffix = "Joint"; } else { //get dimension value in mm double dimValue = Convert.ToDouble(dim.Value); double dimValueMm = UnitUtils.ConvertFromInternalUnits(dimValue, UnitTypeId.Millimeters); double dimValueMmRnd = BrickFuncts.round(dimValueMm); //round to 1 dp if (dimValueMmRnd == 10) { //if value == 10, add item to cut brick list uidoc.ActiveView.SetElementOverrides(dim.Id, ClrSettings.ogsJoint()); dim.Suffix = "Joint"; } else { //divide by CO double dimCO = dimValueMmRnd / BrickFuncts.CO(1); //get math floor and set of CO values double dimCOflr = Math.Floor(dimCO); double dimCOflrCO = BrickFuncts.round(BrickFuncts.CO(dimCOflr)); double dimCOflrCOminus = BrickFuncts.round(BrickFuncts.COMinus(dimCOflr)); double dimCOflrCOPlus = BrickFuncts.round(BrickFuncts.COPlus(dimCOflr)); //get math ceiling and set of CO values double dimCOclng = Math.Ceiling(dimCO); double dimCOclngCO = BrickFuncts.round(BrickFuncts.CO(dimCOclng)); double dimCOclngCOminus = BrickFuncts.round(BrickFuncts.COMinus(dimCOclng)); double dimCOclngCOPlus = BrickFuncts.round(BrickFuncts.COPlus(dimCOclng)); if ((dimValueMmRnd == dimCOflrCO) || (dimValueMmRnd == dimCOclngCO)) { dim.Suffix = "CO"; uidoc.ActiveView.SetElementOverrides(dim.Id, ClrSettings.ogsCO()); } else if ((dimValueMmRnd == dimCOflrCOminus) || (dimValueMmRnd == dimCOclngCOminus)) { dim.Suffix = "CO-"; uidoc.ActiveView.SetElementOverrides(dim.Id, ClrSettings.ogsCOminus()); } else if ((dimValueMmRnd == dimCOflrCOPlus) || (dimValueMmRnd == dimCOclngCOPlus)) { dim.Suffix = "CO+"; uidoc.ActiveView.SetElementOverrides(dim.Id, ClrSettings.ogsCOplus()); } else { dim.Suffix = "cut"; uidoc.ActiveView.SetElementOverrides(dim.Id, ClrSettings.ogsCut()); } } //sb.AppendLine(dimValueMmRnd.ToString()); } }
public static List <Panel> ToSAM_Panels(this ModelCurve modelCurve, ConvertSettings convertSettings) { if (modelCurve == null) { return(null); } List <Panel> result = convertSettings?.GetObjects <Panel>(modelCurve.Id); if (result != null) { return(result); } List <Segment3D> segment3Ds = Geometry.Revit.Convert.ToSAM_Segment3Ds(modelCurve.GeometryCurve); if (segment3Ds == null || segment3Ds.Count == 0) { return(null); } PanelType panelType = PanelType.WallInternal; if (modelCurve.Category.Id.IntegerValue == (int)BuiltInCategory.OST_MEPSpaceSeparationLines || modelCurve.Category.Id.IntegerValue == (int)BuiltInCategory.OST_RoomSeparationLines) { panelType = PanelType.Air; } Construction construction = null; if (ActiveSetting.Setting.TryGetValue(AnalyticalSettingParameter.DefaultConstructionLibrary, out ConstructionLibrary constructionLibrary)) { construction = constructionLibrary.GetConstructions(panelType).FirstOrDefault(); } Document document = modelCurve.Document; result = new List <Panel>(); foreach (Segment3D segment3D in segment3Ds) { //double elevation_Min = System.Math.Max(segment3D[0].Z, segment3D[1].Z); double elevation_Min = (document.GetElement(modelCurve.LevelId) as Level).Elevation; //Level level_Max = Core.Revit.Query.HighLevel(document, UnitUtils.ConvertToInternalUnits(elevation_Min, DisplayUnitType.DUT_METERS)); Level level_Max = Core.Revit.Query.HighLevel(document, elevation_Min); if (level_Max == null) { continue; } #if Revit2017 || Revit2018 || Revit2019 || Revit2020 double height = UnitUtils.ConvertFromInternalUnits(level_Max.Elevation - elevation_Min, DisplayUnitType.DUT_METERS); #else double height = UnitUtils.ConvertFromInternalUnits(level_Max.Elevation - elevation_Min, UnitTypeId.Meters); #endif if (height == 0) { continue; } Vector3D vector3D = new Vector3D(0, 0, height); Face3D face3D = new Face3D(new Polygon3D(new Point3D[] { segment3D[0], segment3D[1], segment3D[1].GetMoved(vector3D) as Point3D, segment3D[0].GetMoved(vector3D) as Point3D })); Panel panel = Analytical.Create.Panel(construction, panelType, face3D); panel.UpdateParameterSets(modelCurve, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap), null, new string[] { "Length" }, true); panel.SetValue(RevitPanelParameter.Length, segment3D.GetLength()); result.Add(panel); } convertSettings?.Add(modelCurve.Id, result); return(result); }
public static Space ToSAM(this SpatialElement spatialElement, ConvertSettings convertSettings) { if (spatialElement == null) { return(null); } Point3D point3D = null; Space result = convertSettings?.GetObject <Space>(spatialElement.Id); if (result != null) { return(result); } if (spatialElement.Location != null) { point3D = ((LocationPoint)spatialElement.Location).Point.ToSAM(); } string name = Core.Revit.Query.Name(spatialElement); if (string.IsNullOrWhiteSpace(name)) { name = spatialElement.Name; } result = new Space(name, point3D); result.UpdateParameterSets(spatialElement, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap)); result.InternalCondition = ToSAM_InternalCondition(spatialElement, convertSettings); ElementId elementId_Level = spatialElement.LevelId; if (elementId_Level != null && elementId_Level != ElementId.InvalidElementId) { Level level = spatialElement.Document?.GetElement(elementId_Level) as Level; if (level != null) { result.SetValue(SpaceParameter.LevelName, level.Name); } } double area; if (!result.TryGetValue(SpaceParameter.Area, out area) || double.IsNaN(area) || area == 0) { result.SetValue(SpaceParameter.Area, UnitUtils.ConvertFromInternalUnits(spatialElement.Area, DisplayUnitType.DUT_SQUARE_METERS)); } double volume; if (!result.TryGetValue(SpaceParameter.Volume, out volume) || double.IsNaN(volume) || volume == 0) { Parameter parameter = spatialElement.get_Parameter(BuiltInParameter.ROOM_VOLUME); if (parameter != null && parameter.HasValue) { result.SetValue(SpaceParameter.Volume, UnitUtils.ConvertFromInternalUnits(parameter.AsDouble(), DisplayUnitType.DUT_CUBIC_METERS)); } } convertSettings?.Add(spatialElement.Id, result); return(result); }
/// <summary> /// Read all BuiltInCategory.OST_StructuralFoundation elements from a Revit model. /// </summary> private void ReadFoundations() { var collector = new FilteredElementCollector(a_doc); List <ElementFilter> filters = new List <ElementFilter>(); var filterCategory = new ElementCategoryFilter(BuiltInCategory.OST_StructuralFoundation); var filterNotSymbol = new ElementClassFilter(typeof(FamilySymbol), true); var filterNotFloorType = new ElementClassFilter(typeof(FloorType), true); var filterNotWallFoundationType = new ElementClassFilter(typeof(WallFoundationType), true); filters.Add(filterCategory); filters.Add(filterNotSymbol); filters.Add(filterNotFloorType); filters.Add(filterNotWallFoundationType); var filter = new LogicalAndFilter(filters); var elements = collector.WherePasses(filter).ToElements(); foreach (var element in elements) { try { if ((element is FamilyInstance || element is WallFoundation || element is Floor) && CheckElementPhase(element)) { var revitElement = new RevitElement(); revitElement.Category = RevitCategory.Foundation; revitElement.Id = element.Id.ToString(); revitElement.Name = element.Name; IList <Parameter> level = null; if (element is WallFoundation) { var wallFoundation = element as WallFoundation; var wallElement = a_doc.GetElement(wallFoundation.WallId); var temp = wallElement.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT); IList <Parameter> first = new List <Parameter>(); if (temp != null) { first.Add(temp); } level = first; } else { level = element.GetParameters("Level"); } Level levelElement = level.Count() > 0 ? a_doc.GetElement(level[0].AsElementId()) as Level : null; revitElement.AssociatedLevel = levelElement != null ? levelElement.Name : a_unknownLevelName; revitElement.AssociatedElevation = levelElement != null ? levelElement.ProjectElevation : a_unknownLevelElevation; revitElement.AssociatedLevel = GetMappedLevel(revitElement.AssociatedLevel); var elementVolume = element.GetParameters("Volume"); revitElement.Volume = elementVolume.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(elementVolume[0].AsDouble(), DisplayUnitType.DUT_CUBIC_FEET) : 0.0; var framingStructuralMaterial = this.GetStructuralMaterialFromElement(element, a_doc); revitElement.MaterialName = framingStructuralMaterial != null ? framingStructuralMaterial.Name : ""; revitElement.Material = framingStructuralMaterial != null?GetMaterialType(framingStructuralMaterial) : MaterialType.Unknown; double density = framingStructuralMaterial != null?GetDensity(framingStructuralMaterial) : 0.0; revitElement.Density = density; a_revitElementData.Add(revitElement); } } catch (Exception e) { ShowElementErrorMessage(element, e); } } }
/// <summary> /// Read all BuiltInCategory.OST_Walls elements from a Revit model. /// </summary> private void ReadWalls() { var collector = new FilteredElementCollector(a_doc); List <ElementFilter> filters = new List <ElementFilter>(); var filterCategory = new ElementCategoryFilter(BuiltInCategory.OST_Walls); var filterNotSymbol = new ElementClassFilter(typeof(FamilySymbol), true); var filterNotWallType = new ElementClassFilter(typeof(WallType), true); filters.Add(filterCategory); filters.Add(filterNotSymbol); filters.Add(filterNotWallType); var filter = new LogicalAndFilter(filters); var elements = collector.WherePasses(filter).ToElements(); foreach (var element in elements) { try { if (element is Wall && CheckElementPhase(element)) { var revitElement = new RevitElement(); revitElement.Category = RevitCategory.Wall; revitElement.Id = element.Id.ToString(); revitElement.Name = element.Name; var wallBaseConstraintParam = element.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT); Level wallBaseConstraintLevel = wallBaseConstraintParam != null?a_doc.GetElement(wallBaseConstraintParam.AsElementId()) as Level : null; revitElement.AssociatedLevel = wallBaseConstraintLevel != null ? wallBaseConstraintLevel.Name : a_unknownLevelName; revitElement.AssociatedElevation = wallBaseConstraintLevel != null ? wallBaseConstraintLevel.ProjectElevation : a_unknownLevelElevation; revitElement.AssociatedLevel = GetMappedLevel(revitElement.AssociatedLevel); var elementVolume = element.GetParameters("Volume"); revitElement.Volume = elementVolume.Count() > 0 ? UnitUtils.ConvertFromInternalUnits(elementVolume[0].AsDouble(), DisplayUnitType.DUT_CUBIC_FEET) : 0.0; var framingStructuralMaterial = this.GetStructuralMaterialFromElement(element, a_doc); revitElement.MaterialName = framingStructuralMaterial != null ? framingStructuralMaterial.Name : ""; revitElement.Material = framingStructuralMaterial != null?GetMaterialType(framingStructuralMaterial) : MaterialType.Unknown; double density = framingStructuralMaterial != null?GetDensity(framingStructuralMaterial) : 0.0; revitElement.Density = density; // Split Wall by Levels var unconnectedHeight = element.GetParameters("Unconnected Height"); // accounts for walls that have no top constraint assigned double wallHeight = unconnectedHeight.Count > 0 ? UnitUtils.ConvertFromInternalUnits(unconnectedHeight[0].AsDouble(), DisplayUnitType.DUT_DECIMAL_FEET) : 0; if (wallBaseConstraintLevel != null && wallHeight > 0 && a_levelData.Count > 0) { var wallBottomElevation = wallBaseConstraintLevel.ProjectElevation; var wallBottomOffset = element.GetParameters("Base Offset"); var baseOffset = wallBottomOffset.Count > 0 ? UnitUtils.ConvertFromInternalUnits(wallBottomOffset[0].AsDouble(), DisplayUnitType.DUT_DECIMAL_FEET) : 0; double wtrueBel = wallBottomElevation + baseOffset; // true bottom elevation of wall with model offset applied double wtrueTel = wtrueBel + wallHeight; // true top elevation of wall SplitByLevels(revitElement, wtrueBel, wtrueTel, wallHeight); } else { a_revitElementData.Add(revitElement); } } } catch (Exception e) { ShowElementErrorMessage(element, e); } } }
/// <summary> /// Get triangles in a solid with transform. /// </summary> /// <param name="solid">The solid contains triangulars</param> /// <param name="transform">The transformation.</param> private void GetTriangular(Document document, Solid solid, Transform transform) { // a solid has many faces FaceArray faces = solid.Faces; bool hasTransform = (null != transform); if (0 == faces.Size) { return; } foreach (Face face in faces) { if (face.Visibility != Visibility.Visible) { continue; } Mesh mesh = face.Triangulate(); if (null == mesh) { continue; } m_TriangularNumber += mesh.NumTriangles; PlanarFace planarFace = face as PlanarFace; // write face to stl file // a face has a mesh, all meshes are made of triangles for (int ii = 0; ii < mesh.NumTriangles; ii++) { MeshTriangle triangular = mesh.get_Triangle(ii); double[] xyz = new double[9]; Autodesk.Revit.DB.XYZ normal = new Autodesk.Revit.DB.XYZ(); try { Autodesk.Revit.DB.XYZ[] triPnts = new Autodesk.Revit.DB.XYZ[3]; for (int n = 0; n < 3; ++n) { double x, y, z; Autodesk.Revit.DB.XYZ point = triangular.get_Vertex(n); if (hasTransform) { point = transform.OfPoint(point); } if (m_Settings.ExportSharedCoordinates) { ProjectPosition ps = document.ActiveProjectLocation.GetProjectPosition(point); x = ps.EastWest; y = ps.NorthSouth; z = ps.Elevation; } else { x = point.X; y = point.Y; z = point.Z; } if (!m_Settings.Units.Empty()) { xyz[3 * n] = UnitUtils.ConvertFromInternalUnits(x, m_Settings.Units); xyz[3 * n + 1] = UnitUtils.ConvertFromInternalUnits(y, m_Settings.Units); xyz[3 * n + 2] = UnitUtils.ConvertFromInternalUnits(z, m_Settings.Units); } else { xyz[3 * n] = x; xyz[3 * n + 1] = y; xyz[3 * n + 2] = z; } var mypoint = new XYZ(xyz[3 * n], xyz[3 * n + 1], xyz[3 * n + 2]); triPnts[n] = mypoint; } Autodesk.Revit.DB.XYZ pnt1 = triPnts[1] - triPnts[0]; normal = pnt1.CrossProduct(triPnts[2] - triPnts[1]); } catch (Exception ex) { m_TriangularNumber--; STLDialogManager.ShowDebug(ex.Message); continue; } if (m_Writer is SaveDataAsBinary && m_Settings.ExportColor) { Material material = document.GetElement(face.MaterialElementId) as Material; if (material != null) { ((SaveDataAsBinary)m_Writer).Color = material.Color; } } m_Writer.WriteSection(normal, xyz); } } }
/// <summary> /// Get a dictionary of paramters and values which match those required by the node type /// defined in the schema /// </summary> /// <param name="node"></param> /// <param name="elm"></param> /// <param name="clientMapping"></param> /// <returns></returns> public static Dictionary <string, object> GetNodePropsWithElementProps(Node node, Element elm, IBuildingGraphSchema schema, BuildingGraphMapping clientMapping, bool includeOnlyMappedFields) { var elmParms = node.GetAllProperties(); if (elm != null && elm.Location is LocationPoint) { var lpt = (elm.Location as LocationPoint); var insPt = lpt.Point; if (!elmParms.ContainsKey("Location")) { elmParms.Add("Location", insPt.ToBuildingGraph()); } //if (!elmParms.ContainsKey("LocationRotation")) elmParms.Add("LocationRotation", lpt.Rotation); } else if (elm != null && elm.Location is LocationCurve) { //just start and end points for now var asCurve = (elm.Location as LocationCurve).Curve; var insPt = asCurve.GetEndPoint(0); if (!elmParms.ContainsKey("Location")) { elmParms.Add("Location", insPt.ToBuildingGraph()); } var endPt = asCurve.GetEndPoint(1); if (!elmParms.ContainsKey("LocationEnd")) { elmParms.Add("LocationEnd", endPt.ToBuildingGraph()); } var length = asCurve.Length; if (!elmParms.ContainsKey("length")) { elmParms.Add("Length", length); } var slope = Math.Abs(endPt.Z - insPt.Z) / length; if (!elmParms.ContainsKey("slope")) { elmParms.Add("slope", length); } } IBuildingGraphType bqType = schema != null?schema.GetBuildingGraphType(node.Label) : null; BuildingGraphMappedType clType = clientMapping != null?clientMapping.Types.FirstOrDefault(ct => ct.Name == node.Label) : null; foreach (var param in elm.Parameters.OfType <Parameter>()) { var hp = new HLRevitParameter(param); var paramName = Utils.GetGraphQLCompatibleFieldName(param.Definition.Name); var val = RevitToGraphValue(hp); if (bqType != null && clientMapping != null) { //resolve mapped field name if present if (clType != null) { var mappedFielName = clType.ValueMap.FirstOrDefault(vm => vm.Value == paramName); if (mappedFielName.Value == paramName) { paramName = mappedFielName.Key; } } var paramField = bqType.Fields.FirstOrDefault(fb => fb.Name == paramName); if (includeOnlyMappedFields && paramField == null) { continue; } //attempt to convert units if (val is double) { var fieldUnit = paramField.Args.FirstOrDefault(arg => arg.Name == "unit"); if (fieldUnit == null) { continue; } //var fieldUnitType = schema.GetBuildingGraphType(fieldUnit.TypeName); var unitMapping = clientMapping.Types.FirstOrDefault(tp => tp.Name == fieldUnit.TypeName); var defaultValue = fieldUnit.DefaultValue != null?fieldUnit.DefaultValue.ToString() : string.Empty; if (unitMapping != null && unitMapping.ValueMap.ContainsKey(fieldUnit.DefaultValue.ToString())) { var revitValue = unitMapping.ValueMap[defaultValue]; DisplayUnitType revitUnitTypeEnum; if (Enum.TryParse(revitValue, out revitUnitTypeEnum)) { //var type = Type.GetType(unitMapping.NativeType);// "Namespace.MyClass, MyAssembly"); val = UnitUtils.ConvertFromInternalUnits((double)val, revitUnitTypeEnum); } } } } if (!elmParms.ContainsKey(paramName)) { elmParms.Add(paramName, val); } } return(elmParms); }
/// <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) { GH_ObjectWrapper objectWrapper = null; if (!dataAccess.GetData(0, ref objectWrapper) || objectWrapper.Value == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data"); return; } Autodesk.Revit.DB.Level level = null; Document document = RhinoInside.Revit.Revit.ActiveDBDocument; if (document == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Cannot access Revit Document"); return; } dynamic obj = objectWrapper.Value; if (obj is GH_Integer) { ElementId elementId = new ElementId(((GH_Integer)obj).Value); if (elementId == null || elementId == ElementId.InvalidElementId) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Cannot access Element"); return; } level = document.GetElement(elementId) as Autodesk.Revit.DB.Level; } else if (obj is GH_String) { string @string = ((GH_String)obj).Value; if (@string.Length > 37) { @string = @string.Substring(37); } level = document.GetElement(@string) as Autodesk.Revit.DB.Level; } else if (obj.GetType().GetProperty("Id") != null) { ElementId aId = obj.Id as ElementId; level = document.GetElement(aId) as Autodesk.Revit.DB.Level; } if (level == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Cannot access Level"); return; } if (level == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data"); return; } Autodesk.Revit.DB.Level level_High = Core.Revit.Query.HighLevel(level); double elevation_High = double.NaN; if (level_High != null) { #if Revit2017 || Revit2018 || Revit2019 || Revit2020 elevation_High = UnitUtils.ConvertFromInternalUnits(level_High.Elevation, DisplayUnitType.DUT_METERS); #else elevation_High = UnitUtils.ConvertFromInternalUnits(level_High.Elevation, UnitTypeId.Meters); #endif } Autodesk.Revit.DB.Level level_Low = Core.Revit.Query.LowLevel(level); double elevation_Low = double.NaN; if (level_Low != null) { #if Revit2017 || Revit2018 || Revit2019 || Revit2020 elevation_Low = UnitUtils.ConvertFromInternalUnits(level_Low.Elevation, DisplayUnitType.DUT_METERS); #else elevation_Low = UnitUtils.ConvertFromInternalUnits(level_Low.Elevation, UnitTypeId.Meters); #endif } dataAccess.SetData(0, level_High); dataAccess.SetData(1, new GH_Number(elevation_High)); #if Revit2017 || Revit2018 || Revit2019 || Revit2020 dataAccess.SetData(2, new GH_Number(UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS))); #else dataAccess.SetData(2, new GH_Number(UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters))); #endif dataAccess.SetData(3, level_Low); dataAccess.SetData(4, new GH_Number(elevation_Low)); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; TransactionGroup tg = new TransactionGroup(doc); tg.Start(); Transaction t1 = new Transaction(doc, "Measure"); List <XYZ> points = new List <XYZ>(); bool stop = false; int count = 0; while (!stop) { Reference pointref = null; try { pointref = uidoc.Selection.PickObject(ObjectType.PointOnElement, "Pick points"); } catch { stop = true; } if (pointref != null) { XYZ p = pointref.GlobalPoint; if (p == null) { return(Result.Failed); } points.Add(p); t1.Start(); DrawCircles(doc, p); t1.Commit(); count++; if (count > 1) { t1.Start(); DrawLine(doc, points[count - 2], points[count - 1]); t1.Commit(); } } } DisplayUnit dunits = doc.DisplayUnitSystem; double distance = 0; for (int i = 0; i < points.Count - 1; i++) { distance += points[i].DistanceTo(points[i + 1]); } if (dunits == DisplayUnit.METRIC) { distance = Math.Round(UnitUtils.ConvertFromInternalUnits(distance, DisplayUnitType.DUT_METERS), 3); TaskDialog.Show("Measure Point to Point", "Total distance: " + distance.ToString() + " m"); } else { distance = Math.Round(distance, 3); TaskDialog.Show("Measure Point to Point", "Total distance: " + distance.ToString() + " ft"); } tg.RollBack(); return(Result.Succeeded); }
//The main method to excute. public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { #region Build the basic and filter the selection UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Document doc = uidoc.Document; // Access current selection Selection sel = uidoc.Selection; FilteredElementCollector col; // Retrieve elements from database£¨only choose room) try { col = new FilteredElementCollector(doc, sel.GetElementIds()) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_Rooms); } catch (Autodesk.Revit.Exceptions.ArgumentException ae) { TaskDialog.Show("Warning", "Please select at least one room.\n" + "Detail:" + ae.Message); return(Result.Failed); } #endregion #region Confirm selection.result in tdResult. // Write all the roomname into a string to confirm with the user. if (col.Count() == 0) { TaskDialog.Show("Warning", "No room is selected." + "This commend operates based on room."); return(Result.Failed); } string confirmMessage = "The following rooms are choosen, confirm?\n"; foreach (Element currentRoom in col) { Room roome = currentRoom as Room; confirmMessage = confirmMessage + roome.Name + "\n"; } //Pop up a dialog to confirm selection. TaskDialogResult tdResult = TaskDialog.Show("Revit", confirmMessage, TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No); if (tdResult == TaskDialogResult.No) { return(Result.Failed); } #endregion #region Load the family(into "panelRfa""basePanelSymbol") //Set directory for the family family_folder = Path.GetDirectoryName(doc.PathName); //check if the family already exist in the project Family panelRfa = FindElementByName (doc, typeof(Family), panelFamilyName) as Family; if (panelRfa == null) { //check for the file to load. if (!File.Exists(FamilyPath)) { TaskDialog.Show("Waning", "Please ensure the PanelAuto.rfa is " + "in the same folder with current project."); return(Result.Failed); } using (Transaction tx = new Transaction(doc)){ tx.Start("Load PanelAuto.Rfa"); doc.LoadFamily(FamilyPath, out panelRfa); tx.Commit(); } } ISet <ElementId> typeId = panelRfa.GetFamilySymbolIds(); FamilySymbol basePanelSymbol = doc .GetElement(typeId.FirstOrDefault()) as FamilySymbol; #endregion #region Ask for custom input double DistanceToWall = 0; double UnitWidth = 0; //Show a dialog to ask input from user. using (InputForm input = new InputForm()){ if (!(input.ShowDialog() == DialogResult.OK)) { return(Result.Failed); } DistanceToWall = UnitUtils.ConvertToInternalUnits ((double)input.DistanceToWall.Value, DisplayUnitType.DUT_MILLIMETERS); UnitWidth = UnitUtils.ConvertToInternalUnits ((double)input.UnitWidth.Value, DisplayUnitType.DUT_MILLIMETERS); } #endregion #region The main work. using (Transaction tx = new Transaction(doc)) { tx.Start("Create the panels"); //Store all the boundary segments of a room. List <EdgeSegment> roomSegments = new List <EdgeSegment>(); //Store all the Id of the panels created. List <ElementId> PanelIds = new List <ElementId>(); //Loop through each room foreach (Element currentRoom in col) { //Clear the data for the new room. roomSegments.Clear(); PanelIds.Clear(); //Step1-Get the raw data of each wall. roomSegments = GetRawData(currentRoom as Room, DistanceToWall, UnitWidth); foreach (EdgeSegment eSegment in roomSegments) { //Step2-Create ranges.In one range panels have same height //and are horizontally spread as evenly as possible if (!eSegment.NoPanel) { eSegment.DivideToPanelRange(); } //Step3-Create construction daga for each panel. foreach (PanelRange pR in eSegment.ranges) { eSegment.panels.AddRange (pR.CreatePanelDatas(UnitWidth, DistanceToWall)); } #region for demostration(while working) //XYZ normal = wall.normal; //XYZ origin = wall.start; //Plane plane = Plane.CreateByNormalAndOrigin(normal, origin); //SketchPlane sP = SketchPlane.Create(doc, plane); //foreach (PanelRange pRange in wall.ranges) //{ // doc.Create.NewModelCurveArray(pRange.GetRangeCurves(), sP); //} #endregion //Step 4-Create the panel instances. foreach (PanelData pData in eSegment.panels) { #region Only for demo while working /* * Plane tempP = Plane.CreateByNormalAndOrigin(pData.PaNormal, pData.PaOrigin); * SketchPlane sP = SketchPlane.Create(doc, tempP); * XYZ T = new XYZ(-pData.PaNormal.Y, pData.PaNormal.X, 0); * XYZ dl = pData.PaOrigin + 0.5 * pData.PaWidth * T; * XYZ dr = pData.PaOrigin - 0.5 * pData.PaWidth * T; * Transform up = Transform.CreateTranslation(new XYZ(0, 0, pData.PaHeight)); * XYZ ul = up.OfPoint(dl); * XYZ ur = up.OfPoint(dr); * Line l1 = Line.CreateBound(dl, ul); * Line l2 = Line.CreateBound(dr, ur); * doc.Create.NewModelCurve(l1, sP); * doc.Create.NewModelCurve(l2, sP); */ #endregion #region Create the panels //Convert the panelWidth and Height into mm //And create the name for the panel. int panelW_mm = (int)Math.Round(UnitUtils.ConvertFromInternalUnits (pData.PaWidth, DisplayUnitType.DUT_MILLIMETERS)); int panelH_mm = (int)Math.Round(UnitUtils.ConvertFromInternalUnits (pData.PaHeight, DisplayUnitType.DUT_MILLIMETERS)); string panelName = "P" + panelW_mm + "-" + panelH_mm; //Check if this type already exist FamilySymbol currentPanelSymbol = FindElementByName (doc, typeof(FamilySymbol), panelName) as FamilySymbol; if (currentPanelSymbol == null) { //Create a new one currentPanelSymbol = basePanelSymbol.Duplicate(panelName) as FamilySymbol; //modify the size of new symbol currentPanelSymbol.GetParameters("Height")[0].Set(pData.PaHeight); currentPanelSymbol.GetParameters("Width")[0].Set(pData.PaWidth); } //Create the actual instance FamilyInstance currentInst = doc.Create.NewFamilyInstance (pData.PaOrigin, currentPanelSymbol, StructuralType.NonStructural); //Rotate the instance to correct direction Line axis = Line.CreateBound(pData.PaOrigin, pData.PaOrigin + XYZ.BasisZ); //The AngleOnPlaneTo will create the angle from 0 to 2Pi double angle = new XYZ(0, -1, 0).AngleOnPlaneTo(pData.PaNormal, new XYZ(0, 0, 1)); ElementTransformUtils.RotateElement(doc, currentInst.Id, axis, angle); //log the panel id PanelIds.Add(currentInst.Id); #endregion } } //Group the panels of the same room. Group group = doc.Create.NewGroup(PanelIds); } tx.Commit(); } #endregion return(Result.Succeeded); }
public static double ConvertValueDocumentUnits(double decimalFeet, Autodesk.Revit.DB.Document document) { FormatOptions formatOption = document.GetUnits().GetFormatOptions(SpecTypeId.PipeSize); return(UnitUtils.ConvertFromInternalUnits(decimalFeet, formatOption.GetUnitTypeId())); }
public void ExportLinkedDocuments(Autodesk.Revit.DB.Document document, string fileName, Dictionary <ElementId, string> linksGUIDsCache, IFCExportOptions exportOptions) { // get the extension int index = fileName.LastIndexOf('.'); if (index <= 0) { return; } string sExtension = fileName.Substring(index); fileName = fileName.Substring(0, index); // get all the revit link instances FilteredElementCollector collector = new FilteredElementCollector(document); ElementFilter elementFilter = new ElementClassFilter(typeof(RevitLinkInstance)); List <RevitLinkInstance> rvtLinkInstances = collector.WherePasses(elementFilter).Cast <RevitLinkInstance>().ToList(); IDictionary <String, int> rvtLinkNamesDict = new Dictionary <String, int>(); IDictionary <String, List <RevitLinkInstance> > rvtLinkNamesToInstancesDict = new Dictionary <String, List <RevitLinkInstance> >(); try { // get the link types foreach (RevitLinkInstance rvtLinkInstance in rvtLinkInstances) { // get the instance if (rvtLinkInstance == null) { continue; } // check the cache if (linksGUIDsCache.Keys.Contains(rvtLinkInstance.Id) == false) { continue; } // get the link document Document linkDocument = rvtLinkInstance.GetLinkDocument(); if (linkDocument == null) { continue; } // get the link file path and name String linkPathName = ""; Parameter originalFileNameParam = linkDocument.ProjectInformation.LookupParameter("Original IFC File Name"); if (originalFileNameParam != null && originalFileNameParam.StorageType == StorageType.String) { linkPathName = originalFileNameParam.AsString(); } else { linkPathName = linkDocument.PathName; } // get the link file name String linkFileName = ""; index = linkPathName.LastIndexOf("\\"); if (index > 0) { linkFileName = linkPathName.Substring(index + 1); } else { linkFileName = linkDocument.Title; } // remove the extension index = linkFileName.LastIndexOf('.'); if (index > 0) { linkFileName = linkFileName.Substring(0, index); } // add to names count dictionary if (!rvtLinkNamesDict.Keys.Contains(linkFileName)) { rvtLinkNamesDict.Add(linkFileName, 0); } rvtLinkNamesDict[linkFileName]++; // add to names instances dictionary if (!rvtLinkNamesToInstancesDict.Keys.Contains(linkPathName)) { rvtLinkNamesToInstancesDict.Add(linkPathName, new List <RevitLinkInstance>()); } rvtLinkNamesToInstancesDict[linkPathName].Add(rvtLinkInstance); } } catch { } // get the link instances // We will keep track of the instances we can't export. // Reasons we can't export: // 1. The path for the linked instance doesn't exist. // 2. Couldn't create a temporary document for exporting the linked instance. // 3. The document for the linked instance can't be found. // 4. The linked instance is mirrored, non-conformal, or scaled. IList <string> pathDoesntExist = new List <string>(); IList <string> noTempDoc = new List <string>(); IList <ElementId> cantFindDoc = new List <ElementId>(); IList <ElementId> nonConformalInst = new List <ElementId>(); IList <ElementId> scaledInst = new List <ElementId>(); IList <ElementId> instHasReflection = new List <ElementId>(); foreach (String linkPathName in rvtLinkNamesToInstancesDict.Keys) { // get the name of the copy String linkPathNameCopy = System.IO.Path.GetTempPath(); index = linkPathName.LastIndexOf("\\"); if (index > 0) { linkPathNameCopy += linkPathName.Substring(index + 1); } else { linkPathNameCopy += linkPathName; } index = linkPathNameCopy.LastIndexOf('.'); if (index <= 0) { index = linkPathNameCopy.Length; } linkPathNameCopy = linkPathNameCopy.Insert(index, " - Copy"); int i = 1; while (File.Exists(linkPathNameCopy)) { linkPathNameCopy = linkPathNameCopy.Insert(index, "(" + (++i).ToString() + ")"); } // copy the file File.Copy(linkPathName, linkPathNameCopy); if (!File.Exists(linkPathNameCopy)) { pathDoesntExist.Add(linkPathName); continue; } // open the document Document documentCopy = null; try { if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") || (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") || (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip")) { documentCopy = document.Application.OpenIFCDocument(linkPathNameCopy); } else { documentCopy = document.Application.OpenDocumentFile(linkPathNameCopy); } } catch { documentCopy = null; } if (documentCopy == null) { noTempDoc.Add(linkPathName); continue; } // get the link document unit scale DisplayUnitType dutLink = documentCopy.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits; double lengthScaleFactorLink = UnitUtils.ConvertFromInternalUnits(1.0, dutLink); // get the link instances List <RevitLinkInstance> currRvtLinkInstances = rvtLinkNamesToInstancesDict[linkPathName]; IList <string> serTransforms = new List <string>(); IList <string> linkFileNames = new List <string>(); foreach (RevitLinkInstance currRvtLinkInstance in currRvtLinkInstances) { // Nothing to report if the element itself is null. if (currRvtLinkInstance == null) { continue; } // get the link document Document linkDocument = currRvtLinkInstance.GetLinkDocument(); if (linkDocument == null) { cantFindDoc.Add(currRvtLinkInstance.Id); continue; } // get the link transform Transform tr = currRvtLinkInstance.GetTransform(); // We can't handle non-conformal, scaled, or mirrored transforms. if (!tr.IsConformal) { nonConformalInst.Add(currRvtLinkInstance.Id); continue; } if (tr.HasReflection) { instHasReflection.Add(currRvtLinkInstance.Id); continue; } if (!MathUtil.IsAlmostEqual(tr.Determinant, 1.0)) { scaledInst.Add(currRvtLinkInstance.Id); continue; } // get the link file path and name String linkFileName = ""; index = linkPathName.LastIndexOf("\\"); if (index > 0) { linkFileName = linkPathName.Substring(index + 1); } else { linkFileName = linkDocument.Title; } // remove the extension index = linkFileName.LastIndexOf('.'); if (index > 0) { linkFileName = linkFileName.Substring(0, index); } //if link was an IFC file then make a different formating to the file name if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") || (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") || (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip")) { String fName = fileName; //get output path and add to the new file name index = fName.LastIndexOf("\\"); if (index > 0) { fName = fName.Substring(0, index + 1); } else { fName = ""; } //construct IFC file name linkFileName = fName + linkFileName + "-"; //add guid linkFileName += linksGUIDsCache[currRvtLinkInstance.Id]; } else { // check if there are multiple instances with the same name bool bMultiple = (rvtLinkNamesDict[linkFileName] > 1); // add the path linkFileName = fileName + "-" + linkFileName; // add the guid if (bMultiple) { linkFileName += "-"; linkFileName += linksGUIDsCache[currRvtLinkInstance.Id]; } } // add the extension linkFileName += sExtension; linkFileNames.Add(linkFileName); // scale the transform origin tr.Origin *= lengthScaleFactorLink; // serialize transform serTransforms.Add(SerializeTransform(tr)); } // IFC export requires an open transaction, although no changes should be made Transaction transaction = new Transaction(documentCopy, "Export IFC Link"); transaction.Start(); FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions(); failureOptions.SetClearAfterRollback(false); transaction.SetFailureHandlingOptions(failureOptions); // export try { int numLinkInstancesToExport = linkFileNames.Count; exportOptions.AddOption("NumberOfExportedLinkInstances", numLinkInstancesToExport.ToString()); for (int ii = 0; ii < numLinkInstancesToExport; ii++) { string optionName = (ii == 0) ? "ExportLinkInstanceTransform" : "ExportLinkInstanceTransform" + (ii + 1).ToString(); exportOptions.AddOption(optionName, serTransforms[ii]); // Don't pass in file name for the first link instance. if (ii == 0) { continue; } optionName = "ExportLinkInstanceFileName" + (ii + 1).ToString(); exportOptions.AddOption(optionName, linkFileNames[ii]); } // Pass in the first value; the rest will be in the options. String path_ = Path.GetDirectoryName(linkFileNames[0]); String fileName_ = Path.GetFileName(linkFileNames[0]); bool result = documentCopy.Export(path_, fileName_, exportOptions); // pass in the options here } catch { } // rollback the transaction transaction.RollBack(); // close the document documentCopy.Close(false); // delete the copy try { File.Delete(linkPathNameCopy); } catch { } // Show user errors, if any. int numBadInstances = pathDoesntExist.Count + noTempDoc.Count + cantFindDoc.Count + nonConformalInst.Count + scaledInst.Count + instHasReflection.Count; if (numBadInstances > 0) { using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport)) { taskDialog.MainInstruction = string.Format(Properties.Resources.LinkInstanceExportErrorMain, numBadInstances); taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning; taskDialog.TitleAutoPrefix = false; string expandedContent = ""; AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportErrorPath, pathDoesntExist); AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantCreateDoc, noTempDoc); AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantFindDoc, cantFindDoc); AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportNonConformal, nonConformalInst); AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportScaled, scaledInst); AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportHasReflection, instHasReflection); taskDialog.ExpandedContent = expandedContent; TaskDialogResult result = taskDialog.Show(); } } } }
private void SplitPipe( Element segment, MEPSystem _system, UIDocument _activeDoc, ElementId _systemtype, PipeType _pipeType ) { ElementId levelId = segment.get_Parameter( BuiltInParameter.RBS_START_LEVEL_PARAM ) .AsElementId(); // system.LevelId; ElementId systemtype = _system.GetTypeId(); // selecting one pipe and taking its location. Curve c1 = (segment.Location as LocationCurve).Curve; //Pipe diameter double pipeDia = UnitUtils.ConvertFromInternalUnits( segment.get_Parameter( BuiltInParameter.RBS_PIPE_DIAMETER_PARAM ).AsDouble(), DisplayUnitType.DUT_MILLIMETERS ); //Standard length double l = 6000; //Coupling length double fittinglength = (1.1 * pipeDia + 14.4); // finding the length of the selected pipe. double len = UnitUtils.ConvertFromInternalUnits( segment.get_Parameter( BuiltInParameter.CURVE_ELEM_LENGTH ).AsDouble(), DisplayUnitType.DUT_MILLIMETERS ); if( len <= l ) return; var startPoint = c1.GetEndPoint( 0 ); var endPoint = c1.GetEndPoint( 1 ); XYZ splitpoint = (endPoint - startPoint) * (l / len); var newpoint = startPoint + splitpoint; Pipe pp = segment as Pipe; // Find two connectors which pipe's two ends connector connected to. Connector startConn = FindConnectedTo( pp, startPoint ); Connector endConn = FindConnectedTo( pp, endPoint ); // creating first pipe Pipe pipe = null; if( null != _pipeType ) { pipe = Pipe.Create( _activeDoc.Document, _pipeType.Id, levelId, startConn, newpoint ); } Connector conn1 = FindConnector( pipe, newpoint ); //Check + fitting XYZ fittingend = (endPoint - startPoint) * ((l + (fittinglength / 2)) / len); //New point after the fitting gap var endOfFitting = startPoint + fittingend; Pipe pipe1 = Pipe.Create( _activeDoc.Document, systemtype, _pipeType.Id, levelId, endOfFitting, endPoint ); // Copy parameters from previous pipe to the following Pipe. CopyParameters( pipe, pipe1 ); Connector conn2 = FindConnector( pipe1, endOfFitting ); _ = _activeDoc.Document.Create.NewUnionFitting( conn1, conn2 ); if( null != endConn ) { Connector pipeEndConn = FindConnector( pipe1, endPoint ); pipeEndConn.ConnectTo( endConn ); } ICollection<ElementId> deletedIdSet = _activeDoc.Document.Delete( segment.Id ); if( 0 == deletedIdSet.Count ) { throw new Exception( "Deleting the selected elements in Revit failed." ); } if( UnitUtils.ConvertFromInternalUnits( pipe1.get_Parameter( BuiltInParameter.CURVE_ELEM_LENGTH ).AsDouble(), DisplayUnitType.DUT_MILLIMETERS ) > l ) { SplitPipe( pipe1, _system, _activeDoc, _systemtype, _pipeType ); } }
public static HostObject ToRevit(this Panel panel, Document document, Core.Revit.ConvertSettings convertSettings) { Geometry.Spatial.Face3D face3D = panel?.GetFace3D(); if (face3D == null) { return(null); } HostObject result = convertSettings?.GetObject <HostObject>(panel.Guid); if (result != null) { return(result); } PanelType panelType = panel.PanelType; Geometry.Spatial.Vector3D normal = panel.Normal; HostObjAttributes hostObjAttributes = panel.Construction.ToRevit(document, panelType, normal, convertSettings); if (hostObjAttributes == null) { hostObjAttributes = Analytical.Query.DefaultConstruction(panelType)?.ToRevit(document, panelType, normal, convertSettings); //Default Construction } BuiltInParameter[] builtInParameters = null; if (hostObjAttributes is Autodesk.Revit.DB.WallType) { double lowElevation = panel.LowElevation(); Level level = document.LowLevel(lowElevation); Autodesk.Revit.DB.Wall wall = ToRevit_Wall(face3D, document, (Autodesk.Revit.DB.WallType)hostObjAttributes, level); if (wall == null) { return(result); } //List<Curve> curveList = new List<Curve>(); //foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D in face3D.GetEdge3Ds()) //{ // if (Geometry.Spatial.Query.Clockwise(closedPlanar3D)) // closedPlanar3D.Reverse(); // List<Line> lines = closedPlanar3D.ToRevit(); // if (lines == null) // continue; // curveList.AddRange(lines); //} //if (curveList == null || curveList.Count == 0) // return null; //double lowElevation = panel.LowElevation(); //Level level = document.LowLevel(lowElevation); //if (level == null) // return null; //Wall wall = Wall.Create(document, curveList, hostObjAttributes.Id, level.Id, false, panel.Normal.ToRevit(false)); Parameter parameter = null; parameter = wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE); if (parameter != null) { parameter.Set(ElementId.InvalidElementId); } parameter = wall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM); if (parameter != null) { #if Revit2017 || Revit2018 || Revit2019 || Revit2020 double height = UnitUtils.ConvertToInternalUnits((panel.HighElevation() - lowElevation), DisplayUnitType.DUT_METERS); #else double height = UnitUtils.ConvertToInternalUnits((panel.HighElevation() - lowElevation), UnitTypeId.Meters); #endif parameter.Set(height); } #if Revit2017 || Revit2018 || Revit2019 || Revit2020 double levelElevation = UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS); #else double levelElevation = UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters); #endif if (Math.Abs(lowElevation - levelElevation) > Core.Tolerance.MacroDistance) { parameter = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET); if (parameter != null) { #if Revit2017 || Revit2018 || Revit2019 || Revit2020 parameter.Set(UnitUtils.ConvertToInternalUnits(lowElevation - levelElevation, DisplayUnitType.DUT_METERS)); #else parameter.Set(UnitUtils.ConvertToInternalUnits(lowElevation - levelElevation, UnitTypeId.Meters)); #endif } } builtInParameters = new BuiltInParameter[] { BuiltInParameter.WALL_BASE_CONSTRAINT, BuiltInParameter.WALL_BASE_OFFSET, BuiltInParameter.WALL_HEIGHT_TYPE, BuiltInParameter.WALL_USER_HEIGHT_PARAM, BuiltInParameter.WALL_KEY_REF_PARAM }; result = wall; } else if (hostObjAttributes is Autodesk.Revit.DB.FloorType) { Geometry.Spatial.IClosedPlanar3D closedPlanar3D_External = face3D.GetExternalEdge3D(); if (!(closedPlanar3D_External is Geometry.Spatial.ICurvable3D)) { return(null); } double elevation = panel.LowElevation(); Level level = document.HighLevel(elevation); Geometry.Spatial.Plane plane = new Geometry.Spatial.Plane(new Geometry.Spatial.Point3D(0, 0, elevation), Geometry.Spatial.Vector3D.WorldZ); CurveArray curveArray_Sloped = new CurveArray(); CurveArray curveArray_Plane = new CurveArray(); Geometry.Spatial.IClosedPlanar3D closedPlanar3D = face3D.GetExternalEdge3D(); if (!(closedPlanar3D is Geometry.Spatial.ICurvable3D)) { return(null); } List <Geometry.Spatial.Segment3D> segment3Ds = Geometry.Revit.Query.Segment3Ds(closedPlanar3D); if (segment3Ds == null || segment3Ds.Count == 0) { return(null); } foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds) { curveArray_Sloped.Append(segment3D.ToRevit_Line()); Geometry.Spatial.Segment3D segment3D_Temp = Geometry.Spatial.Query.Project(plane, segment3D); if (segment3D_Temp == null) { continue; } curveArray_Plane.Append(segment3D_Temp.ToRevit_Line()); } #if Revit2017 || Revit2018 || Revit2019 || Revit2020 || Revit2021 Autodesk.Revit.DB.Floor floor = document.Create.NewFloor(curveArray_Plane, hostObjAttributes as Autodesk.Revit.DB.FloorType, level, false); #else CurveLoop curveLoop = new CurveLoop(); foreach (Curve curve in curveArray_Plane) { curveLoop.Append(curve); } Autodesk.Revit.DB.Floor floor = Autodesk.Revit.DB.Floor.Create(document, new CurveLoop[] { curveLoop }, hostObjAttributes.Id, level.Id); #endif if (floor != null) { floor.ChangeTypeId(hostObjAttributes.Id); List <Geometry.Spatial.IClosedPlanar3D> closedPlanar3Ds_Internal = face3D.GetInternalEdge3Ds(); if (closedPlanar3Ds_Internal != null && closedPlanar3Ds_Internal.Count > 0) { //Requires to be regenerated before inserting openings //https://thebuildingcoder.typepad.com/blog/2013/07/create-a-floor-with-an-opening-or-complex-boundary.html document.Regenerate(); foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D_Internal in face3D.GetInternalEdge3Ds()) { List <Geometry.Spatial.Segment3D> segment3Ds_Internal = Geometry.Revit.Query.Segment3Ds(closedPlanar3D_Internal); if (segment3Ds_Internal == null || segment3Ds_Internal.Count == 0) { continue; } curveArray_Plane = new CurveArray(); //foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds) foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds_Internal) { curveArray_Sloped.Append(segment3D.ToRevit_Line()); Geometry.Spatial.Segment3D segment3D_Temp = Geometry.Spatial.Query.Project(plane, segment3D); if (segment3D_Temp == null) { continue; } curveArray_Plane.Append(segment3D_Temp.ToRevit_Line()); } Opening opening = document.Create.NewOpening(floor, curveArray_Plane, true); } } } if (floor != null) { document.Regenerate(); SlabShapeEditor slabShapeEditor = floor.SlabShapeEditor; if (slabShapeEditor != null) { slabShapeEditor.ResetSlabShape(); foreach (Curve curve in curveArray_Sloped) { XYZ xYZ = curve.GetEndPoint(0); slabShapeEditor.DrawPoint(xYZ); } } } builtInParameters = new BuiltInParameter[] { BuiltInParameter.LEVEL_PARAM }; result = floor; } else if (hostObjAttributes is Autodesk.Revit.DB.RoofType) { CurveArray curveArray = new CurveArray(); foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D in face3D.GetEdge3Ds()) { List <Geometry.Spatial.Segment3D> segment3Ds = Geometry.Revit.Query.Segment3Ds(closedPlanar3D); if (segment3Ds == null || segment3Ds.Count == 0) { return(null); } segment3Ds.ForEach(x => curveArray.Append(x.ToRevit_Line())); } Level level = document.HighLevel(panel.LowElevation()); double levelElevation = level.Elevation; ModelCurveArray modelCurveArray = new ModelCurveArray(); RoofBase roofBase = document.Create.NewFootPrintRoof(curveArray, level, hostObjAttributes as Autodesk.Revit.DB.RoofType, out modelCurveArray); Parameter parameter = roofBase.get_Parameter(BuiltInParameter.ROOF_UPTO_LEVEL_PARAM); if (parameter != null) { parameter.Set(ElementId.InvalidElementId); } SlabShapeEditor slabShapeEditor = roofBase.SlabShapeEditor; if (slabShapeEditor != null) { slabShapeEditor.ResetSlabShape(); foreach (Curve curve in curveArray) { XYZ xYZ = curve.GetEndPoint(0); //if (Math.Abs(xYZ.Z - levelElevation) > Core.Tolerance.MicroDistance) slabShapeEditor.DrawPoint(xYZ); } } builtInParameters = new BuiltInParameter[] { BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM, BuiltInParameter.ROOF_BASE_LEVEL_PARAM, BuiltInParameter.ROOF_UPTO_LEVEL_PARAM }; result = roofBase; } if (result == null) { return(null); } List <Aperture> apertures = panel.Apertures; if (apertures != null) { if (result is Autodesk.Revit.DB.Wall && ((Autodesk.Revit.DB.Wall)result).WallType.Kind == WallKind.Curtain) { } else { foreach (Aperture aperture in apertures) { Geometry.Spatial.Plane plane_Aperture = aperture?.PlanarBoundary3D?.Plane; if (plane_Aperture == null) { continue; } //bool flipHand = !plane_Panel.AxisX.SameHalf(plane_Aperture.AxisX); //bool flipFacing = !plane_Panel.Normal.SameHalf(plane_Aperture.Normal); FamilyInstance failyInstance_Aperture = aperture.ToRevit(document, result, convertSettings); } } } if (convertSettings.ConvertParameters) { Core.Revit.Modify.SetValues(result, panel, builtInParameters); Core.Revit.Modify.SetValues(result, panel, ActiveSetting.Setting); Core.Revit.Modify.SetJson(result, panel.ToJObject()?.ToString()); } //TODO: Implement proper log //System.IO.File.AppendAllText(@"C:\Users\DengusiakM\Desktop\SAM\2020-04-16 floorbug\LOG.txt", string.Format("{0}\t{1}\t{2}\n", DateTime.Now.ToString(), panel.Guid, panel.Name)); convertSettings?.Add(panel.Guid, result); return(result); }
public static Construction ToSAM(this HostObjAttributes hostObjAttributes, ConvertSettings convertSettings) { if (hostObjAttributes == null) { return(null); } Construction result = convertSettings?.GetObject <Construction>(hostObjAttributes.Id); if (result != null) { return(result); } string name = hostObjAttributes.Name; PanelType panelType = hostObjAttributes.PanelType(); if (panelType == PanelType.Undefined) { panelType = Query.PanelType((BuiltInCategory)hostObjAttributes.Category.Id.IntegerValue); } Construction construction = Analytical.Query.DefaultConstruction(panelType); if (construction != null && (name.Equals(construction.Name) || name.Equals(construction.UniqueName()))) { result = new Construction(construction); } else { result = new Construction(hostObjAttributes.Name); } result.UpdateParameterSets(hostObjAttributes, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap)); //result.Add(Core.Revit.Query.ParameterSet(hostObjAttributes)); convertSettings?.Add(hostObjAttributes.Id, result); if (panelType != PanelType.Undefined) { result.SetValue(ConstructionParameter.DefaultPanelType, panelType.Text()); } else { result.SetValue(ConstructionParameter.DefaultPanelType, null); } List <ConstructionLayer> constructionLayers = result.ConstructionLayers; if (constructionLayers != null && constructionLayers.Count != 0) { result.SetValue(ConstructionParameter.DefaultThickness, constructionLayers.ConvertAll(x => x.Thickness).Sum()); } else { CompoundStructure compoundStructure = hostObjAttributes.GetCompoundStructure(); if (compoundStructure != null) { #if Revit2017 || Revit2018 || Revit2019 || Revit2020 double thickness = UnitUtils.ConvertFromInternalUnits(compoundStructure.GetWidth(), DisplayUnitType.DUT_METERS); #else double thickness = UnitUtils.ConvertFromInternalUnits(compoundStructure.GetWidth(), UnitTypeId.Meters); #endif result.SetValue(ConstructionParameter.DefaultThickness, thickness); } } return(result); }
public void ExportDataHydro() { ExternalCommandData revit = Transfer.revit; UIApplication uiApp = revit.Application; Document doc = uiApp.ActiveUIDocument.Document; Selection sel = uiApp.ActiveUIDocument.Selection; List <BuiltInCategory> listCategories = new List <BuiltInCategory>() { BuiltInCategory.OST_PipeCurves, BuiltInCategory.OST_PipeFitting, BuiltInCategory.OST_PipeAccessory, BuiltInCategory.OST_FlexPipeCurves }; LibCategories libCategories = new LibCategories(); List <Element> listElements = libCategories.AllElnewe(doc, listCategories).ToList(); if (listElements[0].LookupParameter("entools_number") == null) { TaskDialog.Show("Error", "Parameter entools_number missing."); return; } listElements = listElements.OrderBy(x => int.Parse(x.LookupParameter("entools_number").AsValueString())).ToList(); const BuiltInParameter bipSyst = BuiltInParameter.RBS_DUCT_PIPE_SYSTEM_ABBREVIATION_PARAM; const BuiltInParameter bipDiameterInner = BuiltInParameter.RBS_PIPE_INNER_DIAM_PARAM; const BuiltInParameter bipLength = BuiltInParameter.CURVE_ELEM_LENGTH; const BuiltInParameter bipSize = BuiltInParameter.RBS_CALCULATED_SIZE; const BuiltInParameter minSize = BuiltInParameter.RBS_PIPE_SIZE_MINIMUM; const BuiltInParameter maxSize = BuiltInParameter.RBS_PIPE_SIZE_MAXIMUM; var listId = new List <object>(); var listName = new List <object>(); var listType = new List <object>(); var listDo = new List <object>(); var listDi = new List <object>(); var listLength = new List <object>(); var listKvs = new List <object>(); try { Reference selection = sel.PickObject(ObjectType.Element, "Select element of system"); Element element = doc.GetElement(selection); string stype = element.get_Parameter(bipSyst).AsString(); string i = string.Empty; string getType = string.Empty; double getLen; double dinner; string size = string.Empty; string minsize = string.Empty; string maxsize = string.Empty; string id = string.Empty; listElements = listElements.Where(x => x.get_Parameter(bipSyst).AsString() == stype).ToList(); foreach (Element pipe in listElements) { if (pipe.LookupParameter("entools_number") == null) { TaskDialog.Show("Error", "Parameter entools_number missing."); break; } else { getType = pipe.get_Parameter(bipSyst).AsString(); i = pipe.LookupParameter("entools_number").AsValueString(); size = pipe.get_Parameter(bipSize).AsString(); Category category = pipe.Category; BuiltInCategory builtInCategory = (BuiltInCategory)category.Id.IntegerValue; if (builtInCategory == BuiltInCategory.OST_PipeCurves) { id = pipe.Id.ToString(); getLen = pipe.get_Parameter(bipLength).AsDouble(); dinner = pipe.get_Parameter(bipDiameterInner).AsDouble(); getLen = Math.Round(UnitUtils.ConvertFromInternalUnits(getLen, DisplayUnitType.DUT_MILLIMETERS), 0); dinner = Math.Round(UnitUtils.ConvertFromInternalUnits(dinner, DisplayUnitType.DUT_MILLIMETERS), 1); listName.Add(getType + ":" + i.ToString()); listId.Add(pipe.Id.ToString()); listType.Add("PIP"); listDo.Add(size.Replace('.', ',')); listDi.Add(dinner.ToString().Replace('.', ',')); listLength.Add(getLen.ToString().Replace('.', ',')); listKvs.Add(pipe.LookupParameter("entools_kvse").AsValueString()); } if (builtInCategory == BuiltInCategory.OST_PipeFitting) { minsize = pipe.get_Parameter(minSize).AsValueString(); maxsize = pipe.get_Parameter(maxSize).AsValueString(); listName.Add(getType + ":" + i.ToString()); listId.Add(pipe.Id.ToString()); listType.Add("FIT"); listDo.Add(maxsize.Replace('.', ',') + "-" + minsize.Replace('.', ',')); listDi.Add(minsize.Replace('.', ',')); listLength.Add("-"); listKvs.Add(pipe.LookupParameter("entools_kvse").AsValueString()); } if (builtInCategory == BuiltInCategory.OST_PipeAccessory) { listName.Add(getType + ":" + i.ToString()); listId.Add(pipe.Id.ToString()); listType.Add("ACC"); listDo.Add(size); listDi.Add("-"); listLength.Add("-"); listKvs.Add(pipe.LookupParameter("entools_kvse").AsValueString()); } if (builtInCategory == BuiltInCategory.OST_FlexPipeCurves) { getLen = pipe.get_Parameter(bipLength).AsDouble(); dinner = pipe.get_Parameter(bipDiameterInner).AsDouble(); getLen = Math.Round(UnitUtils.ConvertFromInternalUnits(getLen, DisplayUnitType.DUT_MILLIMETERS), 0); dinner = Math.Round(UnitUtils.ConvertFromInternalUnits(dinner, DisplayUnitType.DUT_MILLIMETERS), 1); listName.Add(getType + ":" + i.ToString()); listId.Add(pipe.Id.ToString()); listType.Add("FLE"); listDo.Add(size.Replace('.', ',')); listDi.Add(dinner.ToString()); listLength.Add(getLen.ToString()); listKvs.Add("-"); } } } ExportGD(listName, listType, listId, listDo, listDi, listLength, listKvs); } catch (Exception ex) { MessageBox.Show(ex.StackTrace); TaskDialog.Show("Report", "Canceled"); } }
/// <summary> /// Generate Viewpoint /// </summary> /// <param name="elemCheck"></param> /// <returns></returns> private VisualizationInfo generateViewpoint(int elemCheck) { try { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; VisualizationInfo v = new VisualizationInfo(); XYZ centerIMP = new XYZ(); string type = ""; double zoomValue = 1; if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view { XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0]; XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1]; v.SheetCamera = new SheetCamera(); v.SheetCamera.SheetID = uidoc.ActiveView.Id.IntegerValue; v.SheetCamera.TopLeft = new IssueTracker.Classes.Point(TL.X, TL.Y, TL.Z); v.SheetCamera.BottomRight = new IssueTracker.Classes.Point(BR.X, BR.Y, BR.Z); } else { View3D view3D = (View3D)uidoc.ActiveView; if (!view3D.IsPerspective) //IS ORTHO { XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0]; XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1]; double xO = (TL.X + BR.X) / 2; double yO = (TL.Y + BR.Y) / 2; double zO = (TL.Z + BR.Z) / 2; //converto to METERS centerIMP = new XYZ(xO, yO, zO); double dist = TL.DistanceTo(BR) / 2; //custom sectet value to get solibri zoom value from Corners of Revit UiView XYZ diagVector = TL.Subtract(BR); // **** CUSTOM VALUE FOR TEKLA **** // //zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS); // **** CUSTOM VALUE FOR TEKLA **** // double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5; zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue; type = "OrthogonalCamera"; } else // it is a perspective view { centerIMP = uidoc.ActiveView.Origin; type = "PerspectiveCamera"; zoomValue = 45; } ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false); //ViewOrientation3D t = new ViewOrientation3D(centerIMP, uidoc.ActiveView.UpDirection, uidoc.ActiveView.ViewDirection); XYZ c = t.EyePosition; XYZ vi = t.ForwardDirection; XYZ up = t.UpDirection; if (type == "OrthogonalCamera") { v.OrthogonalCamera = new OrthogonalCamera(); v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS); v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS); v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS); v.OrthogonalCamera.CameraUpVector.X = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS); v.OrthogonalCamera.CameraUpVector.Y = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS); v.OrthogonalCamera.CameraUpVector.Z = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS); v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1; v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1; v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1; v.OrthogonalCamera.ViewToWorldScale = zoomValue; } else { v.PerspectiveCamera = new PerspectiveCamera(); v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS); v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS); v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS); v.PerspectiveCamera.CameraUpVector.X = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS); v.PerspectiveCamera.CameraUpVector.Y = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS); v.PerspectiveCamera.CameraUpVector.Z = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS); v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1; v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1; v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1; v.PerspectiveCamera.FieldOfView = zoomValue; } } //COMPONENTS PART FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType(); System.Collections.Generic.ICollection <ElementId> collection = null; if (elemCheck == 0) { collection = collector.ToElementIds(); } else if (elemCheck == 1) { collection = uidoc.Selection.GetElementIds(); } if (null != collection && collection.Any()) { v.Components = new IssueTracker.Classes.Component[collection.Count]; for (var i = 0; i < collection.Count; i++) { Guid guid = ExportUtils.GetExportId(doc, collection.ElementAt(i)); string ifcguid = IfcGuid.ToIfcGuid(guid).ToString(); ; v.Components[i] = new ARUP.IssueTracker.Classes.Component(doc.Application.VersionName, collection.ElementAt(i).ToString(), ifcguid); } } return(v); } catch (System.Exception ex1) { TaskDialog.Show("Error!", "exception: " + ex1); } return(null); }
// TODO: Wall to Speckle // TODO: Set levels, heights, etc. // Does not go through nicely from revit to revit public static SpeckleElementsClasses.Wall ToSpeckle(this Autodesk.Revit.DB.Wall myWall) { var speckleWall = new SpeckleElementsClasses.Wall(); speckleWall.baseCurve = SpeckleCore.Converter.Serialise(((LocationCurve)myWall.Location).Curve) as SpeckleObject; var heightParam = myWall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM); var heightValue = heightParam.AsDouble(); var height = UnitUtils.ConvertFromInternalUnits(heightValue, heightParam.DisplayUnitType); speckleWall.height = heightValue / Scale; var offsetParam = myWall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET); var offsetValue = offsetParam.AsDouble(); var offset = UnitUtils.ConvertFromInternalUnits(offsetValue, offsetParam.DisplayUnitType); speckleWall.offset = offsetValue / Scale; speckleWall.wallType = myWall.WallType.Name; var level = (Level)Doc.GetElement(myWall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId()); speckleWall.baseLevel = level.ToSpeckle(); try { var topLevel = (Level)Doc.GetElement(myWall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId()); speckleWall.topLevel = topLevel.ToSpeckle(); } catch (Exception e) { } speckleWall.parameters = GetElementParams(myWall); speckleWall.typeParameters = GetElementTypeParams(myWall); var grid = myWall.CurtainGrid; // TODO: Should move maybe in base class defintion speckleWall.Properties["__flipped"] = myWall.Flipped; speckleWall.ApplicationId = myWall.UniqueId; speckleWall.elementId = myWall.Id.ToString(); speckleWall.GenerateHash(); // meshing for walls in case they are curtain grids if (grid != null) { var mySolids = new List <Solid>(); foreach (ElementId panelId in grid.GetPanelIds()) { mySolids.AddRange(GetElementSolids(Doc.GetElement(panelId))); } foreach (ElementId mullionId in grid.GetMullionIds()) { mySolids.AddRange(GetElementSolids(Doc.GetElement(mullionId))); } (speckleWall.Faces, speckleWall.Vertices) = GetFaceVertexArrFromSolids(mySolids); } else { (speckleWall.Faces, speckleWall.Vertices) = GetFaceVertexArrayFromElement(myWall, new Options() { DetailLevel = ViewDetailLevel.Fine, ComputeReferences = false }); } return(speckleWall); }
public static SpeckleObject ColumnToSpeckle(Autodesk.Revit.DB.FamilyInstance myFamily) { var myColumn = new Column(); var baseLevel = (Autodesk.Revit.DB.Level)Doc.GetElement(myFamily.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId()); var topLevel = (Autodesk.Revit.DB.Level)Doc.GetElement(myFamily.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId()); myColumn.baseLevel = baseLevel?.ToSpeckle(); myColumn.topLevel = topLevel?.ToSpeckle(); try { myColumn.baseLine = (SpeckleCoreGeometryClasses.SpeckleLine)SpeckleCore.Converter.Serialise(myFamily.GetAnalyticalModel().GetCurve()); } catch { var basePt = (myFamily.Location as LocationPoint).Point; var topPt = new XYZ(basePt.X, basePt.Y, topLevel.Elevation); myColumn.baseLine = (SpeckleCoreGeometryClasses.SpeckleLine)SpeckleCore.Converter.Serialise(Autodesk.Revit.DB.Line.CreateBound(basePt, topPt)); } myColumn.columnFamily = myFamily.Symbol.FamilyName; myColumn.columnType = Doc.GetElement(myFamily.GetTypeId()).Name; myColumn.parameters = GetElementParams(myFamily); // TODO: Maybe move this column properties in the class defintion myColumn.Properties["__facingFlipped"] = myFamily.FacingFlipped; myColumn.Properties["__handFlipped"] = myFamily.HandFlipped; if (myFamily.Location is LocationPoint) { myColumn.Properties["__rotation"] = ((LocationPoint)myFamily.Location).Rotation; } else if (myFamily.Location is LocationCurve) { var myAngle = myFamily.get_Parameter(BuiltInParameter.STRUCTURAL_BEND_DIR_ANGLE).AsDouble(); // Stands for cross-section rotation! var rads = UnitUtils.ConvertFromInternalUnits(myAngle, DisplayUnitType.DUT_RADIANS); myColumn.Properties["__rotation"] = rads; // TODO: Figure this column rotation shit out. // For now... Do nothing?? //var t = myFamily.GetTotalTransform(); } myColumn.GenerateHash(); myColumn.ApplicationId = myFamily.UniqueId; myColumn.elementId = myFamily.Id.ToString(); // leaving the mesh out of the hashing process might address the randomatic hash generation we're getting // and hence the nuking the usability of local caching and diffing var allSolids = GetElementSolids(myFamily, opt: new Options() { DetailLevel = ViewDetailLevel.Fine, ComputeReferences = true }); (myColumn.Faces, myColumn.Vertices) = GetFaceVertexArrFromSolids(allSolids); return(myColumn); }
public static (Dictionary <string, List <double> >, Dictionary <ElementId, List <double> >, Dictionary <ElementId, Dictionary <string, double> >) BureauLot(List <Document> docs) { // creation des dicos Dictionary <string, List <double> > dicolotsurface = new Dictionary <string, List <double> >(); // LOT ET SURFACE BUREAU ET REUNION Dictionary <ElementId, List <double> > dicolevelsurface = new Dictionary <ElementId, List <double> >(); // ETAGE ET SURFACE BUREAU ET REUNION Dictionary <ElementId, Dictionary <string, double> > dicolotlevel = new Dictionary <ElementId, Dictionary <string, double> >(); // ETAGE ET DICO LOT ET SURFACE //Liste pour compte 1 seule fois chaque piece List <int> pieceids = new List <int>(); //On liste les erreurs int nombreerreur = 0; List <string> messageerreur = new List <string>(); //On passe tous les documents foreach (Document doc in docs) { FilteredElementCollector pieces = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType(); foreach (Element piece in pieces) { try { //on check si la piece a deja ete compté if (pieceids.Contains(piece.Id.IntegerValue)) { continue; } // on check que le parametre "Service" n'est pas nul if (piece.get_Parameter(BuiltInParameter.ROOM_DEPARTMENT) == null) { nombreerreur += 1; continue; } string lotpiece = piece.get_Parameter(BuiltInParameter.ROOM_DEPARTMENT).AsString(); //on verifie si le parametre "Service" n'est pas vide if (lotpiece == "") { nombreerreur += 1; continue; } ElementId levelpieceid = piece.LevelId; Element levelpiece = doc.GetElement(levelpieceid); double surfacepiece = piece.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble(); surfacepiece = UnitUtils.ConvertFromInternalUnits(surfacepiece, DisplayUnitType.DUT_SQUARE_METERS); surfacepiece = Math.Round(surfacepiece, 2); string nompiece = piece.Name; //ANALYSE //NOUVEAU LOT DE PIECE POUR SURFACE LOT ET BUREAU if (dicolotsurface.ContainsKey(lotpiece) == false) { List <double> listetriplezero = new List <double> { 0.00, 0.00, 0.00 }; dicolotsurface.Add(lotpiece, listetriplezero); dicolotsurface[lotpiece][0] += surfacepiece; //SI LA PIECE EST UN BUREAU if (nompiece.Contains("BUREAU") | nompiece.Contains("Bureau") | nompiece.Contains("bureau")) { dicolotsurface[lotpiece][1] += surfacepiece; } //SI LA PIECE EST UNE SALLE DE REUNION else if (nompiece.Contains("reunion") | nompiece.Contains("REUNION") | nompiece.Contains("réunion")) { dicolotsurface[lotpiece][2] += surfacepiece; } } //LOT DEJA VU else { // dicolotsurface[lotpiece][0] += surfacepiece; if (nompiece.Contains("BUREAU") | nompiece.Contains("Bureau") | nompiece.Contains("bureau")) { dicolotsurface[lotpiece][1] += surfacepiece; } else if (nompiece.Contains("réunion") | nompiece.Contains("REUNION") | nompiece.Contains("reunion")) { dicolotsurface[lotpiece][2] += surfacepiece; } } // SI NOUVEL ETAGE DICO SURFACE ETAGE ET BUREAU REU if (dicolevelsurface.ContainsKey(levelpieceid) == false) { List <double> listedoublezero = new List <double> { 0.00, 0.00 }; dicolevelsurface.Add(levelpieceid, listedoublezero); if (nompiece.Contains("BUREAU") | nompiece.Contains("Bureau") | nompiece.Contains("bureau")) { dicolevelsurface[levelpieceid][0] += surfacepiece; } else if (nompiece.Contains("reunion") | nompiece.Contains("REUNION") | nompiece.Contains("réunion")) { dicolevelsurface[levelpieceid][1] += surfacepiece; } } else { if (nompiece.Contains("BUREAU") | nompiece.Contains("Bureau") | nompiece.Contains("bureau")) { dicolevelsurface[levelpieceid][0] += surfacepiece; } else if (nompiece.Contains("reunion") | nompiece.Contains("REUNION") | nompiece.Contains("réunion")) { dicolevelsurface[levelpieceid][1] += surfacepiece; } } // SURFACE ETAGE LOT if (dicolotlevel.ContainsKey(levelpieceid) == false) { Dictionary <string, double> nvletage = new Dictionary <string, double>(); nvletage.Add(lotpiece, surfacepiece); dicolotlevel.Add(levelpieceid, nvletage); } else { if (dicolotlevel[levelpieceid].ContainsKey(lotpiece)) { dicolotlevel[levelpieceid][lotpiece] += surfacepiece; } else { dicolotlevel[levelpieceid].Add(lotpiece, surfacepiece); } } } catch (Exception e) { string meser = e.Message; if (messageerreur.Contains(meser) != true) { messageerreur.Add(meser); } nombreerreur += 1; } } } if (nombreerreur != 0) { foreach (string erreur in messageerreur) { TaskDialog.Show("Erreur lors de la récupération des pièces", " Message d'erreur :" + Environment.NewLine + string.Format("{0}", erreur)); } } return(dicolotsurface, dicolevelsurface, dicolotlevel); }
/// <summary> /// Convert a value to revit display unit /// </summary> /// <param name="value">Value</param> /// <param name="unit">Unit</param> /// <returns>Value in revit internal unit</returns> internal static double ToDisplay(this double value, DisplayUnitType unit) { return(UnitUtils.ConvertFromInternalUnits(value, unit)); }